Search code examples
c++opencvmaskgrayscale

Getting maximum pixel value in grayscale image in opencv


After I do some image manipulation, and apply mask, I get what I want. I can clearly see on imshow result of "crop" that there's gray pixels in the middle of image. I'm trying to get the maximum pixel value location. I've checked the crop.channels(), which returns 1.

    Mat mask = drawing2;
    drawContours(mask, contours, -1, Scalar(255), CV_FILLED);
    Mat dist;
    distanceTransform( cannyInv, dist, CV_DIST_L2, 3 );
    normalize(dist,dist,0.0,1.0,NORM_MINMAX);
    Mat crop;
    dist.copyTo(crop, mask);
    cout << "max.. "<< *std::max_element(crop.begin<double>(),crop.end<double>()) <<endl;

which returns max.. 4.25593e-08

    for(int y = 0; y < crop.rows; y++)
    {
        for(int x = 0; x < crop.cols; x++)
        {
            if (crop.at<unsigned char>(x,y) > 0){      
                cout << "X........"<<x<<" Y......"<<y<< " = "<<crop.at<unsigned char>(x,y) <<endl;
            }
        }
    }

The output is:

X........604 Y......479 = ¿
X........607 Y......479 =   
X........610 Y......479 = ¿

Help me please

PD: I know that there's similar question. But this is specific problem.


Solution

  • I'm not sure how I solved it. A lot of time has passed. But the code that currently I have and it works is this:

        Mat dist=Mat::zeros(480,640, CV_8UC1);;
        distanceTransform( cannyInv, dist, CV_DIST_L2, 3 );
        Mat distNorm;
        dist.convertTo(distNorm, CV_8UC1,1,0);
        Mat result= Mat::zeros(480,640, CV_8UC1);
        distNorm.copyTo(result, mask);
        Mat tmp=Mat::zeros(480,640, CV_8UC1);
        Mat fik=Mat::zeros(480,640, CV_8UC3);
        for(int i = 0; i < result.rows; i++)
        {
            for(int j = 0; j < result.cols; j++)
            {
                if ( result.at< uchar >( i,j ) > 0){
                    uchar val = result.at< uchar >( i,j  );
                    if(val>maxVal){
                        if(val>0){
                            cv::circle(tmp,cvPoint(j,i),2,255,-1);
                        }
                        maxVal=val;
                        maxX = j;
                        maxY = i;
                    }
                }
            }
        }