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 的 with 语句详解

一、简介 with是从Python 2.5 引入的一个新的语法,更准确的说,是一种上下文的管理协议,用于简化try…except…finally的处理流程。with通过__enter__...

python中二维阵列的变换实例

本文实例讲述了python中二维阵列的变换方法。分享给大家供大家参考。具体方法如下: 先看如下代码: arr = [ [1, 2, 3], [4, 5, 6], [7, 8,9],...

对dataframe进行列相加,行相加的实例

实例如下所示: >>> import pandas as pd >>> df = pd.DataFrame({"x":['a','b','c','...

Python中的上下文管理器和with语句的使用

Python2.5之后引入了上下文管理器(context manager),算是Python的黑魔法之一,它用于规定某个对象的使用范围。本文是针对于该功能的思考总结。 为什么需要上下文管...

Python实现感知器模型、两层神经网络

Python实现感知器模型、两层神经网络

本文实例为大家分享了Python实现感知器模型、两层神经网络,供大家参考,具体内容如下 python 3.4 因为使用了 numpy 这里我们首先实现一个感知器模型来实现下面的对应关系...