Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

c++ - accessing pixel value of gray scale image in OpenCV

I just want to get my concept clear that - is accessing all the matrix elements of cv::Mat means I am actually accessing all the pixel values of an image (grayscale - 1 channel and for colour - 3 channels)? Like suppose my code for printing the values of matrix of gray scale that is 1 channel image loaded and type CV_32FC1, is as shown below, then does that mean that I am accessing only the members of the cv::mat or I am accessing the pixel values of the image (with 1 channel - grayscale and type CV_32FC1) also?

    cv::Mat img = cv::imread("lenna.png");
    for(int j=0;j<img.rows;j++) 
    {
    for (int i=0;i<img.cols;i++)
      {
        std::cout << "Matrix of image loaded is: " << img.at<uchar>(i,j);
      }
    }

I am quite new to image processing with OpenCV and want to clear my idea. If I am wrong, then how can I access each pixel value of an image?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are accessing the elements of the matrix and you are accessing the image itself also. In your code, after you do this:

 cv::Mat img = cv::imread("lenna.png");

the matrix img represents the image lenna.png. ( if it is successfully opened )

Why don't you experiment yourself by changing some of the pixel values:

 cv::Mat img = cv::imread("lenna.png");
//Before changing
cv::imshow("Before",img);
//change some pixel value
for(int j=0;j<img.rows;j++) 
{
  for (int i=0;i<img.cols;i++)
  {
    if( i== j)   
       img.at<uchar>(j,i) = 255; //white
  }
}
//After changing
cv::imshow("After",img);

Note: this only changes the image values in volatile memory, that is where the mat img is currently loaded. Modifying the values of the mat img, not going to change value in your actual image "lenna.png",which is stored in your disk, (unless you do imwrite)

But in case of 1-channel grayscale image it is CV_8UC1 not CV_32FC1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...