simone
simone

Reputation: 5227

How to find dots with OpenCV in Python?

I'm just starting with OpenCV so this question is more like "what do you call the thing in OpenCV that does..." than "how do you do the thing..." - if I know what to look for usually docs and more googling go a long way.

So: using OpenCV in Python how could I find the position of all the black dots at the border between red and gray?

It's a nice to have if it is possible to tell if the border is horizontal or vertical or alternatively its angle at the point.

enter image description here

In other words - the position of the dots inside the white borders, but not the ones in the greyed out area:

enter image description here

Upvotes: 2

Views: 695

Answers (1)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15405

Some setup:

im = cv.imread("4V56c.png")
hsv = cv.cvtColor(im, cv.COLOR_BGR2HSV)

Dots:

# axis=2 is the color dimension. all values must be at most 30.
# result is a boolean array (0 or 1). times 255 because of reasons.
dots = (im <= 30).all(axis=2) * np.uint8(255)

dots

Border:

# a certain saturation
mask = (hsv[:,:,1] >= 50) * np.uint8(255)
# erase all the gray stuff
mask = cv.morphologyEx(src=mask, op=cv.MORPH_CLOSE, kernel=None, iterations=5)
# blow up and shrink
dilated = cv.dilate(mask, kernel=None, iterations=5)
eroded = cv.erode(mask, kernel=None, iterations=5)
# difference
border = dilated & ~eroded

border

Combined:

dots & border

dots & border

Upvotes: 3

Related Questions