After I applied the threshold value and found the contours of the object, I used the following code to get a straight rectangle around the object (or a rotated rectangle introducing its instruction):
img = cv2.imread('image.png') imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY) # find contours contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnt = contours[0] # straight rectangle x,y,w,h = cv2.boundingRect(cnt) img= cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
see image

Then I calculated the number of object and background pixels inside the straight rectangle using the following code:
Now I want to adapt the rectangle of the object as a function of the relationship between the background pixel and the object of the object, i.e. have a rectangle that occupies most of the object without or a smaller background pixel, for example

How do I create this?
source share