Ask Your Question

How to initialize a Mat object with zeros

asked 2016-10-11 02:04:26 -0500

AMEMB gravatar image

I want to create a Mat object initially initialized with zeros, and i want to avoid doing that using two nested for-loops. is there any alternative solution to the one posted below?


this.mDest = new Mat(this.mMatEdges.rows(), this.mMatEdges.cols(), CvType.CV_8U);
    for (int i =  0; i < this.mMatEdges.size().height; i++) {
        for (int j = 0; j < this.mMatEdges.size().width; j++) {
            this.mDest.put(i, j, 0);
edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2016-10-11 02:14:56 -0500

berak gravatar image

there is a simple constructor for that:

this.mDest = new Mat(this.mMatEdges.rows(), this.mMatEdges.cols(), CvType.CV_8U, Scalar.all(0));
edit flag offensive delete link more


looking at guidovitales answer I have to ask is there a difference between your Solution ans his? e.g. Runtime difference or result differences? just curious about that.

Vintez gravatar imageVintez ( 2016-10-11 04:01:09 -0500 )edit

@Vintez , no difference at all (just 2 api calls doing the same thing)

berak gravatar imageberak ( 2016-10-11 04:18:35 -0500 )edit

answered 2016-10-11 02:16:02 -0500

guidovitale gravatar image

updated 2016-10-11 02:19:27 -0500

berak gravatar image

for a grayscale image this should work (works for me, I use openCV 3.0):

 Mat zeroMat = Mat.zeros(n_rows, n_cols, CvType.CV_8UC1);

where n_rows and n_cols are the number of rows and colums (thus, int) respectively. if your image is not grayscale, change the last entry.

edit flag offensive delete link more


thanks for your nice answer, hope you don't mind my little edit (making it more "java") ;)

berak gravatar imageberak ( 2016-10-11 02:20:20 -0500 )edit

thanks for the editing!

guidovitale gravatar imageguidovitale ( 2016-10-11 02:33:02 -0500 )edit

Question Tools

1 follower


Asked: 2016-10-11 02:04:26 -0500

Seen: 22,199 times

Last updated: Oct 11 '16