1. Access pixel value in Mat Image
For a single channel grey scale image (type 8UC1).
For a 3 channel image with BGR color ordering (the default format returned by imread):
The same method can be used to change pixel intensities:
2. How can I set all pixel values to a specific value?
-
For grayscale image:
cv::Mat m(100, 100, CV_8UC1); //gray m = Scalar(5); //used only Scalar.val[0]
or
cv::Mat m(100, 100, CV_8UC1); //gray m.setTo(Scalar(5)); //used only Scalar.val[0]
or
Mat mat = Mat(100, 100, CV_8UC1, cv::Scalar(5));
-
For colored image (e.g. 3 channels)
cv::Mat m(100, 100, CV_8UC3); //3-channel m = Scalar(5, 10, 15); //Scalar.val[0-2] used
or
cv::Mat m(100, 100, CV_8UC3); //3-channel m.setTo(Scalar(5, 10, 15)); //Scalar.val[0-2] used
or
Mat mat = Mat(100, 100, CV_8UC3, cv::Scalar(5,10,15));
For a 3-channel color image: use Range() function
img(Range(0, 1), Range(0, 1)) = Scalar(128, 128, 128);
Do NOT Use Range() function again!
Mat M = img(Range(10,10), Range(100,100)); // copy a rectangular part of Mat img to initialize a new Mat M.
Mat M(Range(10,10), Range(100,100)) = img(Range(10,10), Range(100,100)); // change pixel values of part of Mat M using a block of img
The code above cannot work because Range() is just copying the header of the matrix. We should use copyTo() instead.
img.copyTo(M(Rect(10, 10, width, height)));
Here, we should pay attention on usage of Rect. The first two input of Rect is the position of the left upper corner of ROI (Region of Interest). And the last two inputs are the width and height of ROI, not the position of right lower corner.