是否可以将Houghlines函数的输出转换为HoughlinesP函数的输出?
我有一张图片,想从中提取出红色的网格。我之前用过HoughlinesP这个函数,效果不错(可以查看这个链接:查看图片),但现在我想用HoughLines函数,因为它运行得更快。问题是,这个函数的输出不是[x1,y1,x2,y2]这样的格式,而是[rho, theta]。
我已经尝试过这样转换:
line_coordinates = []
for line in lines:
for rho,theta in line:
x1 = int(rho * math.cos(theta))
y1 = int(rho * math.sin(theta))
x2 = int(x1 + 1000 * (-math.sin(theta)))
y2 = int(y1 + 1000 * (math.cos(theta)))
line_coordinates.append([x1, y1, x2, y2])
cv2.line(imgOriginal, (x1, y1), (x2, y2), (0, 0, 255), 2)
但是如果我这样做,就会得到像这样的一些结果:查看图片,我该如何改进这个转换呢?
我使用的函数是:
imgOriginal = cv2.imread(path, cv2.IMREAD_COLOR)
hsv = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)
mask_red = cv2.inRange(hsv, np.array([150, 25, 150]), np.array([180, 255, 255]))
mask_red_extra = cv2.inRange(hsv, np.array([1, 25, 150]), np.array([40, 255, 255]))
red_mask = mask_red + mask_red_extra
cv2.imshow('edges', red_mask)
threshold = 150
lines = cv2.HoughLines(red_mask, 1, np.pi/180, threshold)
hough_lines = cv2.HoughLinesP(red_mask, 1, np.pi / 180, threshold=50, minLineLength=75, maxLineGap=300)
这里是原始图片:查看图片
1 个回答
0
不可以。不能把 Houghlines
函数的输出结果用到 HoughlinesP
函数里。
应该使用 HoughLines
而不是 HoughLinesP
。
代码示例:
import cv2
import numpy as np
img = cv2.imread('l.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 r_theta in lines:
arr = np.array(r_theta[0], dtype=np.float64)
r, theta = arr
# Stores the value of cos(theta) in a
a = np.cos(theta)
b = np.sin(theta)
x0 = a*r
y0 = b*r
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('linesDetected', img)
cv2.waitKey(0)
截图: