Ram*_*ffo 3 python opencv image-processing python-3.x
我生成带有某些线条的嘈杂图像,如下所示:

我正在尝试使用 OpenCV 检测线条,但出了点问题。
到目前为止,这是我的代码,包括生成嘈杂图像的代码。
import cv2
import numpy as np
def draw_random_lines(img, w, n):
for i in range(n):
point1 = (np.random.randint(low = 0, high = w), np.random.randint(low = 0, high = w))
point2 = (np.random.randint(low = 0, high = w), np.random.randint(low = 0, high = w))
cv2.line(img,point1,point2,(255,0,0),5)
x = y = 0
while(y<w):
while(x<w):
if(np.any(img[x, y] != 0)):
if(np.random.randint(low=0, high=100) < 60):
img[x, y] = [255, 255, 255]
else:
img[x, y] = [0, 0, 0]
else:
if(np.random.randint(low=0, high=100) < 95):
img[x, y] = [255, 255, 255]
else:
img[x, y] = [0, 0, 0]
x+=1
x=0
y+=1
return img
w = 512
img = np.zeros((w,w,3), np.uint8)
img = draw_random_lines(img, w, 5)
cv2.imshow("Original", img)
cv2.imwrite("alo.png", img)
img = cv2.imread("alo.png")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,200)
for line in lines:
for rho,theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imshow("Detectada", img)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
这是我得到的结果(非常错误):

那么,如何正确检测这些嘈杂图像中的线条?
由于 OpenCV 的 Hough 变换实现在黑色背景上寻找白色像素,因此找到线条的第一个重要步骤是反转您的嘈杂图像。
轻微的中值模糊将进一步有助于去除噪声,从而提高霍夫变换的性能。
对于我建议的解决方案,我还使用了该HoughLinesP方法而不是HoughLines. (根据我的经验,你会得到“更好”的结果。)
所以,这是我的代码片段:
import cv2
import numpy as np
# Read input
img = cv2.imread('images/K9YLm.png', cv2.IMREAD_GRAYSCALE)
# Initialize output
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
# Median blurring to get rid of the noise; invert image
img = 255 - cv2.medianBlur(img, 3)
# Detect and draw lines
lines = cv2.HoughLinesP(img, 1, np.pi/180, 10, minLineLength=50, maxLineGap=30)
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(out, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow('out', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
输出out如下所示:
由于 的使用HoughLinesP,您会得到一组相当大的(较小的)行。人们需要设置一种类似行的“分组”。(或者,也许可以在单独的图像上绘制红线,然后重新运行线检测。)
希望有帮助!