laser curved line detection using opencv and python

房东的猫 提交于 2019-12-22 18:29:10

问题


I have taken out the laser curve of this image :


(source: hostingpics.net)

And now, I'm trying to obtain a set of points (the more, the better), which are in the middle of this curve. I have tried to split the image into vertical stripes, and then to detect the centroid. But it doesn't calculate lots of points, and it's not satisfactory at all !

img = cv2.Canny(img,50,150,apertureSize = 3)
sub = 100
step=int(img.shape[1]/sub)
centroid=[]
for i in range(sub):
    x0= i*step
    x1=(i+1)*step-1
    temp = img[:,x0:x1]
    hierarchy,contours,_ = cv2.findContours(temp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if contours <> []:   
        for i in contours :     
            M = cv2.moments(i)
            if M['m00'] <> 0:
            centroid.append((x0+int(M['m10']/M['m00']),(int(M['m01']/M['m00']))))

I also tried cv2.fitLine(), but it wasn't satisfactory either. How could I detect points in the middle of this curve efficiently ? regards.


回答1:


I think you are getting fewer points because of the following two reasons:

  • using an edge detector: depending on the thresholds, sometimes the edges may not reasonably represent the curve
  • sampling the image using a large step

Try the following instead.

# threshold the image using a threshold value 0
ret, bw = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
# find contours of the binarized image
contours, heirarchy = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# curves
curves = np.zeros((img.shape[0], img.shape[1], 3), np.uint8) 

for i in range(len(contours)):
    # for each contour, draw the filled contour
    draw = np.zeros((img.shape[0], img.shape[1]), np.uint8) 
    cv2.drawContours(draw, contours, i, (255,255,255), -1)
    # for each column, calculate the centroid
    for col in range(draw.shape[1]):
        M = cv2.moments(draw[:, col])
        if M['m00'] != 0:
            x = col
            y = int(M['m01']/M['m00'])
            curves[y, x, :] = (0, 0, 255)

I get a curve like this:

You can also use distance transform and then get the row associated with max distance value for each column of individual contours.



来源:https://stackoverflow.com/questions/26561893/laser-curved-line-detection-using-opencv-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!