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?