opencv保存png alpha通道的办法

We are currently facing the situation that we need to process PNG files that contain an alpha channel. Unfortunately OpenCV curently does not support so (but there’s a hack – but that didn’t help in my situation). The documentation for cvLoadImage contains a sad little note:

Note that in the current implementation the alpha channel, if any, is stripped from the output image, e.g. 4-channel RGBA image will be loaded as RGB.

Diving into the code I figured alpha channels have been disabled on purpose. Around line 220 in grfmt_png.cpp (the respective PNG encoder / decoder) it reads: png_set_strip_alpha( png_ptr ).

So the hope would be, if one disables this line libpng should be able to read in the alpha channel. Indeed it does, if you specify  a large enough buffer to write in (CV_8UC4 instead of CV_8UC3). So we need  a few more patches to make it work throughout:
1. In grfmt_ png.cpp, line 170 add  a line that allows to push through the type (alpha channel) detection: 
// Allow for PNG alpha channel here
if(color_type == PNG_COLOR_TYPE_RGB_ALPHA) { m_type = CV_8UC4;
}

2. In grfmt_png.cpp, around line 220 allow for an alpha channel by commenting the following statements:

//png_set_strip_alpha( png_ptr );
3. In loadsave.cpp , line 222 we finally tweak the parent routine to be more flexible towards the channels returned. Here we replace the “3″ by CV_MAT_CN(type):
type = CV_MAKETYPE(CV_MAT_DEPTH(type), CV_MAT_CN(type));
(Note all changes were performed against  OpenCV 2.0)

After a recompile you should be able to read alpha-channeled pngs as well!

转载于:https://my.oschina.net/userlocal/blog/33311

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值