img_correct.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import argparse
  2. import os
  3. import cv2
  4. import numpy as np
  5. from PIL import Image
  6. import glob
  7. def save_img(img_Path, save_Path, cnt):
  8. img_path = img_Path
  9. img = cv2.imread(img_path)
  10. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  11. ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
  12. coords = np.column_stack(np.where(thresh > 0))
  13. angle = cv2.minAreaRect(coords)[-1]
  14. print('{}:{}'.format(img_path, angle))
  15. # #调整角度
  16. if angle < -45:
  17. angle = -(90 + angle)
  18. else:
  19. angle = -angle
  20. im = Image.open(img_path)
  21. im_rotate = im.rotate(angle, expand=0, fillcolor='#FFFFFF')
  22. if cnt == 0:
  23. save_path = save_Path + '/' + img_path.split('\\')[-1]
  24. else:
  25. save_path = save_Path + '/' + img_path.split('/')[-1]
  26. im_rotate.save(save_path)
  27. def correct(img_fold, img_Path, save_fold):
  28. if not os.path.exists(save_fold):
  29. os.makedirs(save_fold)
  30. if img_Path == '':
  31. path_list = glob.glob(img_fold + '/*.png')
  32. size = len(path_list)
  33. print('total: {} images'.format(size))
  34. for path in path_list:
  35. save_img(path, save_fold, 0)
  36. else:
  37. save_img(img_Path, save_fold, 1)
  38. if __name__ == '__main__':
  39. parser = argparse.ArgumentParser()
  40. parser.add_argument('--img_dir', type=str, default='')
  41. parser.add_argument('--img_path', type=str, default='')
  42. parser.add_argument('--save_dir', type=str, default='')
  43. args = parser.parse_args()
  44. correct(args.img_dir, args.img_path, args.save_dir)