OpenCV仅检测图像中的特定行

2024-09-20 22:59:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在下图中分离出一条直线,我知道一些方法,比如CannyEdge检测,可以检测图像中的所有直线,但我正在努力寻找我感兴趣的直线

任何有关OpenCV中的工具的信息都将非常感谢。enter image description here

目标是检测球场上方的红色边线(我用蓝色勾勒出)

enter image description here


Tags: 工具方法图像信息目标opencv感兴趣直线
1条回答
网友
1楼 · 发布于 2024-09-20 22:59:14

在Python/OpenCV中,您可以在线条的红色上设置阈值,然后获得最大轮廓或比区域中某个阈值更大的轮廓,这就是我下面展示的

输入:

enter image description here

import cv2
import numpy as np

# read image as grayscale
img = cv2.imread('red_line.png')

# threshold on red color
lowcolor = (0,0,75)
highcolor = (50,50,135)
thresh = cv2.inRange(img, lowcolor, highcolor)


# apply morphology close
kernel = np.ones((5,5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# get contours and filter on area
result = img.copy()
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
result = img.copy()
for c in contours:
    area = cv2.contourArea(c)
    if area > 5000:
        cv2.drawContours(result, [c], -1, (0, 255, 0), 2)


# show thresh and result    
cv2.imshow("thresh", thresh)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save resulting images
cv2.imwrite('red_line_thresh.png',thresh)
cv2.imwrite('red_line_extracted.png',result)


阈值图像:

enter image description here

结果轮廓:

enter image description here

相关问题 更多 >

    热门问题