I have an image of type CV_8UC1
. How can I set all pixel values to a specific value?
Vec3b is the abbreviation for "vector with 3 byte entries" Here those byte entries are unsigned char values to represent values between 0 .. 255. Each byte typically represents the intensity of a single color channel, so on default, Vec3b is a single RGB (or better BGR) pixel.
The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.
There are three channels in an RGB image- red, green and blue. The color space where red, green and blue channels represent images is called RGB color space. In OpenCV, BGR sequence is used instead of RGB. This means the first channel is blue, the second channel is green, and the third channel is red.
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));
P.S.: Check out this thread if you further want to know how to set given channel of a cv::Mat
to a given value efficiently without changing other channels.
In another way you can use
Mat::setTo
Like
Mat src(480,640,CV_8UC1);
src.setTo(123); //assign 123
The assignment operator for cv::Mat
has been implemented to allow assignment of a cv::Scalar
like this:
// Create a greyscale image
cv::Mat mat(cv::Size(cols, rows), CV_8UC1);
// Set all pixel values to 123
mat = cv::Scalar::all(123);
The documentation describes:
Mat& Mat::operator=(const Scalar& s)
s – Scalar assigned to each matrix element. The matrix size or type is not changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With