Python批量修改图片尺寸与格式的实现方案
本文介绍如何利用Python中的PIL和OpenCV库实现图片的批量读取、尺寸调整及格式保存。通过遍历指定目录,使用Image.resize方法设定目标分辨率,并结合cv2.imwrite完成文件写入,适用于需要统一处理大量图片资源的场景。
本文分享了一段使用Python读取图片并调整其文件大小与格式的具体代码示例,供读者参考实践。
# Author:NDK
# -*- coding:utf-8 -*-
from PIL import Image
import os
import cv2
import numpy as np
import glob
# old_dir = './test/'
# def read_image(cwd, newpath):
# for roots, dirs, files in os.walk(cwd):
# print(dirs)
# for i in dirs:
# print(i)
# os.chdir(cwd + i)
# for pic in glob.glob('*.png'):
# _, image = pic.split('_')
# img = image.split('.')[0]
# print(img)
# if len(img) != 0:
# if int(img) % 2 != 0:
# im = Image.open(pic)
# im.save(newpath + i + '/' + pic)
# read_image('./num/','./new_img/')
# for i in range(10):
root_path = r"/test/9/" #操作文件路径
print(root_path)
# dir = root_path+"images"+"/"
dir = root_path
count = 0
for root,dir,files in os.walk(dir):
for file in files:
srcImg = cv2.imread(root_path+"/"+str(file))
img = Image.open(root_path+"/"+str(file))
print(root_path+str(file))
newImg = img.resize((50, 50), Image.BILINEAR) #想调整的大小
cv2.imwrite(r'./img2/'+str(file),newImg) # 写入文件地址
以上内容为本文的全部介绍,希望能为读者的学习提供有益帮助,同时也欢迎持续关注本站以获取更多技术资源。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













