您的位置:首页 > 编程语言 > Python开发

Python实现批量修改图片格式和大小的方法【opencv库与PIL库】

2018-12-16 20:14 3143 查看

本文实例讲述了Python实现批量修改图片格式和大小的方法。分享给大家供大家参考,具体如下:

第一种方法用到opencv库

import os
import time
import cv2
def alter(path,object):
result = []
s = os.listdir(path)
count = 1
for i in s:
document = os.path.join(path,i)
img = cv2.imread(document)
img = cv2.resize(img, (20,20))
listStr = [str(int(time.time())), str(count)]
fileName = ''.join(listStr)
cv2.imwrite(object+os.sep+'%s.jpg' % fileName, img)
count = count + 1
alter('C:\\imgDemo','C:\\imgDemo1')

第二种方法用到PIL库

import os
import time
from PIL import Image
def alter(path,object):
s = os.listdir(path)
count = 1
for i in s:
document = os.path.join(path,i)
img = Image.open(document)
out = img.resize((20,20))
listStr = [str(int(time.time())), str(count)]
fileName = ''.join(listStr)
out.save(object+os.sep+'%s.jpg' % fileName)
count = count + 1
alter('C:\\imgDemo','C:\\imgDemo1')

运行上述代码可得到C:\imgDemo目录下对应批量生成的20*20大小的图片。

运行效果如下:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: