import cv2 import numpy as np img = cv2.imread("data/test/test2.png") dst = 255- img gray = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY) ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) minx = 65523 miny = 65523 maxx = 0 maxy = 0 for contour in contours: boundRect = cv2.boundingRect(contour) (x,y,w,h)=boundRect if xmaxx: maxx=x+w if y+h>maxy: maxy=y+h cutw=maxx-minx cuth=maxy-miny # w>h if cutw>cuth: cuty1=int((maxy+miny)/2-cutw/2) cuty2=int((maxy+miny)/2+cutw/2) img = img[cuty1:cuty2,minx:maxx] if cutw