How to set all pixels of an OpenCV Mat to a specif

2020-05-20 03:57发布

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

3条回答
beautiful°
2楼-- · 2020-05-20 04:22
  • 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.

查看更多
放荡不羁爱自由
3楼-- · 2020-05-20 04:28

In another way you can use

Mat::setTo

Like

      Mat src(480,640,CV_8UC1);
      src.setTo(123); //assign 123
查看更多
狗以群分
4楼-- · 2020-05-20 04:32

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.

查看更多
登录 后发表回答