python批量resize图⽚⼤⼩_python批量图⽚resize代码——分
别3种库函数实现
⼀.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 = size(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 = size((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'
resize函数vba
for i in glob.glob(path):
im1 = Image.open(i)
im2 = size((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
解决⽅法  如下(其余格式报错同理,按 de == "P" de == "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 ists(output_dir):
os.makedirs(output_dir)
for file in files:
img = Image.open(r'C:\Users\admin\Desktop\drone\beijing/' + file)
de == "P" de == "RGBA":
img = vert('RGB')
img = size((416, 416), Image.ANTIALIAS)
img.save(os.path.join(output_dir, file))
resize_image()
⼆.按指定图像位置裁剪
以按中⼼位置抠出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 = size(im1, (128, 128))
cv2.imwrite(os.path.join(r'C:\Users\admin\Desktop\1\r_128', os.path.basename(i)), im2)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。