cvtest.py 898 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import cv2
  2. import numpy as np
  3. img = cv2.imread("data/test/test2.png")
  4. dst = 255- img
  5. gray = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
  6. ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
  7. contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  8. minx = 65523
  9. miny = 65523
  10. maxx = 0
  11. maxy = 0
  12. for contour in contours:
  13. boundRect = cv2.boundingRect(contour)
  14. (x,y,w,h)=boundRect
  15. if x<minx:
  16. minx=x
  17. if y<miny:
  18. miny=y
  19. if x+w>maxx:
  20. maxx=x+w
  21. if y+h>maxy:
  22. maxy=y+h
  23. cutw=maxx-minx
  24. cuth=maxy-miny
  25. # w>h
  26. if cutw>cuth:
  27. cuty1=int((maxy+miny)/2-cutw/2)
  28. cuty2=int((maxy+miny)/2+cutw/2)
  29. img = img[cuty1:cuty2,minx:maxx]
  30. if cutw<cuth:
  31. cutx1=int((maxx+minx)/2-cuth/2)
  32. cutx2=int((maxx+minx)/2+cuth/2)
  33. img = img[miny:maxy,cutx1:cutx2]
  34. # img = img[miny:maxy,minx:maxx]
  35. cv2.imwrite("cctmp.png", img)