Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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) соответственно убрать.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question