【发布时间】:2019-10-28 18:55:02
【问题描述】:
我生成带有某些线条的嘈杂图像,比如这个:
我正在尝试使用 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)
这是我得到的结果(非常错误):
那么,我怎样才能正确检测这些嘈杂图像中的线条?
【问题讨论】:
标签: python python-3.x image-processing opencv