简体   繁体   中英

Maximum single channel cv::Mat from multi channel cv::Mat

I am using opencv through the C++ interface. I have a cv::Mat m1 representing a multi channel image, from which I need to obtain a single channel image m2 where a pixel has as value the maximum among all the values of the corresponding pixel in m1 (a pixel in m1 has multiple values, one for each channel). Does anybody know the most efficient way to obtain m2 from m1 ?

You can accomplish this using cv::reduce() and Mat::reshape() . The key is to reshape m1 into a single-channel image where each element of a row represents one color component. You can do this via m1.reshape(1, m1.total()) . Then applying reduce() will give a Mat containing the maximum component value, and then it is a simple matter to reshape the result to give the shape of m1 . A simple example follows:

uchar data[] = {1,2,3, 3,1,2, 2,1,3, 3,2,1};
cv::Mat m1(2,2, CV_8UC3, data); // Maximum component value is 3 for all pixels
cv::Mat m2;
cv::reduce(m1.reshape(1, m1.total()), m2, 1, CV_REDUCE_MAX);
m2 = m2.reshape(0, m1.cols); // 2x2 Mat, all elements are 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM