一.1.opencv: cv2
'cv2'
import cv2
import os
import glob
path = r'C:\Users\87419\Desktop\cg1\img\*.jpg'
for i in glob.glob(path):
im1 = cv2.imread(i)
im2 = cv2.resize(im1,(256,256))
cv2.imwrite(os.path.join(r'C:\Users\87419\Desktop\cg1\resize',os.path.basename(i)),im2)
2.matplotlib : from matplotlib import pyplot as plt
'plt, PIL '
'plt本身无法实现resize, 故不推荐此方法(得到的图是带白边的)'
import matplotlib.pyplot as plt
import os
import glob
from PIL import Image
path = r'C:\Users\87419\Desktop\cg1\img\*.jpg'
for i in glob.glob(path):
im1 = Image.open(i)
im2 = im1.resize((256,256))
plt.imshow(im2)
plt.axis('off')
plt.savefig(os.path.join(r'C:\Users\87419\Desktop\cg1\resize',os.path.basename(i)))
3. PIL: from PIL import Image
'PIL'
from PIL import Image
import os
import glob
path = r'C:\Users\87419\Desktop\cg1\img\*.jpg'
for i in glob.glob(path):
im1 = Image.open(i)
im2 = im1.resize((256,256))
im2.save(os.path.join(r'C:\Users\87419\Desktop\cg1\resize',os.path.basename(i)))
可能会遇到报错 OSError: cannot write mode P as JPEG
解决方法 如下(其余格式报错同理,按 if img.mode == "P" or img.mode == "RGBA": 统一转为RGB就可以了)
import os
from PIL import Image
def resize_image():
# 获取输入文件夹中的所有文件
files = os.listdir(r'C:\Users\admin\Desktop\drone\beijing')
output_dir = r'C:\Users\admin\Desktop\drone\bj_416'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in files:
img = Image.open(r'C:\Users\admin\Desktop\drone\beijing/' + file)
if img.mode == "P" or img.mode == "RGBA":
img = img.convert('RGB')
img = img.resize((416, 416), Image.ANTIALIAS)
img.save(os.path.join(output_dir, file))
resize_image()
详解见 https://blog.csdn.net/z704630835/article/details/84968767
二.按指定图像位置裁剪
以按中心位置抠出128*128大小为例:
先
import os
import cv2
# 遍历指定目录,显示目录下的所有文件名
def CropImage4File(filepath, destpath):
pathDir = os.listdir(filepath) # list all the path or file in filepath
for allDir in pathDir:
child = os.path.join(filepath, allDir)
dest = os.path.join(destpath, allDir)
if os.path.isfile(child):
image = cv2.imread(child)
sp = image.shape # obtain the image shape
sz1 = sp[0] # height(rows) of image
sz2 = sp[1] # width(colums) of image
a = int(sz1 / 2 - 600) # x start
b = int(sz1 / 2 + 300) # x end
c = int(sz2 / 2 - 450) # y start
d = int(sz2 / 2 + 450) # y end
cropImg = image[a:b, c:d] # crop the image
cv2.imwrite(dest, cropImg) # write in destination path
if __name__ == '__main__':
filepath = r'C:\Users\admin\Desktop\1\01' # source images
destpath = r'C:\Users\admin\Desktop\1\02' # resized images saved here
CropImage4File(filepath, destpath)
再
'cv2'
import cv2
import os
import glob
path = r'C:\Users\admin\Desktop\1\02\*.jpg'
for i in glob.glob(path):
im1 = cv2.imread(i)
im2 = cv2.resize(im1, (128, 128))
cv2.imwrite(os.path.join(r'C:\Users\admin\Desktop\1\r_128', os.path.basename(i)), im2)