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

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

使用 Python 处理3万多条数据只要几秒钟

使用 Python 处理3万多条数据只要几秒钟

应用场景:工作中经常遇到大量的数据需要整合、去重、按照特定格式导出等情况。如果用 Excel 操作,不仅费时费力,还不准确,有么有更高效的解决方案呢? 本文以17个 txt 文本,3万多...

在Python的框架中为MySQL实现restful接口的教程

在Python的框架中为MySQL实现restful接口的教程

最近在做游戏服务分层的时候,一直想把mysql的访问独立成一个单独的服务DBGate,原因如下:     请求收拢到DBGate,可以使DBGate变...

Apache如何部署django项目

Apache如何部署django项目

在此之前,我们一直使用django的manage.py 的runserver 命令来运行django应用,但这只是我们的开发环境,当项目真正部署上线的时候这做就不可行了,必须将我们的项目...

python解压TAR文件至指定文件夹的实例

如下所示: ######### Extract all files from src_dir to des_dir def extract_tar_files(src_dir,des...

解决Python出现_warn_unsafe_extraction问题的方法

解决Python出现_warn_unsafe_extraction问题的方法

在Python项目中运行出现了“AttributeError: ResourceManager instance has no attribute ‘_warn_unsafe_extra...