Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute maximum pixel value of Mat in OpenCV [duplicate]

Tags:

c++

opencv

This should be obvious, I thought. But I can't find easy way to find maximum among all pixels in a Mat of OpenCV. Of course, I can do following for each pixel type. But general max function would be still useful.

double cvMax(cv::Mat& mat)
{
float max=0;
float* pData=(float*)mat.data;
for(int i=0;i<mat.rows;i++) 
{
    for(int j=0;j<mat.cols;j++)
    {
        float value = pData[j+i*mat.cols];
        if(value>max) 
        {
            max=value;
        }
    }
}
return max;
}
like image 771
Tae-Sung Shin Avatar asked Sep 20 '12 22:09

Tae-Sung Shin


People also ask

What is Max pixel value?

For most images, pixel values are integers that range from 0 (black) to 255 (white).

What is Vec3b?

Vec3b is the abbreviation for "vector with 3 byte entries" Here those byte entries are unsigned char values to represent values between 0 .. 255. Each byte typically represents the intensity of a single color channel, so on default, Vec3b is a single RGB (or better BGR) pixel.

What is CV_8UC3?

CV_8UC3 - 3 channel array with 8 bit unsigned integers. CV_8UC4 - 4 channel array with 8 bit unsigned integers. CV_8UC(n) - n channel array with 8 bit unsigned integers (n can be from 1 to 512) )

What is the use of mat in OpenCV?

The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.


1 Answers

cv::minMaxIdx is really simple to use. It looks complicated in the docs, but you can omit most of the parameters:

Mat m = ...;

double min, max;
minMaxIdx(m, &min, &max);

printf("min: %f, max: %f\n", min, max);

Moreover, cv::minMaxIdx is more than 10 times faster than std::max_element. This is because cv::minMaxIdx is optimized for handling cv::Mat data and it uses multiple threads if possible.

If you also need the locations of the minimum and maximum in the image, you can use cv::minMaxLoc.

like image 79
Daniel S. Avatar answered Oct 06 '22 05:10

Daniel S.