First time here? Check out the FAQ!

Ask Your Question
0

How to initialize a Mat object with zeros

asked Oct 11 '16

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?

code:

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);
        }
    }
Preview: (hide)

2 answers

Sort by » oldest newest most voted
1

answered Oct 11 '16

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));
Preview: (hide)

Comments

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 (Oct 11 '16)edit
1

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

berak gravatar imageberak (Oct 11 '16)edit
1

answered Oct 11 '16

guidovitale gravatar image

updated Oct 11 '16

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.

Preview: (hide)

Comments

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

berak gravatar imageberak (Oct 11 '16)edit
1

thanks for the editing!

guidovitale gravatar imageguidovitale (Oct 11 '16)edit

Question Tools

1 follower

Stats

Asked: Oct 11 '16

Seen: 25,395 times

Last updated: Oct 11 '16