利用 OpenCV 为 RGB 图像添加 alpha 值
主要是参考 opencv 文档,并留意一下 IplImage 的数据结构即可
#include <opencv/cxcore.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
int main(int argc,char** argv)
{
char filename[100];
for(int i = 0; i < 16; i++) {
sprintf(filename,"test_picture (%d).jpg",i);
IplImage* image = cvLoadImage(filename);
IplImage* dest_image = cvCreateImage(cvGetSize(image),image->depth,4);
for(int i =0; i < image->height; i++) {
uchar* img_dst = (uchar*)(image->imageData+image->widthStep*i);
uchar* dest_img_dst = (uchar*)(dest_image->imageData+dest_image->widthStep*i);
for(int j = 0; j < image->width; j++) {
dest_img_dst[4*j] = img_dst[3*j];
dest_img_dst[4*j+1] = img_dst[3*j+1];
dest_img_dst[4*j+2] = img_dst[3*j+2];
dest_img_dst[4*j+3] = 255;
}
}
sprintf(filename,"outfile_%d.bmp",i);
cvSaveImage(filename,dest_image);
}
return 0;
}
上述分为两步的原因主要是考虑到数据对齐,因为图像的宽度不一定都能被IplImage定义的格式整除,为此IplImage中的widthStep是用于数据对齐。因此,在每一行,先得到图像数据的行地址,然后再对这一行的数据进行操作,直至整个图像拷贝完。
OpenCV将IplImage存成QImage
一个可用思路是如上逐像素拷贝,但是那样效率慢。可以直接使用IplImage的imageData构造QImage。但是需要注意的是IplImage中存图像的顺序是BGR,而QImage等是使用RGB的存储方式,因此,需要先用cvConvertImage中使用SWAP_BR这个flag对OpenCV中的图像转换成RGB顺序,然后再用这个数据构造QImage