machinevision-toolbox-python
machinevision-toolbox-python copied to clipboard
Fix blob error for single pixels
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
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!
There must be something else going on here, for a single pixel blob m00 should be one.
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
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?
accepted with some enhanced comment, need to fix the CI, then will send to PyPi
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?