一、问题描述

常常会遇到已有的图片大小不符合我们的需求,需要对图片进行resize,opencv有一个cv2.resize()函数可以对图片进行缩放,而在图片数量庞大的前提下,只能使用批处理,本文记录的代码功能是多图片的批处理缩放

二、代码

  1. import cv2
  2. import os
  3. # 按指定图像大小调整尺寸
  4. def resize_image(image, height=1280, width=720):
  5. top, bottom, left, right = (0, 0, 0, 0)
  6. # 获取图片尺寸
  7. h, w, _ = image.shape
  8. print(h)
  9. print(w)
  10. # 对于长宽不等的图片,找到最长的一边
  11. longest_edge = max(h, w)
  12. # 计算短边需要增加多少像素宽度才能与长边等长(相当于padding,长边的padding为0,短边才会有padding)
  13. if h < longest_edge:
  14. dh = longest_edge - h
  15. top = dh // 2
  16. bottom = dh - top
  17. elif w < longest_edge:
  18. dw = longest_edge - w
  19. left = dw // 2
  20. right = dw - left
  21. else:
  22. pass # pass是空语句,是为了保持程序结构的完整性。pass不做任何事情,一般用做占位语句。
  23. # RGB颜色
  24. BLACK = [0, 0, 0]
  25. # 给图片增加padding,使图片长、宽相等
  26. # top, bottom, left, right分别是各个边界的宽度,cv2.BORDER_CONSTANT是一种border type,表示用相同的颜色填充
  27. constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)
  28. # 调整图像大小并返回图像,目的是减少计算量和内存占用,提升训练速度
  29. return cv2.resize(constant, (height, width))
  30. def read__image(path_name):
  31. num = 0
  32. for dir_image in os.listdir(path_name): # os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
  33. full_path = os.path.abspath(os.path.join(path_name, dir_image))
  34. if os.path.isdir(full_path): # 如果是文件夹,继续递归调用
  35. read__image(full_path)
  36. else: # 如果是文件了
  37. if dir_image.endswith('.JPG'):
  38. image = cv2.imread(full_path)
  39. #image = resize_image(image)
  40. image = cv2.resize(image, (1280,720))
  41. # 将尺寸调整好的图片保存起来
  42. image_name = r'D:\jsgf\pine\data\VOCdevkit317_406_407_720p\images\val/%s' % ( dir_image) # 注意这里图片名一定要加上扩展名,否则后面imwrite的时候会报错
  43. cv2.imwrite(image_name, image)
  44. num = num + 1
  45. if __name__ == '__main__':
  46. read__image(r'D:\jsgf\pine\data\VOCdevkit317_406_407_720p\images\val')