23

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

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742

3 Answers3

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

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
10

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.

keineahnung2345
  • 2,635
  • 4
  • 13
  • 28
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 5
    since Scalar(123) only initializes the *1st* element of the Scalar, you probably want Scalar::all(123) , if the Mat has more than one channel. – berak Dec 28 '13 at 17:03
5

In another way you can use

Mat::setTo

Like

      Mat src(480,640,CV_8UC1);
      src.setTo(123); //assign 123
Haris
  • 13,645
  • 12
  • 90
  • 121