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

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.


In another way you can use

Mat::setTo

Like

      Mat src(480,640,CV_8UC1);
      src.setTo(123); //assign 123

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

Tags:

C++

Matrix

Opencv