【问题标题】:Python and OpenCV: sort list of contours according to two criteriaPython和OpenCV:根据两个标准对轮廓列表进行排序
【发布时间】:2018-03-30 23:38:34
【问题描述】:

在 Python 中,我有一个轮廓列表。每个轮廓都是一个 numpy 数组。 每个轮廓都是一个正方形,如下图所示:

每个轮廓都有 cx 和 cy - 它们是轮廓的时刻 - 它的中心。

我还计算了每个轮廓的平均 rgb 并将其添加到列表中。

如何对轮廓进行排序,如您在 1-24 的第一张图像中所见 - 从左上角到右下角 - 仅使用 (cx,cy) 逐行排列?

我的代码:

    def find_contour_mean_color_value(self , img , width=None , height=None , full_square=False):

    contours = []

    for (i,cnt) in enumerate(self.all_detected_color_squares):
        mom = cv2.moments(cnt)
        (cx,cy) = int(mom['m10']/mom['m00']), int(mom['m01']/mom['m00'])

        if full_square == True:
            x,y,w,h = cv2.boundingRect(cnt)
            roi = img[y:y+h, x:x+w]

        else:
            #define needed square around the center as following
            center_square_width = width
            center_square_height = height

            x_1= int(cx-(center_square_width/2))
            y_1 = int(cy-(center_square_height/2))

            roi = img[y_1:y_1 + center_square_height , x_1:x_1 + center_square_width]



        color = cv2.mean(roi)
        (r,g,b) = (color[2] , color[1] , color[0])
        contours.append((self.all_detected_color_squares , (cx ,cy) , (r,g,b) ))


    self.all_detected_color_squares = np.array(contours)

我们如何根据需要对轮廓列表进行排序,并通过图像和数字进行描述?

我确信使用 labmda 是可行的,但我无法做到。

更多详情见:

【问题讨论】:

    标签: python-3.x numpy opencv3.0


    【解决方案1】:

    这应该返回按 (cx, cy) 排序的轮廓:

    contours = sorted(contours, key = lambda x: x[1])
    

    【讨论】:

    • 是的,但这不足以像图片中描述的那样对正方形进行排序
    • 它们是如何排序的?从图片上很难分辨。
    • 使用 findContours 并基于区域。
    【解决方案2】:

    可以这样做:

        squares = sorted(detected_squares, key=lambda x: x[1][1])
        for i in range(self.cols_num):
            i = i*self.rows_num
            j = i + self.rows_num
            squares[i:j] = sorted(squares[i:j], key=lambda x: x[1][0])
    
    
        detected_squares = squares
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 2015-01-24
      • 2020-12-15
      • 2021-09-14
      • 1970-01-01
      相关资源
      最近更新 更多