当前位置:   article > 正文

Python批量剪切图像并保存_pytorch图像批量裁剪

pytorch图像批量裁剪
  1. import cv2
  2. import os
  3. import numpy as np
  4. def flip(image,change_angle):
  5. # Extracting height and width from
  6. # image shape
  7. height, width = image.shape[:2]
  8. print("old image size (wxh)=", (width, height))
  9. # get the center coordinates of the
  10. # image to create the 2D rotation
  11. # matrix
  12. center = ((width-1)/2, (height-1)/2)
  13. # using cv2.getRotationMatrix2D()
  14. # to get the rotation matrix
  15. rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=change_angle, scale=1)
  16. print(rotate_matrix)
  17. bound_w = height * np.abs(rotate_matrix[0,1]) + width * np.abs(rotate_matrix[0,0])
  18. bound_h = height * np.abs(rotate_matrix[0,0]) + width * np.abs(rotate_matrix[0,1])
  19. bound_w = int(round(bound_w, 10))
  20. bound_h = int(round(bound_h, 10))
  21. print("new image size (wxh)=", (bound_w, bound_h))
  22. rotate_matrix[0, 2] += (bound_w-1) / 2 - center[0]
  23. rotate_matrix[1, 2] += (bound_h-1) / 2 - center[1]
  24. # rotate_matrix[1,2] += height/2
  25. # rotate the image using cv2.warpAffine
  26. # 90 degree anticlockwise
  27. rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(bound_w, bound_h), borderMode=cv2.BORDER_CONSTANT, borderValue=(128, 128, 128))
  28. return rotated_image
  29. def save(data_dir,save_dir):
  30. if not os.path.exists(save_dir):
  31. os.mkdir(save_dir)
  32. for name in os.listdir(data_dir):
  33. #save_name = name[:-4] + "_{}.png".format(angle)#翻转图像命名
  34. save_name = name[:-4] + "_cut.png" # 剪切图像命名
  35. img = cv2.imread(os.path.join(data_dir,name))
  36. #img_new = flip(img, angle)#翻转图像方法
  37. img_new = cut(img) # 剪切图像方法
  38. cv2.imwrite(os.path.join(save_dir,save_name), img_new)
  39. def flip_main():
  40. Data_dir = "/home/ljs/Desktop/name" # 要改变的图片的路径文件夹
  41. Save_dir = "/home/ljs/Desktop/name_flip" # 要保存的图片的路径文件夹
  42. for i in range(0,361,15):
  43. #print(i)
  44. save(Data_dir, Save_dir, i) # 进行批量处理并且保存
  45. def show():
  46. imgFile = "/home/ljs/Desktop/name/1.png"
  47. img = cv2.imread(imgFile)
  48. cv2.imshow("Demo1", img)
  49. cv2.waitKey(0)
  50. def cut(image):
  51. cropped_image = image[250:1450, 300:1750] # Slicing to crop the image
  52. return cropped_image
  53. def cut_main():
  54. Data_dir = "/home/ljs/Desktop/name_flip" # 要改变的图片的路径文件夹
  55. Save_dir = "/home/ljs/Desktop/name_cut" # 要保存的图片的路径文件夹
  56. save(Data_dir, Save_dir) # 进行批量处理并且保存
  57. if __name__ == '__main__':
  58. #flip_main()
  59. #show()
  60. cut_main()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/77487
推荐阅读
相关标签
  

闽ICP备14008679号