OpenCV的所有功能都能正常运行,但运行此代码并不能给我预期的结果:
dave = cv2.imread('dave.png')
dave1 = cv2.cvtColor(dave,cv2.COLOR_BGR2GRAY)
dave2 = cv2.Canny(dave1,50,150,apertureSize = 3)
dave3 = dave2.copy()
lines = cv2.HoughLines(dave2,1,np.pi/180,200)
for rho,theta in lines[0]:
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(dave3,(x1,y1),(x2,y2),(100,100,100),20)
cv2.imshow('image',dave3)
cv2.waitKey(0)
cv2.destroyAllWindows()
代码几乎与tutorial
中的代码相同原始图片:
我的结果:
答案 0 :(得分:1)
你的问题是dave3是灰度图像,并且是彩色图像。您正在尝试将彩色线条写入灰度图像dave3,这没有意义。
尝试将线条写入彩色图像dave。
cv.line上的缩进缺失了。此外,我已经将该命令中的绘制线宽从20减少到2,类似于原始教程。
您可能希望在行中循环,以绘制所有行。
您正在寻找的代码可能是:
import cv2
import numpy as np
dave = cv2.imread('dave.jpg')
dave1 = cv2.cvtColor(dave,cv2.COLOR_BGR2GRAY)
dave2 = cv2.Canny(dave1,50,150,apertureSize = 3)
lines = cv2.HoughLines(dave2,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(dave,(x1,y1),(x2,y2),(0,255,0),0)
cv2.imshow('image',dave)
cv2.waitKey(0)
cv2.destroyAllWindows()