machinevision-toolbox-python icon indicating copy to clipboard operation
machinevision-toolbox-python copied to clipboard

Fix blob error for single pixels

Open Tjeard0 opened this issue 2 years ago • 4 comments

Some blobs were being created that were one pixel in size causing the code:

blob.uc = M.m10 / M.m00

for the centroid to throw a division by zero error.

Added in code to prevent the blob being appended when the value of m00 is zero

Tjeard0 avatar Nov 26 '23 07:11 Tjeard0

Hi @petercorke - could you please take a look at this? We've had some issues in EGB339 because of it, and it's a straightforward fix.

Many thanks!

Tobias-Fischer avatar Dec 19 '23 02:12 Tobias-Fischer

There must be something else going on here, for a single pixel blob m00 should be one.

petercorke avatar Dec 19 '23 04:12 petercorke

There's a bit of online chatter about this, m00=0 can happen for some malformed contours. See https://stackoverflow.com/questions/62392240/opencv-cv2-moments-returns-all-moments-to-zero and https://github.com/opencv/opencv/issues/7962

petercorke avatar Dec 19 '23 04:12 petercorke

Hi @petercorke - I've had a closer look at this. The StackOverflow you linked to contains this important detail:

That means, if you have a 2 by 2 pixel rectangle, you get contour points on those border pixels, say (1,1), (2,1), (2,2), (1,2). The area of that is just 1 (taken as a mathematical polygon), when it should have been 4 (in OpenCV's notion of a contour). For a plain line, same thing, but now you've got zero area.

So for a single-pixel line (or even a single-pixel dot), OpenCV returns m00=0. I think the cleaner solution is to follow the OpenCV tutorials and avoid division by zero using some epsilon: https://docs.opencv.org/4.9.0/d0/d49/tutorial_moments.html

What do you think?

Tobias-Fischer avatar Feb 29 '24 00:02 Tobias-Fischer

accepted with some enhanced comment, need to fix the CI, then will send to PyPi

petercorke avatar May 26 '24 02:05 petercorke

Hi @petercorke - thanks for looking at this! It seems like the change hasn’t ended up in the main branch, unless I’m overseeing something?

Tobias-Fischer avatar May 26 '24 06:05 Tobias-Fischer