题------记录博客只是为了方便自己以后学习,如果什么地方有误,还请指正。
1、目的:
- 在深度学习中,有时收集到的图片像素尺寸大小不一,需要将图片预处理到指定的像素尺寸。代码是将批量的图片裁剪到指定的像素尺寸。以500x500像素图片为例,裁剪结果为192x256。
2、代码:
import cv2
import imutils
import os
def crop_image(image,target_width,target_height):
(h, w) = image.shape[:2]
dH =0
dW=0
if w < h:
image = imutils.resize(image, width=target_width,
inter=cv2.INTER_AREA)
dH = int((image.shape[0] - target_height) / 2.0)
else:
image = imutils.resize(image, height=target_height,
inter=cv2.INTER_AREA)
dW = int((image.shape[1] - target_width) / 2.0)
(h, w) = image.shape[:2]
image = image[dH:h - dH, dW:w - dW]
return cv2.resize(image, (target_width, target_height),interpolation=cv2.INTER_AREA)
if __name__ =="__main__":
image_paths = "C:/Users/Desktop/images/" #图片文件夹路径,路径不能出现中文
filelist = os.listdir(image_paths)
for filename in filelist:
image = cv2.imread(image_paths+'/'+filename)
img = crop_image(image, 192, 256) #可在此处修改宽,高
cv2.imwrite(filename,img)
3、结果对比
- 像素500x500
- 像素192x256
参考博客:https://blog.csdn.net/y459541195/article/details/100687966.