Python转换图片格式 -- PIL库的使用

news/2024/10/23 9:31:17/

PIL库提供了强大的功能,可以将所有格式的彩色或灰度图片读入,并以其他格式保存(真格式,而不是重命名)。

对于彩色图像,不管其图像格式是PNG,还是BMP,或者JPG,在PIL中,使用Image模块的open()函数打开后,返回的图像对象的模式都是“RGB”。

对于灰度图像,不管其图像格式是PNG,还是BMP,或者JPG,打开后,其模式为“L”。

--------------------------------------------------------------------------------

在安装PIL库时,需要注意Python的版本。

pip install PIL      #支持的版本为python 2.5, 2.6, 2.7
pip install pillow   #支持的版本为python 3.+

代码如下:

# image to png
# 任意格式 to 任意格式
# 修改格式名即可
import os
from PIL import Image
import shutil
import sysdef image2png(dataset_dir,type):files = [] image_list = os.listdir(dataset_dir) files = [os.path.join(dataset_dir, _) for _ in image_list] for index,bmp in enumerate(files): if index > 250: breaktry: sys.stdout.write('\r>>Converting image %d/100000 ' % (index)) sys.stdout.flush() im = Image.open(bmp) png = os.path.splitext(bmp)[0] + "." + typeim.save(png) except IOError as e: print('could not read:',bmp) print('error:',e) print('skip it\n') sys.stdout.write('Convert Over!\n') sys.stdout.flush() if __name__ == "__main__": current_dir = os.getcwd() print(current_dir)data_dir = 'A:\pics' #这里是图片文件夹image2png(data_dir,'png')

如果仅是重命名,可以直接在文件夹中,运行命令行cmd,运行以下命令:

ren .*bmp .*png #仅是重命名而已

之前文章中,对表格数据的处理,对三元组处理,网页元素处理,都是用了Python的集成开源库,看来Python成为新时代宠儿是有道理的,毕竟这是个大数据的时代。

 

参考文章:

https://blog.csdn.net/icamera0/article/details/50843172/

https://blog.csdn.net/u013517229/article/details/81076705

https://www.jb51.net/article/141625.htm


http://www.ppmy.cn/news/857004.html

相关文章

SQL Server里PIVOT运算符的”红颜祸水“

概述 SQL Server里PIVOT运算符背后的基本思想是在T-SQL查询期间,你可以旋转行为列。运算符本身是SQL Server 2005后引入的,主要用在基于建立在实体属性值模型(Entity Attribute Value model (EAV))原则上的数据库。EAM模型背后的想…

Selenium爬虫 -- 图片视频的src绝对地址链接分析

爬取**的时候,每次爬取图片都要转到mbasic.**网站,这样极容易被检测封号。 然后我发现在检查页面的元素的时候,图片和视频的链接都藏在了元素的style属性中。 思路: 定位多媒体元素 -> 获取src属性 -> 截取http网址 …

论前端开发的红颜知己-------饿了么UI

对于PC端开发的码农来看,这个组件库一定是耳熟能详了,以下总结了一下开发中常用的技巧,未来还会持续添加,期待----- 1.element.ui中的el-upload传递索引 index是外部v-for循环时的索引; :on-success的回调函数原本有三…

jquery图片放大镜代码

<script type="text/javascript" src="${path}/front/js/jquery-1.8.3.min.js"></script><script type="text/javascript">$(function(){//图片放大镜$(".imagess").mouseover(function(event){//获取新的图片var b…

ASP.NET 多/单 图片上传

前端暂时用layer框架&#xff1a; <% Page Language"C#" AutoEventWireup"true" CodeFile"Default.aspx.cs" Inherits"_Default" %><!DOCTYPE html><html xmlns"http://www.w3.org/1999/xhtml"> <hea…

IOS 如何获取与修改图片的EXIF信息

简介&#xff1a;Exif是一种图像文件格式&#xff0c;它的数据存储与JPEG格式是完全相同的。实际上Exif格式就是在JPEG格式头部插入了数码照片的信息&#xff0c;包括拍摄时的光圈、快门、白平衡、ISO、焦距、日期时间等各种和拍摄条件以及相机品牌、型号、色彩编码、拍摄时录制…

图片和多行文本垂直居中

图片和多行文本垂直居中 代码&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta name"keywords" content"zidingyi"><meta name"keywords" content"zidingyi"><meta charset&qu…

Python数据处理 - 查看海量图片

目标检测模型在测试集上做推理的时候,有时会是几十万张的规模,这样就没办法用文件资源管理器打开,会卡死,只能用程序一张张打开查看效果。 import matplotlib.pyplot as plt # plt 用于显示图片 import matplotlib.image as mpimg # mpimg 用于读取图片 import numpy as np imp…