我需要从灰度图像创建一个“红色”图像.我正在使用这段代码:
void build_red(const cv::Mat& in,cv::Mat& out) { out = Mat::zeros(in.rows,in.cols,CV_8UC1); Mat zeros = Mat::zeros(in.rows,CV_8UC1); Mat tmp; in.convertTo(tmp,CV_8UC1); vector<Mat> ch; ch.push_back(zeros); ch.push_back(zeros); ch.push_back(tmp); cout << "Using " << ch.size() << " channels" << endl; merge(ch,out); } // build_red
有一些解释:
void build_red(const cv::Mat& in,cv::Mat& out) {
in是输入矩阵,输出.
out = Mat::zeros(in.rows,CV_8UC1);
分配一些空间(可能是无用的,但我的尝试的一部分)
Mat zeros = Mat::zeros(in.rows,CV_8UC1);
创建一个具有相同大小的空矩阵,并将输入图像转换为单通道uchar.
vector<Mat> ch; ch.push_back(zeros); ch.push_back(zeros); ch.push_back(tmp); cout << "Using " << ch.size() << " channels" << endl; merge(ch,out);
创建一个带有三个通道的向量,然后将它们合并成“out”.
但是,当我运行代码时,我会收到以下消息:
Using 3 channels
并有以下例外:
OpenCV Error: Bad number of channels (Source image must have 1,3 or 4 channels) in cvConvertImage,file /[...]/libs/OpenCV-2.4.0/modules/highgui/src/utils.cpp,line 611 terminate called after throwing an instance of 'cv::Exception' what(): /[...]/libs/OpenCV-2.4.0/modules/highgui/src/utils.cpp:611: error: (-15) Source image must have 1,3 or 4 channels in function cvConvertImage
你可以帮我吗?从我没有经验的观点来看,图像的类型是相同的,并且通道的数量是正确的.
@R_403_323@
如果您有灰度图像,您为什么要转换图像?
只需为蓝色和绿色创建相同大小的两个空矩阵.
您将输出矩阵定义为1个通道矩阵.您的输出矩阵必须至少包含3个通道. (蓝,绿,红).蓝色和绿色将完全清空,您将灰度图像作为输出图像的红色通道.
#include <opencv2/highgui/highgui.hpp> #include <stdio.h> using namespace std; using namespace cv; int main() { Mat img,g,fin_img; img = imread("Lenna.png",CV_LOAD_IMAGE_GRAYSCALE); vector<Mat> channels; g = Mat::zeros(Size(img.rows,img.cols),CV_8UC1); channels.push_back(g); channels.push_back(g); channels.push_back(img); merge(channels,fin_img); imshow("img",fin_img); waitKey(0); return 0; }