一、自定义
import cv2
import numpy as np
from matplotlib import pyplot as pltdef line_detection(image):gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)edges = cv2.Canny(gray,50,150,apertureSize=3)lines = cv2.HoughLines(edges,1,np.pi/180,200)for line in lines:rho,theta = line[0]a = np.cos(theta)b = np.sin(theta)x0 = a*rhoy0 = b*rhox1 = int(x0+1000*(-b))y1 = int(y0+1000*(a))x2 = int(x0-1000*(-b))y2 = int(y0-1000*(a))cv2.line(image,(x1,y1),(x2,y2),(0,0,255),2)#将直线画到image上,直线的两点分别为(x1,y1),(x2,y2),直线的颜色为(0,0,255),直线的宽度为2cv2.imshow("image_lines",image)src = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\qqq.png")
cv2.imshow("image",src)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)
line_detection(src)
cv2.waitKey(0)
cv2.destroyAllWindows()
效果图如下:
二、调用API接口
import cv2
import numpy as np
from matplotlib import pyplot as pltdef line_detect(image):gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)edges = cv2.Canny(gray,50,150,apertureSize=3)lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=50,maxLineGap=10)for line in lines:x1,y1,x2,y2 = line[0]cv2.line(image,(x1,y1),(x2,y2),(0,0,255),2)#将直线画到image上,直线的两点分别为(x1,y1),(x2,y2),直线的颜色为(0,0,255),直线的宽度为2cv2.imshow("image_lines",image)src = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\qqq.png")
cv2.imshow("image",src)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)
line_detect(src)
cv2.waitKey(0)
cv2.destroyAllWindows()
效果图如下: