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

yipeiwu_com5年前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简单调用MySQL存储过程并获得返回值的方法

本文实例讲述了Python调用MySQL存储过程并获得返回值的方法。分享给大家供大家参考。具体实现方法如下: try: conn = MySQLdb.connect (...

Python库urllib与urllib2主要区别分析

作为一个Python菜鸟,之前一直懵懂于urllib和urllib2,以为2是1的升级版。今天看到老外写的一篇《Python: difference between urllib and...

Python实现翻转数组功能示例

本文实例讲述了Python实现翻转数组功能。分享给大家供大家参考,具体如下: 题目描述 给定一个长度为n的整数数组a,元素均不相同,问数组是否存在这样一个片段,只将该片段翻转就可以使整个...

Python3实现的腾讯微博自动发帖小工具

复制代码 代码如下:# -*- coding: UTF-8 -*-import mysql.connector as dbimport client.tWeiboimport time...

详解Python中__str__和__repr__方法的区别

 对我当前工程进行全部测试需要花费不少时间。既然有 26 GB 空闲内存,为何不让其发挥余热呢? tmpfs 可以通过把文件系统保存在大内存中来加速测试的执行效率。 但...