Ask Your Question
0

Access channels of CV_8UC Image

asked 2016-12-28 05:03:03 -0600

atp gravatar image

updated 2016-12-28 05:03:37 -0600

I want to convert a float matrix to an unsigned char matrix with the same number of channels.

cv::Mat imgA(3, 3, CV_32FC(5));
// image is filled with something
cv::Mat imgB;
imgA.convertTo(imgB, CV_8UC(imgA.channels()));

How can the additional channels of a CV_8UC image be accessed? The following gives a segmentation fault.

std::cout << (int) imgB.at<uchar>(0,0,1) << "\n";
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-12-28 05:24:21 -0600

berak gravatar image

updated 2016-12-28 05:32:56 -0600

convertTo only changes the depth of the image, not the channels, so rather call it like:

imgA.convertTo(imgB, CV_8U);

if you need to access single pixels, you can add a new type for this:

typedef Vec<uchar,5> Vec5b;

for (int r=0; r<imgB.rows; r++) {
    for (int c=0; c<imgB.cols; c++) {
         Vec5b &pix = imgB.at<Vec5b>(r,c);
         cout << int(pix[0]) << ","; // without the cast, cout would try to print ascii bytes ;(
         cout << int(pix[1]) << ","
         cout << int(pix[2]) << ","
         cout << int(pix[3]) << ","
         cout << int(pix[4]) << ";";
    } 
    cout << endl;
}

but again, you also could simply print the whole Mat:

cout << imgB << endl;
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-12-28 05:03:03 -0600

Seen: 1,242 times

Last updated: Dec 28 '16