0

I want to write a script that receives a picture and it should then individually save the 9 biggest objects in the picture. My problem is, that the script saves those 9 objects according to their size. I would like to define an order in which it will save the objects.

Here's my code so far:

import cv2
import numpy as np

image = cv2.imread('pic1.png')
orig_img = image

blank = np.zeros(image.shape, dtype='uint8')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 70, 175)

ret, thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)

contours, hierachies = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)

for i, cont in enumerate(sorted_contours[:9], 1):

        x, y, w, h = cv2.boundingRect(cont)
        cropped = orig_img[y:y+h, x:x+w]
        cv2.imwrite('cropped_image{}.png'.format(i), cropped)

        cv2.imshow('Contours', orig_img)


cv2.waitKey(0)
cv2.destroyAllWindows()

The sample picture is this one. And I would like the order to be like this. But as of right now, the script hast just a list of big to small and it will save according to that.

Any ideas how to implement that?

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
balé
  • 1
  • 1
    Does this answer your question? [Python: Sorting items from top left to bottom right with OpenCV](https://stackoverflow.com/questions/66946804/python-sorting-items-from-top-left-to-bottom-right-with-opencv) – Christoph Rackwitz Feb 10 '22 at 13:58
  • if that's not suitable, I'm sure we could devise a new algorithm that recovers the table structure in your image from the positions of those cards (find neighbors in cardinal directions, build graph) – Christoph Rackwitz Feb 10 '22 at 13:59
  • also relevant: https://stackoverflow.com/questions/29630052/ordering-coordinates-from-top-left-to-bottom-right – Christoph Rackwitz Feb 10 '22 at 14:01

0 Answers0