Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill Matrix with zeros in OpenCV?

The code below causes an exception. Why?

#include <opencv2/core/core.hpp> #include <iostream>  using namespace cv; using namespace std;  void main() {      try {         Mat m1 = Mat(1,1, CV_64F, 0);         m1.at<double>(0,0) = 0;     }     catch(cv::Exception &e) {         cerr << e.what() << endl;     }  } 

Error is follows:

OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] && (unsigned)(i1*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channels()) && ((((sizeof(size_t)<<28)|0x8442211) >> ((DataType<_Tp>::depth) & ((1 << 3 ) - 1))*4) & 15) == elemSize1()) in unknown function, file %OPENCV_DIR%\build\include\opencv2\core\mat.hpp, line 537 

UPDATE

If tracing this code, I see that constructor line calls the constructor

inline Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step) 

Why? This prototype has 5 parameters, while I am providing 4 arguments.

like image 989
Suzan Cioc Avatar asked Jun 11 '13 10:06

Suzan Cioc


People also ask

What is CV_32F?

CV_32F : 4-byte floating point ( float ).

What is CV_64FC1?

That is, image of type CV_64FC1 is simple grayscale image and has only 1 channel: image[i, j] = 0.5. while image of type CV_64FC3 is colored image with 3 channels: image[i, j] = (0.5, 0.3, 0.7) (in C++ you can check individual pixels as image.at<double>(i, j) ) CV_64F is the same as CV_64FC1 .

What is scalar OpenCV?

ScalarRepresents a 4-element vector. The type Scalar is widely used in OpenCV for passing pixel values. In this tutorial, we will use it extensively to represent BGR color values (3 parameters). It is not necessary to define the last argument if it is not going to be used.

What is mat in OpenCV?

The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.


2 Answers

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.

like image 67
juanchopanza Avatar answered Sep 19 '22 04:09

juanchopanza


use cv::mat::setto

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

like image 35
GPPK Avatar answered Sep 17 '22 04:09

GPPK