#include<opencv2/opencv.hpp> #include<iostream> #include<cassert> #include<vector> using namespace cv; using namespace std; int main() { Mat srcImage=imread("e:/huangshan.jpg"); Mat imageBlue,imageGreen,imageRed; Mat mergeImage; //定义一个Mat向量容器保存拆分后的数据 vector<Mat> channels; //判断文件加载是否正确 assert(srcImage.data!=NULL); namedWindow("image",CV_WINDOW_AUTOSIZE); namedWindow("mergeImage",CV_WINDOW_AUTOSIZE); //通道的拆分 split(srcImage,channels); //提取蓝色通道的数据 imageBlue = channels.at(0); //提取绿色通道的数据 imageGreen = channels.at(1); //提取红色通道的数据 imageRed = channels.at(2); imshow("image",imageBlue); //对拆分的通道数据合并 merge(channels,mergeImage); imshow("mergeImage",mergeImage); waitKey(); system("pause"); return 0; }
int main() { Mat srcImage = imread("e:/image/1740156366.jpg"); Mat imageBlue, imageGreen, imageRed; Mat mergeImage; //定义一个Mat向量容器保存拆分后的数据 vector<Mat> channels; //判断文件加载是否正确 assert(srcImage.data != NULL); namedWindow("image", CV_WINDOW_AUTOSIZE); namedWindow("mergeImage", CV_WINDOW_AUTOSIZE); //通道的拆分 split(srcImage, channels); //提取蓝色通道的数据 imageBlue = channels.at(0); //提取绿色通道的数据 imageGreen = channels.at(1); //提取红色通道的数据 imageRed = channels.at(2); imshow("image", imageBlue); //对拆分的通道数据合并 merge(channels, mergeImage); imshow("mergeImage1", mergeImage); waitKey(); //定义一个Mat向量容器保存拆分后的数据 vector<Mat> channels2; channels2.push_back(imageBlue); channels2.push_back(imageBlue); channels2.push_back(imageBlue); //对拆分的通道数据合并 merge(channels2, mergeImage); imshow("mergeImage2", mergeImage); //The effect is the same? waitKey(); waitKey(); system("pause"); return 0; }
OpenCV单通道图像保存后为何再载入还是3通道的?
用OpenCV打开一幅3通道的图形,用cvtColor(image,result,COLOR_BGR2GRAY)函数将image转换为灰度图,
并用std::cout<<"channnels : "<<result.channels(); 语句确认了channel为1,
用imwrite("single.bmp",result)或imwrite("single.jpg",result)语句将单通道图像保存为单通道后,
再用image2=imread()重新加载single.bmp或single.jpg,结果图像又是3通道的了,这是怎么回事呢?
猜测你后面去读图像的时候应该使用的是imread()函数的第二个参数使用的是默认值,那么这个时候都是以color形式读取的,所有就又变回3通道了;下面是第二个参数的介绍
flags – Flags specifying the color type of a loaded image:
– CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has
the corresponding depth, otherwise convert it to 8-bit.
– CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
– CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one
如果你想读取图像的原样,建议使用如下:"..."替换为自己的图像
Mat test = imread("...", -1);
请教怎么把单通道保存为jpg的图片啊? 先存为灰度,再转为RGB
扫描二维码关注公众号,回复:
763344 查看本文章