I
I
Ilya Neizvestnyj2019-10-10 14:17:45
Python
Ilya Neizvestnyj, 2019-10-10 14:17:45

How to keep contours from left to right?

There is a program that crops the image along the contours. But when saving, cropped objects are saved in random order. How can I make sure they are saved sequentially?

import cv2
image = cv2.imread("C:/Users/pikro/PycharmProjects/CV/20.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(image, 10, 250)
_, cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
idx = 0

for c in cnts:
    x, y, w, h = cv2.boundingRect(c)
    if w > 20 and h > 20:
        idx += 1
        new_img = image[y:y + h, x:x + w]
        cv2.imwrite(str(idx) + '.png', new_img)
cv2.imshow("im", image)
cv2.waitKey(0)

5d9f1353af09c246877050.png
Result:
5d9f138fdea87282517443.png
5d9f13b51ab61047561339.png
5d9f13b92d922276411529.png
5d9f13bd285b8446232857.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2019-10-10
@Cheloved

cv2.boundingRect returns the x-coordinate of the rectangle of each contour. Just sort by it. More or less like this:

rects = sorted([cv2.boundingRect(c) for c in cnts], key=lambda x: x[0])

for x,y,w,h in rects:
    # и далее как есть. x, y, w, h = cv2.boundingRect(c) соответственно убрать.

D
Denis, 2019-10-10
@D3Nd3R

Find the centers of the boundingRect and sort by X.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question