2
votes

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?

1
have a look at docs.opencv.org/modules/core/doc/… but you would have to convert widthheight 3-channel-elements in widthheight*channel matrix first - Micka
How can I do the conversion, could you be more explicit? My be with Mat::reshape(), but in that case the matrix must satisfy Mat::IsCountinuous(). - Raul Alonso

1 Answers

2
votes

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