Ask Your Question
0

compare/countNonZero return bigger value then expected

asked 2016-03-19 11:39:29 -0600

carobnodrvo gravatar image

If I take 2 binary images (pixel values 0 or 255) and compare them with compare/countNonZero and then with two nested loops I don't get same "score".

So first I use this code:

compare(mat1, mat2, mat_tmp, CMP_EQ);

score = countNonZero(mat_tmp);

and then this:

for (int x = 0; x < mat1.cols; ++x)
{
    for (int y = 0; y < mat2.rows; ++y)
    {
        Scalar s1 = mat1.at<uchar>(y,x);
        Scalar s2 = mat2.at<uchar>(y,x);
        score += (s1.val[0]/255)*(s2.val[0]/255);
    }
}

the score values are significantly different (e.g. compare/countNonZero score=206 814 and for nested loops is 1022).

Shouldn't it be same? Why is it so? Have I misunderstood something?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-03-19 12:02:09 -0600

berak gravatar image

updated 2016-03-19 12:03:59 -0600

imho, you're calculating something different, than compare() / countNonzero().

try:

uchar s1 = mat1.at<uchar>(y,x);
uchar s2 = mat2.at<uchar>(y,x);
score += (s1 == s2);

can you explain, how you arrived at:

score += (s1.val[0]/255)*(s2.val[0]/255);

?

edit flag offensive delete link more

Comments

That works and it's because compare/countNonZero count also where both matrices are 0 whereas nested loop doesn't.

Well pixel s1 or s2 can either be 0 or 255 so if they are both 255 I increase score by one and if they are 0 (or different) I don't count it. That was my logic.

One more question: Can I implement my logic from above with compare/countNonZero (currently I think no but I want to her another opinion)

carobnodrvo gravatar imagecarobnodrvo ( 2016-03-19 12:10:47 -0600 )edit
1

what you implemented is a (scaled) per-element-multiplication, not a comparison at all.

incase you need (an optimized version of) that, have a look at multiply

berak gravatar imageberak ( 2016-03-19 12:13:16 -0600 )edit

Many thanks kind Sir. That's the thing I needed.

carobnodrvo gravatar imagecarobnodrvo ( 2016-03-19 12:18:52 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-03-19 11:39:29 -0600

Seen: 155 times

Last updated: Mar 19 '16