C++ 如何将 OpenCV Mat 的所有像素设置为特定值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20816955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:19:50  来源:igfitidea点击:

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

c++opencvmatrix

提问by Drew Noakes

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

我有一个类型的图像CV_8UC1。如何将所有像素值设置为特定值?

回答by herohuyongtao

  • 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));
    
  • 对于灰度图像:

    cv::Mat m(100, 100, CV_8UC1); //gray 
    m = Scalar(5);  //used only Scalar.val[0] 
    

    或者

    cv::Mat m(100, 100, CV_8UC1); //gray 
    m.setTo(Scalar(5));  //used only Scalar.val[0] 
    

    或者

    Mat mat = Mat(100, 100, CV_8UC1, cv::Scalar(5));
    
  • 对于彩色图像(例如 3 个通道)

    cv::Mat m(100, 100, CV_8UC3); //3-channel 
    m = Scalar(5, 10, 15);  //Scalar.val[0-2] used 
    

    或者

    cv::Mat m(100, 100, CV_8UC3); //3-channel 
    m.setTo(Scalar(5, 10, 15));  //Scalar.val[0-2] used 
    

    或者

    Mat mat = Mat(100, 100, CV_8UC3, cv::Scalar(5,10,15));
    


P.S.: Check out this threadif you further want to know how to set given channel of a cv::Matto a given value efficiently without changing other channels.

PS:如果您想进一步了解如何在不更改其他通道的情况下有效地将 a 的给定通道设置为给定值,请查看此线程cv::Mat

回答by Drew Noakes

The assignment operator for cv::Mathas been implemented to allow assignment of a cv::Scalarlike this:

cv::Mat已经实现了赋值运算符,以允许cv::Scalar像这样赋值:

// 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 documentationdescribes:

文档描述:

Mat& Mat::operator=(const Scalar& s)

s – Scalar assigned to each matrix element. The matrix size or type is not changed.

Mat& Mat::operator=(const Scalar& s)

s – 分配给每个矩阵元素的标量。矩阵大小或类型不会改变。

回答by Haris

In another way you can use

以另一种方式,您可以使用

Mat::setTo

垫::设置为

Like

喜欢

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