开发者社区> 问答> 正文

如何在可能会有些变形的网格中订购cv2轮廓?

我已经编写了一个python文件来检测cv2网格中的轮廓,并通过从左到右逐列向下对其进行排序。(请参见下面的grid1图片)。

我已经拉出轮廓的左上角并按其x坐标然后按其y坐标进行排序,然后使用已排序的角对轮廓列表进行排序,这是相当琐碎的。当网格完全笔直时,这可以很好地工作。

现在,如果网格已变形,则在grid2上将不再起作用,我们可以看到标记为2的棋子的左上角的x坐标小于标记为2的棋子的左上角的x坐标。 1(如绿线所示)。

因此,当我应用对grid1起作用的排序函数时,它按x排序,然后按y排序,因此标记为2的那部分被错误地排序为排序轮廓的第一个元素,而不是应该排序的第二个元素。

我正在寻找一种对两种情况进行正确排序的好方法。

有人有建议吗?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 23:43:01 657 0
1 条回答
写回答
取消 提交回答
  • 您可以基于原点的拐角距离和相对拐角位置来选择排序。

    • Find contours and hierarchy.

    保持轮廓无子(基于层次结构)。

    • Find corners of bounding rectangles.

    根据以下条件分析拐角(或更简单的条件):

    • Top left contours is the one with the minimum distance of top left corner.
    • Bottom right contours is the one with the maximum distance of top left corner.
    • Other two contours can be separated by maximum x and maximum y (after eliminating the top left and bottom right).

    以下解决方案以颜色绘制边界矩形以进行测试:

    1. Red
    2. Green
    3. Blue
    4. Yellow

    这是一个工作代码示例(请阅读注释):

    import numpy as np
    import cv2
    
    # Read input image as Grayscale
    img = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)
    
    # Convert img to uint8 binary image with values 0 and 255
    # All black pixels goes to 0, and other pixels goes to 255
    ret, thresh_gray = cv2.threshold(img, 1, 255, cv2.THRESH_BINARY)
    
    # Find contours in thresh_gray.
    cnts, hiers = cv2.findContours(thresh_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]  # [-2:] indexing takes return value before last (due to OpenCV compatibility issues).
    
    corners = [] # List of corners
    dist = np.array([]) # Array of distance from axes origin
    
    # Iterate cnts and hiers, find bounding rectangles, and add corners to a list
    for c, h in zip(cnts, hiers[0]):
        # If contours has no child
        if h[2] == -1:
            # Get bounding rectangle
            x, y, w, h = cv2.boundingRect(c)
    
            # Append corner to list of corners - format is corners[i] holds a tuple: ((x0, y0), (x1, y1))
            p0 = (x, y)
            p1 = (x+w, y+h)
            corners.append((p0, p1))
    
            # Distance of corners from origin
            d = np.array([np.linalg.norm(p0), np.linalg.norm(p1)])
    
            if dist.size == 0:
                dist = d
            else:
                dist = np.vstack((dist, d))
    
    
    top_left = np.argmin(dist[:,0]) # Index of top left corner (assume minimum distance from origin)
    bottom_right = np.argmax(dist[:,1]) # Index of top bottom right corner (assume maximum distance from origin)
    
    tmp_corners = np.array(corners)
    tmp_corners[top_left, :, :] = np.array(((0,0), (0,0))) #Ignore top_left corners
    tmp_corners[bottom_right, :, :] = np.array(((0,0), (0,0))) #Ignore bottom_right corners
    bottom_left = np.argmax(tmp_corners[:,1,1]) #Maximum y is bottom left
    tmp_corners[bottom_left, :, :] = np.array(((0,0), (0,0))) #Ignore bottom_left corners
    top_right = np.argmax(tmp_corners[:,1,0])  #Maximum x is top right
    
    # Convert Grayscale to BGR (just for testing - for drawing rectangles in green color).
    out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    
    # Draw rectangles (for testing)
    # 1. Red
    # 2. Green
    # 3. Blue
    # 4. Yellow
    cv2.rectangle(out, corners[top_left][0], corners[top_left][1], (0, 0, 255), thickness = 2)
    cv2.rectangle(out, corners[bottom_left][0], corners[bottom_left][1], (0, 255, 0), thickness = 2)
    cv2.rectangle(out, corners[top_right][0], corners[top_right][1], (255, 0, 0), thickness = 2)
    cv2.rectangle(out, corners[bottom_right][0], corners[bottom_right][1], (0, 255, 255), thickness = 2)
    
    cv2.imwrite('out.png', out)  #Save out to file (for testing).
    
    
    # Show result (for testing).
    cv2.imshow('thresh_gray', thresh_gray)
    cv2.imshow('out', out)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    结果:

    回答来源:stackoverflow

    2020-03-24 23:43:11
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载