12345678910111213141516171819202122232425262728293031323334353637383940 |
- 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 x<minx:
- minx=x
- if y<miny:
- miny=y
- if x+w>maxx:
- 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<cuth:
- cutx1=int((maxx+minx)/2-cuth/2)
- cutx2=int((maxx+minx)/2+cuth/2)
- img = img[miny:maxy,cutx1:cutx2]
- # img = img[miny:maxy,minx:maxx]
- cv2.imwrite("cctmp.png", img)
|