opencvsplitbgr

split a BGR matrix without use split() function


I am programming with Visual Studio 2012 and the Opencv library, in the 2.4.6 version.

Someone can help me about splitting a BGR image into three images, one for every channel?

I know that there is the split function in OpenCV, but it causes me an unhandled exception, probably because I have a 64 bit processor with the 32 bit library, or probably it's the version of the library, so I want to know how to iterate on the pixel values of a BGR matrix without use split().

Thanks in advance.


Solution

  • If you don't want to use split() then you can read each r,g,b pixel value from your source image and write to destination image and which should be single channel.

    #include <stdio.h>
    #include <opencv2/opencv.hpp>
    #include <iostream>
    
    using namespace cv;
    using namespace std;
    
    
    int main( int argc, const char** argv ){
    
     Mat src = imread("ball.jpg", 1);
     Mat r(src.rows,src.cols,CV_8UC1);
     Mat g(src.rows,src.cols,CV_8UC1);
     Mat b(src.rows,src.cols,CV_8UC1);
    
     for(int i=0;i<src.rows;i++){
      for(int j=0;j<src.cols;j++){
        Vec3b pixel = src.at<Vec3b>(i, j);
        b.at<uchar>(i,j) = pixel[0];
        g.at<uchar>(i,j) = pixel[1];
        r.at<uchar>(i,j) = pixel[2];
       }
      }
    
      imshow("src", src);
      imshow("r", r);
      imshow("g", g);
      imshow("b", b);
    
      waitKey(0);
     }