How to fill Matrix with zeros in OpenCV?

前端 未结 8 936
-上瘾入骨i
-上瘾入骨i 2020-12-15 03:36

The code below causes an exception. Why?

#include 
#include 

using namespace cv;
using namespace std;

void mai         


        
相关标签:
8条回答
  • 2020-12-15 04:16

    How to fill Matrix with zeros in OpenCV?

    To fill a pre-existing Mat object with zeros, you can use Mat::zeros()

    Mat m1 = ...;
    m1 = Mat::zeros(1, 1, CV_64F);
    

    To intialize a Mat so that it contains only zeros, you can pass a scalar with value 0 to the constructor:

    Mat m1 = Mat(1,1, CV_64F, 0.0);
    //                        ^^^^double literal
    

    The reason your version failed is that passing 0 as fourth argument matches the overload taking a void* better than the one taking a scalar.

    0 讨论(0)
  • 2020-12-15 04:17

    use cv::mat::setto

    img.setTo(cv::Scalar(redVal,greenVal,blueVal))

    0 讨论(0)
  • 2020-12-15 04:17

    If You are more into programming with templates, You may also do it this way...

    template<typename _Tp>
    ... some algo ...
    cv::Mat mat = cv::Mat_<_Tp>::zeros(rows, cols);
    mat.at<_Tp>(i, j) = val;
    
    0 讨论(0)
  • 2020-12-15 04:21

    You can choose filling zero data or create zero Mat.

    1. Filling zero data with setTo():

      img.setTo(Scalar::all(0));
      
    2. Create zero data with zeros():

      img = zeros(img.size(), img.type());
      

    The img changes address of memory.

    0 讨论(0)
  • 2020-12-15 04:21

    I presume you are talking about filling zeros of some existing mat? How about this? :)

    mat *= 0;

    0 讨论(0)
  • 2020-12-15 04:26

    You can use this to fill zeroes in a Mat object already containing data:

    image1 = Scalar::all(0);
    

    For eg, if you use it this way:

    Mat image,image1;
    image = imread("IMG_20160107_185956.jpg", CV_LOAD_IMAGE_COLOR);   // Read the file
    
    if(! image.data )                              // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }
    cvtColor(image,image1,CV_BGR2GRAY);
    image1 = Scalar::all(0);
    

    It will work fine. But you cannot use this for uninitialised Mat. For that you can go for other options mentioned in above answers, like

    Mat drawing = Mat::zeros( image.size(), CV_8UC3 );
    
    0 讨论(0)
提交回复
热议问题