【问题标题】:Split an image into multiple images based on result from cv2.HoughLines根据 cv2.HoughLines 的结果将图像拆分为多个图像
【发布时间】:2019-03-09 03:19:19
【问题描述】:

我想根据黑线把这张图片分割成多张图片

我使用 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)

结果如下:

我想知道如何将图像分割成多个带有绿线的小图像

【问题讨论】:

    标签: python cv2


    【解决方案1】:

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

    image = cv2.imread(image_filepath)
    

    现在如果 lines 是在 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

    【讨论】:

    • cv2.HoughLines(...) 只返回 rho 和 theta,不知道如何获取 start_y_coordinate、start_y_coordinate 等。
    【解决方案2】:

    请参阅“感兴趣区域”
    Region of Interest opencv python - StackOverflow)

    阅读本文以获取 x/y:
    Hough Line Transform - Opencv Phyton 教程 1 文档)

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 2015-06-29
      • 2018-03-21
      相关资源
      最近更新 更多