Y
Y
Yeldos Adetbekov2017-10-30 00:09:10
Python
Yeldos Adetbekov, 2017-10-30 00:09:10

How to split sticky contours in opencv?

Hello, there was a problem with coin recognition. Unable to separate stuck objects. I tried to change the parameters of the dilate(), erode() function. Detachable, but error occurs with other examples where there are overexposures (Where the core of the coin fades). I do closing () - stick.

import cv2
import numpy as np
from matplotlib import pyplot as plt
imgs = [ 
         "P1000697s.jpg", 
         "P1000698s.jpg", 
         "P1000699s.jpg", 
         "P1000703s.jpg", 
         "P1000705s.jpg", 
         "P1000706s.jpg", 
         "P1000709s.jpg",
         "P1000710s.jpg",
         "P1000713s.jpg"
       ]
img = cv2.imread("lab1assets/{img}".format(img = imgs[4]))
b,g,r = cv2.split(img)
blur = cv2.blur(r, (7, 7))
retval, threshold = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

plt.imshow(threshold, cmap="gray")
plt.show()

plt.subplot(3,1,2), plt.hist(img.ravel(), 256)
plt.axvline(x=retval, color='r', linestyle='dashed', linewidth=2)
plt.show()

print(retval)

59f642b3d8a5f857784661.png
kernelc = np.ones((1,1),np.uint8)
kernel = np.ones((20,20),np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

erosion = cv2.erode(threshold, element, iterations = 1)
dilation = cv2.dilate(erosion, element, iterations = 1)
# opening = cv2.morphologyEx(dilation, cv2.MORPH_OPEN, element)
closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, element)

plt.imshow(closing, cmap="gray")
plt.show()

59f642e759e42927363207.png
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
validc = []

for c in contours:
    m = cv2.moments(c)
    (x,y),radius = cv2.minEnclosingCircle(c)
    center = (int(x),int(y))
    radius = int(radius)
    if(m['m00'] <= 2*np.pi*np.square(61) and m['m00'] >= 3322):
        validc.append(c)
        cv2.circle(img,center,radius,(0,255,0),2)

# cv2.drawContours(img, validc,-1,(0,255,0),5)
cv2.putText(img,"Hello World!!!", (50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)

plt.imshow(img, cmap="gray")
plt.show()

59f6434fda1c7360556204.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fedor, 2017-11-02
@krox

Try to start the search for circles from the examples. It would be nice to post the original picture or a link to it so that you can try it yourself

R
Repulse, 2017-11-02
@Repulse

Here is a similar example:
https://docs.opencv.org/master/d3/db4/tutorial_py_...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question