gho*_*ium 2 python opencv image-processing hough-transform
我正在尝试使用 opencv 中的霍夫线从织物图像中提取垂直线。我应用对比度增强来增强线条,并应用双边过滤来尝试去除其他织物纹理。但是,在应用粗糙线时,代码会检测整个图像上的线条。我尝试使用霍夫的参数,但结果是相同的。
应用直方图均衡和双边滤波器后的输入图像:
这是应用霍夫线后的图像,红色代表检测到的线。显示霍夫检测的输出:
我可以尝试的另一种方法是什么,以便霍夫不会开始将微小的织物图案也检测为线条?
这是我的代码:
`
img1= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img2 = cv2.equalizeHist(img1)
img3 = cv2.equalizeHist(img2)
img4 = cv2.equalizeHist(img3)
img5 = cv2.bilateralFilter(img4, 9, 75,75)
cv2.imshow("threshold",img5)
edges = cv2.Canny(img4,50,127,apertureSize = 3)
lines= cv2.HoughLines(edges, 1, math.pi/180.0, 200, np.array([]), 0, 0)
a,b,c = lines.shape
for i in range(a):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0, y0 = a*rho, b*rho
pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) )
pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) )
cv2.line(img, pt1, pt2, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow('image1',img)
cv2.waitKey(0)
cv2.destroyAllWindows()`
Run Code Online (Sandbox Code Playgroud)
在进行精明边缘检测和霍夫线提取之前,您需要对均衡图像进行阈值处理,应用形态学对其进行清理。使用Python/OpenCV进行如下处理。
输入:
import cv2
import numpy as np
import math
# read image
img = cv2.imread('fabric_equalized.png')
# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# threshold
thresh = cv2.threshold(gray,165,255,cv2.THRESH_BINARY)[1]
# apply close to connect the white areas
kernel = np.ones((15,1), np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = np.ones((17,3), np.uint8)
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)
# apply canny edge detection
edges = cv2.Canny(img, 175, 200)
# get hough lines
result = img.copy()
lines= cv2.HoughLines(edges, 1, math.pi/180.0, 165, np.array([]), 0, 0)
a,b,c = lines.shape
for i in range(a):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0, y0 = a*rho, b*rho
pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) )
pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) )
cv2.line(result, pt1, pt2, (0, 0, 255), 2, cv2.LINE_AA)
# save resulting images
cv2.imwrite('fabric_equalized_thresh.jpg',thresh)
cv2.imwrite('fabric_equalized_morph.jpg',morph)
cv2.imwrite('fabric_equalized_edges.jpg',edges)
cv2.imwrite('fabric_equalized_lines.jpg',result)
# show thresh and result
cv2.imshow("thresh", thresh)
cv2.imshow("morph", morph)
cv2.imshow("edges", edges)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
阈值图像:
形态学清洗后的图像:
边缘图像:
生成的霍夫线: