我正在嘗試使用霍夫變換來找到我需要的線條。我正在處理多個影像,其中一個示例是這樣的
https://i.stack.imgur.com/KmGdP.jpg
但是,當使用霍夫變換時,結果為
https://i.stack.imgur.com/DJvbg.jpg
我不知道為什么只有一條線出現在我希望霍夫線包含所有四個側面的標志上,而對于其他影像,我什至沒有出現霍夫線。我究竟做錯了什么?是否有任何糾正措施?這是我正在運行的代碼
import numpy as np
import cv2 as cv
import os
images = []
edges = []
light_range = (0, 0, 0)
dark_range = (80, 80, 80)
#Importing testing images
for i in os.listdir("Directional Signage/Train"):
img = cv.imread(os.path.join("Directional Signage/Train", i))
if img is None:
print("Couldn't read this image" str(i))
else:
images.append(img)
for i in range(0, len(images)):
#Preprocessing
#mask = cv.inRange(images[i], light_range, dark_range)
img = np.float32(images[i]) / 255.0
gx = cv.Sobel(img, cv.CV_32F, 1, 0, ksize=1)
gy = cv.Sobel(img, cv.CV_32F, 0, 1, ksize=1)
mag, angle = cv.cartToPolar(gx, gy, angleInDegrees=True)
gray = cv.cvtColor(mag,cv.COLOR_BGR2GRAY)
gray = np.uint8(gray * 255.0)
edges = cv.Canny(gray,50,150,apertureSize = 3)
lines = cv.HoughLines(edges,2,np.pi/90,200)
#edges.append(lines)
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))
cv.line(images[i],(x1,y1),(x2,y2),(0,0,255),2)
for i in range(0, len(images)):
cv.imshow("blobby " str(i), images[i])
l = cv.waitKey(0)
uj5u.com熱心網友回復:
您只是在一行 ( lines[0]) 上進行迭代,因此很明顯您從每個影像中獲得一行,請改為執行以下操作:
[...]
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))
cv.line(images[i],(x1,y1),(x2,y2),(0,0,255),2)
[...]
更新:現在不是得到一條紅線,而是我的整個影像變紅了
原因是,該Hough函式找到了每一行,但按優先級。更有可能是真實線路的線路位于串列的第一部分。
串列的前兩行,也許就是你要找的,所以試試這個:
[...]
for line in lines[:2]:
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))
cv.line(images[i],(x1,y1),(x2,y2),(0,0,255),2)
[...]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310955.html
