2

I just realised that there is nothing on the web, after much searching about how to access a pixel's intensity value in OpenCv. A grayscale image.

Most online searches are about how to access BGR values of a colour image, like this one: Accessing certain pixel RGB value in openCV

image.at<> is basically for 3 channels, namely the BGR, out of curiousity, is there another similar method from OpenCV of accessing a certain pixel value of a grayscale image?

Community
  • 1
  • 1
rockinfresh
  • 2,068
  • 4
  • 28
  • 46
  • possible duplicate of [accessing pixel value of gray scale image in OpenCV](http://stackoverflow.com/questions/17919399/accessing-pixel-value-of-gray-scale-image-in-opencv) – Rui Marques Jan 22 '14 at 15:46

4 Answers4

6

You can use image.at<uchar>(j,i) to acces a pixel value of a grayscale image.

Nallath
  • 2,100
  • 20
  • 37
4

cv::Mat::at<>() function is for every type of image, whether it is a single channel image or multi-channel image. The type of value returned just depends on the template argument provided to the function.

The value of grayscale image can be accessed like this:

//For 8-bit grayscale image.
unsigned char value = image.at<unsigned char>(row, column);

Make sure to return the correct data type depending on the image type (8u, 16u, 32f etc.).

sgarizvi
  • 16,623
  • 9
  • 64
  • 98
3
  • For IplImage* image, you can use

    uchar intensity = CV_IMAGE_ELEM(image, uchar, y, x);
    
  • For Mat image, you can use

    uchar intensity = image.at<uchar>(y, x);
    
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
-2

at(y,x)]++;

for(int i = 0; i < 256; i++)
    cout<<histogram[i]<<" ";

// draw the histograms
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound((double) hist_w/256);

Mat histImage(hist_h, hist_w, CV_8UC1, Scalar(255, 255, 255));

// find the maximum intensity element from histogram
int max = histogram[0];
for(int i = 1; i < 256; i++){
    if(max < histogram[i]){
        max = histogram[i];
    }
}

// normalize the histogram between 0 and histImage.rows

for(int i = 0; i < 255; i++){
    histogram[i] = ((double)histogram[i]/max)*histImage.rows;
}


// draw the intensity line for histogram
for(int i = 0; i < 255; i++)
{
    line(histImage, Point(bin_w*(i), hist_h),
                          Point(bin_w*(i), hist_h - histogram[i]),
         Scalar(0,0,0), 1, 8, 0);
}

// display histogram
namedWindow("Intensity Histogram", CV_WINDOW_AUTOSIZE);
imshow("Intensity Histogram", histImage);

namedWindow("Image", CV_WINDOW_AUTOSIZE);
imshow("Image", image);
waitKey();
return 0;

}