用Python简单处理图片
使用python进行数字图片处理,还得安装Pillow包。虽然python里面自带一个PIL(pythonimageslibrary),但这个库现在已经停止更新了,所以使用Pillow,它是由PIL发展而来的。
pipinstallPillow
一、图片的打开与显示
fromPILimportImage
img=Image.open('d:/dog.png')
img.show()
虽然使用的是Pillow,但它是由PILfork而来,因此还是要从PIL中进行import.使用open()函数来打开图片,使用show()函数来显示图片。
这种图片显示方式是调用操作系统自带的图片浏览器来打开图片,有些时候这种方式不太方便,因此我们也可以使用另上一种方式,让程序来绘制图片。
fromPILimportImage
importmatplotlib.pyplotasplt
img=Image.open('d:/dog.png')
plt.figure("dog")
plt.imshow(img)
plt.show()
这种方法虽然复杂了些,但推荐使用这种方法,它使用一个matplotlib的库来绘制图片进行显示。matplotlib是一个专业绘图的库,相当于matlab中的plot,可以设置多个figure,设置figure的标题,甚至可以使用subplot在一个figure中显示多张图片。matplotlib可以直接安装
pipinstallmatplotlib
figure默认是带axis的,如果没有需要,我们可以关掉
plt.axis('off')
打开图片后,可以使用一些属性来查看图片信息,如
printimg.size#图片的尺寸
printimg.mode#图片的模式
printimg.format#图片的格式
显示结果为:
(558,450)
RGBA
PNG
二、图片的保存
img.save('d:/dog.jpg')
就一行代码,非常简单。这行代码不仅能保存图片,还是转换格式,如本例中,就由原来的png图片保存为了jpg图片。
以上内容为大家介绍了用Python简单处理图片,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
为什么Python爬虫使用MongoDB?
想必大家都知道,在从事网络爬虫工作之前,我们需要掌握很多知识,除了基本的爬虫原理之外,我们还需要学习框架、数据库等,其中就包含MongoDB...详情>>
2023-11-07 23:02:10
python如何进行类型转换的
python提供了将变量或值从一种类型转换成另一种类型的内置函数。1、int:将符合数学格式数字型字符串转换成整数。>>>int('123')1232、s...详情>>
2023-11-07 18:51:20
python怎么生成随机数
以下实例演示了python如何生成一个随机数:#生成0~9之间的随机数#导入random(随机数)模块importrandomprint(random.randint(0,9))执行以上代码...详情>>
2023-11-07 17:09:17
python如何删除空格
python中的字符串方法提供了如下常用的方法来删除空白:strip():删除字符串前后的空白。lstrip():删除字符串前面(左边)的空白。rstrip():删...详情>>
2023-11-07 14:57:44热门推荐
技术干货






