Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all pixels of an OpenCV Mat to a specific value?

Tags:

c++

opencv

matrix

I have an image of type CV_8UC1. How can I set all pixel values to a specific value?

like image 269
Drew Noakes Avatar asked Dec 28 '13 16:12

Drew Noakes


People also ask

What is Vec3b?

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.

What is mat type in OpenCV?

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.

What are channels in OpenCV?

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.


3 Answers

  • 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.

like image 118
herohuyongtao Avatar answered Nov 09 '22 23:11

herohuyongtao


In another way you can use

Mat::setTo

Like

      Mat src(480,640,CV_8UC1);
      src.setTo(123); //assign 123
like image 43
Haris Avatar answered Nov 10 '22 01:11

Haris


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.

like image 22
Drew Noakes Avatar answered Nov 10 '22 00:11

Drew Noakes