Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...