1

I'm new to opencv using python, so please bear with me. I have a tray with different sizes of circles like in the link. https://is.alicdn.com/img/pb/810/421/429/429421810_364.jpg This is not the actual image I have, but it is very similar to the one above. I have to detect the tray in the image and find the contours for all the holes (circles) in the tray. The tray might be tilted depending on the user taking the image. So far, I used a Gaussian blur and canny edge detection on the image, and closed the gaps in the canny edge detection. This is the image after Canny Edge Detection After Canny Edge Detection This is the image after morphology. After morphology Then I used findcontours and tried to find the largest contour with 4 vertices, which would ideally be the tray itself. The contour detection is only able to identify the left vertical border and top horizontal border. It is not able to recognize the 4 edges of the tray.

This is my code so far:

import numpy as np
import cv2
import matplotlib.pyplot as plt

image = cv2.imread("img.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.GaussianBlur(image, (3, 3), 0)
image_canny = cv2.Canny(image, 30, 200)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
gaps_closed = cv2.morphologyEx(image_canny, cv2.MORPH_CLOSE, kernel)
_, contours, _= cv2.findContours(gaps_closed.copy(), cv2.RETR_TREE, 
cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key = cv2.contourArea, reverse = True)
[:5]
Cnt = None
for c in contours:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)

    if len(approx) == 4:
        Cnt = approx
        break

cv2.drawContours(image, [Cnt], -1, (0, 255, 0), 4)
plt.imshow(image)
plt.show()
4

2 回答 2

0

调整 cv2.canny 的参数应该可以更容易地检测托盘的边缘。但是,使用 cv2.HoughLines 可能是检测托盘的更好方法,因为 HoughLines 并不要求检测到完整的边缘。

于 2017-06-29T05:02:55.900 回答
0

对输入执行直方图均衡应该可以提高图像的对比度。这将改善图像中的边缘检测。

由于图像中的孔看起来很小,形态学操作可能不是要走的路。这将掩盖这些孔,您可能无法将它们取回。

Opencv 有霍夫圆变换的实现。这是一个示例的python教程:http: //docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html。使用它应该可以解决您的问题。

如果这不起作用,发布您的实际输入图像会有所帮助

于 2017-06-29T18:56:32.370 回答