Cycle through pixels with opencv

后端 未结 7 2205
情深已故
情深已故 2020-12-07 17:46

How would I be able to cycle through an image using opencv as if it were a 2d array to get the rgb values of each pixel? Also, would a mat be preferable over an iplimage for

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 18:44

    cv::Mat is preferred over IplImage because it simplifies your code

    cv::Mat img = cv::imread("lenna.png");
    for(int i=0; i(i,j)[0] << " " << img.at(i,j)[1] << " " << img.at(i,j)[2] << std::endl;
    

    This assumes that you need to use the RGB values together. If you don't, you can uses cv::split to get each channel separately. See etarion's answer for the link with example.

    Also, in my cases, you simply need the image in gray-scale. Then, you can load the image in grayscale and access it as an array of uchar.

    cv::Mat img = cv::imread("lenna.png",0);
    for(int i=0; i(i,j) << std::endl;
    

    UPDATE: Using split to get the 3 channels

    cv::Mat img = cv::imread("lenna.png");
    std::vector three_channels = cv::split(img);
    
    // Now I can access each channel separately
    for(int i=0; i(i,j) << " " << three_channels[1].at(i,j) << " " << three_channels[2].at(i,j) << std::endl;
    
    // Similarly for the other two channels
    

    UPDATE: Thanks to entarion for spotting the error I introduced when copying and pasting from the cv::Vec3b example.

提交回复
热议问题