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字符串逆序的实现方法【一题多解】

/post/156406.htm /post/156407.htm 1. 使用索引 >> strA = 'abcdefg' >> strA[::-1] 'gf...

Django ORM 自定义 char 类型字段解析

Django ORM 自定义 char 类型字段解析

用 CharField 定义的字段在数据库中存放为 verchar 类型 自定义 char 类型字段需要下面的代码: class FixedCharField(models.Fie...

在Django中实现添加user到group并查看

一、添加user到group 第一种: user.groups.add(1) # add by id 第二种: from django.contrib.auth.models...

使用python实现语音文件的特征提取方法

使用python实现语音文件的特征提取方法

概述 语音识别是当前人工智能的比较热门的方向,技术也比较成熟,各大公司也相继推出了各自的语音助手机器人,如百度的小度机器人、阿里的天猫精灵等。语音识别算法当前主要是由RNN、LSTM、D...

python3.x提取中文的正则表达式示例代码

实例一: 读取txt文件中含有中文的字符 import re ##此处使用的编辑器是python3.x d="[\u4e00-\u9fa5]+" #中文匹配的符号 f=open('...