由于算法的需要,需要把彩色图像的R、G、B值分离出来,OpenCV中正好有split() 和 merge() 函数可以实现。
实验环境:VS2010 + OpenCV2.4.9
一、对单独彩色图片的RGB通道分离:
#include <iostream> #include "cv.h" #include "highgui.h" using namespace std; using namespace cv; int main(int argc,char* argv[]) { Mat img = imread("lena.jpg"/*,CV_LOAD_IMAGE_COLOR*/); Mat channel[3]; split(img,channel); imshow("original",img); imshow("B",channel[0]); imshow("G",channel[1]); imshow("R",channel[2]); //set blue channel to 0 channel[0] = Mat::zeros(img.rows,img.cols,CV_8UC1); //merge red and green channels merge(channel,3,img); imshow("R_G_merge",img); waitKey(0); return 1; }下面是实验图片:
第一张是原始图片:
二、对摄像头摄入视频帧的RGB彩色通道分离
int main(int argc,char* argv[]) { VideoCapture cap; cap.open(0); if(!cap.isOpened()) { exit(0); } cap.set(CV_CAP_PROP_FRAME_WIDTH,250); cap.set(CV_CAP_PROP_FRAME_HEIGHT,250); cout << "Frame Width: " << cap.get(CV_CAP_PROP_FRAME_WIDTH) << endl; cout << "Frame Height: " << cap.get(CV_CAP_PROP_FRAME_HEIGHT) << endl; Mat frame; vector<Mat> rgb; cap >> frame; //rgb.push_back( Mat(frame.rows, frame.cols, CV_8UC1)); //rgb.push_back( Mat(frame.rows, frame.cols, CV_8UC1)); //rgb.push_back( Mat(frame.rows, frame.cols, CV_8UC1)); //rgb.push_back( Mat(frame.rows, frame.cols, CV_8UC1)); namedWindow("original", 1); namedWindow("red", 1); namedWindow("green", 1); namedWindow("blue", 1); for(;;) { cap >> frame; imshow("original", frame); split(frame, rgb); imshow("red", rgb.at(2)); imshow("green", rgb.at(1)); imshow("blue", rgb.at(0)); if(waitKey(30) >= 0) break; } waitKey(0); return 1; }
上帝之手,O(∩_∩)O哈哈~