Python 和 OpenCV:根据两个标准对轮廓列表进行排序
Python and OpenCV: sort list of contours according to two criteria
在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 是可行的,但我做不到。
有关详细信息,请参阅:
这应该 return 按 (cx, cy) 排序的轮廓:
contours = sorted(contours, key = lambda x: x[1])
可以这样做:
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
在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 是可行的,但我做不到。
有关详细信息,请参阅:
这应该 return 按 (cx, cy) 排序的轮廓:
contours = sorted(contours, key = lambda x: x[1])
可以这样做:
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