python中PIL库的常⽤操作
版权声明:本⽂为博主原创⽂章,转载请注明出处。 blog.csdn/sinat_34474705/article/details/71368022 Python 中的图像处理(PIL(Python Imaging Library))
## Image是PIL中最重要的模块
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline
## 图像读取、显⽰
# 读取
img = Image.open('cat.jpg') # 创建⼀个PIL图像对象
print type(img) # PIL图像对象
print img.format,img.de
# 显⽰(为显⽰⽅便,这⾥调⽤plt.imshow显⽰)
plt.imshow(img)
# img.show()
<class 'PIL.JpegImagePlugin.JpegImageFile'>
JPEG (480, 360) RGB
<matplotlib.image.AxesImage at 0x7fce074f3210>
## 转换成灰度图像
img_gray = vert('L')
# 显⽰
plt.figure
plt.imshow(img_gray)
# 保存
img_gray.save('img_gray.jpg') # 保存灰度图(默认当前路径)
## 转换成指定⼤⼩的缩略图
img = Image.open('cat.jpg')
img_thumbnail = img.thumbnail((32,24))
print img.size
plt.imshow(img)
(32, 24)
<matplotlib.image.AxesImage at 0x7fce05b004d0>
## 复制和粘贴图像区域
img = Image.open('cat.jpg')
# 获取制定位置区域的图像
box = (100,100,400,400)
region = p(box)
plt.subplot(121)
plt.imshow(img)
plt.subplot(122)
plt.imshow(region)
<matplotlib.image.AxesImage at 0x7fce05a00710>
## 调整图像尺⼨和图像旋转
img = Image.open('cat.jpg')
# 调整尺⼨
img_resize = size((128,128))
plt.subplot(121)
plt.imshow(img_resize)
# 旋转
img_rotate = ate(45)
plt.subplot(122)
plt.imshow(img_rotate)
<matplotlib.image.AxesImage at 0x7fce058a4bd0>
PIL结合OS模块使⽤
## 获取指定路径下所有jpg格式的⽂件名,返回⽂件名列表
import os
def getJpgList(path):
# os.listdir(path): 返回path下所有的⽬录和⽂件
# dswith(str,start_index = 0,end_index = end): 判断字符串sring是否以指定的后缀str结果,返回True或False    jpgList =[f for f in os.listdir(path) dswith('.jpg')]
return jpgList
getJpgList('/home/meringue/Documents/PythonFile/imageProcessNotes/')
['img_gray.jpg',
matplotlib中subplot'fish-bike.jpg',
'building.jpg',
'cat.jpg',
'cat_thumb.jpg',
'lena.jpg']
## 批量转换图像格式
def convertJPG2PNG(path):
filelist = getJpgList(path)
print ''
for filename in filelist:
# os.path.splitext(filename): 分离⽂件名和扩展名
outfile = os.path.splitext(filename)[0] + '.png'
if filename != outfile: # 判断转换前后⽂件名是否相同
try:
# 读取转换前⽂件,并保存⼀份以outfile命名的新⽂件
Image.open(filename).save(outfile)
print '%s has been converted to %s successfully' %(filename,outfile)
except IOError: # 如果出现‘IOError’类型错误,执⾏下⾯操作
print 'cannot convert', filename
convertJPG2PNG('/home/meringue/Documents/PythonFile/imageProcessNotes/')
<
img_gray.jpg has been converted to img_gray.png successfully
fish-bike.jpg has been converted to fish-bike.png successfully
building.jpg has been converted to building.png successfully
cat.jpg has been converted to cat.png successfully
cat_thumb.jpg has been converted to cat_thumb.png successfully
lena.jpg has been converted to lena.png successfully

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。