首页 > 解决方案 > 根据 cv2.HoughLines 的结果将图像拆分为多个图像

问题描述

我想根据黑线将此图像拆分为多个图像

在此处输入图像描述

我使用 cv2.HoughLines 来获取一些线条,将它们合并以避免重叠线条。这里是我的绘图代码:

# After get lines from cv2.HoughLines()
for line in lines:

    rho, theta = 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))

    cv2.line(image, (x1, y1), (x2, y2), (0, 200, 0), 2)

cv2.imwrite('results/result.jpg', image)

结果如下:

在此处输入图像描述

我想知道如何用这些绿线将图像分割成多个小图像

标签: pythoncv2

解决方案


假设image是opencv读取图像作为nd数组的变量。

image = cv2.imread(image_filepath)

现在 iflines是在 houghline 转换后分配的变量,例如:

lines = cv2.HoughLinesP(...) 

得到它的形状:

a,b,c = lines.shape

启动一个变量以获取坐标并附加边界框:

line_coords_list = []
for i in range(a):
    line_coords_list.append([(lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3])])

现在,遍历边界框列表并裁剪主图像并用一些文件名写入它们:

temp_img = image[start_y_coordinate : end_y_coordinate , start_x_coorinate : end_x_coordinate]
temp_name = image_filepath[:-4] + "_"+str(start_y_coordinate )+"_"+str(end_y_coordinate)+ "_" + str(start_x_coorinate) + "_" + str(end_x_coordinate) + ".png"
cv2.imwrite(temp_name, temp_img)

如果您正在使用cv2.HoughLines(...),那么您可能必须使用以下方法在图像中找到轮廓:

_, blackAndWhite = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV)
_,contours,h = cv2.findContours(blackAndWhite,cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE)

然后遍历轮廓:

for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    line_coords_list.append((x,y,w,h))

在这里,在寻找轮廓时,第三项和第四项分别是宽度和高度。所以end_y_coordinate = y+hend_x_coordinate = x+w


推荐阅读