我正在尝试使用Houghlines方法在白色矩形的每一侧绘制 4 条线。
这是我正在处理的图像源图像 (2592 x 1246 图像)。
import cv2 as cv
import numpy as np
img = cv.imread("picture_compress.bmp")
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(img_gray, 100, 200, 5)
lines = cv.HoughLines(edges, rho=2, theta=np.pi / 180, threshold=200) # lines will be in polar coordinate system
colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0), (255, 0, 255), (255, 255, 0), (0, 255, 255)]
for i, line in enumerate(lines):
rho, theta = line[0] # rho --> distance from the coordinate origin (0,0) (Top-Left corner of the image)
# theta --> line rotation angle in radius
# getting the cos(theta) and sin(theta) value
a = np.cos(theta)
b = np.sin(theta)
# getting the origin value(top-left corner of the image)
x0 = a * rho
y0 = b * rho
# 2 points
pt1 = (int(x0 + 2592 * (-b)), int(y0 + 2592 * a))
pt2 = (int(x0 - 2592 * (-b)), int(y0 - 2592 * a))
# draw lines on the input image
cv.line(img, pt1, pt2, colors[i % len(colors)], thickness=3, lineType=cv.LINE_AA)
print("Total number of lines:", str(len(lines)))
cv.namedWindow("Hough", cv.WINDOW_NORMAL)
cv.imshow("Hough", img)
cv.waitKey(0)
结果我得到了Result。
从最后一张图片中,您可以看到在白色斑点的边缘绘制了多条线。
任务:
- 在矩形的每一侧仅绘制 4 条线的最佳方法是什么?
- 如何仅使用HoughLines而不是HoughLinesP来获得 4 条有限线?
--------------------------------------------------已编辑(2021 年 3 月 17 日) ------------------------------------------ --------
让我发布我正在处理的原始图像。
Fase 1:Eroded_Dilated_Image - 应用腐蚀和膨胀并填充斑点后的结果。代码:
# This function is used for cleaning the image
def erode_dilate(img, num_iter):
kernel = np.ones((3, 3), np.uint8)
erosion = cv.erode(src=img, kernel=kernel, iterations=num_iter)
dilation = cv.dilate(src=erosion, kernel=kernel, iterations=num_iter)
return dilation
# This function will search for the blob with max area and will fill it
def find_draw_big_blob(img):
contours, _ = cv.findContours(image=img, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)
contour_area = [cv.contourArea(cnt) for cnt in contours] # List of contours' area
id_max_area = np.argmax(contour_area)
label_max_image = np.zeros(img.shape)
draw_max_contour = cv.drawContours(image=label_max_image, contours=contours, contourIdx=id_max_area, color=255, thickness=-1)
img = cv.imread("25559.bmp")
gray_image = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret1, thresh = cv.threshold(gray_image, thresh=127, maxval=255, type=cv.THRESH_OTSU)
image_erode_dilate = erode_dilate(img=thresh, num_iter=2)
big_blob = find_draw_big_blob(img=image_erode_dilate)
cv.imshow("Image", big_blob)
Fase 2: houghlines_Image - 应用hough trasform后的最终结果。我用于这个霍夫变换的代码已经在问题中了。
但最终的结果并不是我想要的结果。
我想实现这个sample_image中显示的以下结果