python中PIL库的常用操作

来源:互联网 发布:淘宝买彩票安全吗 编辑:程序博客网 时间:2024/05/29 02:25

Python 中的图像处理(PIL(Python Imaging Library))

## Image是PIL中最重要的模块from PIL import Imageimport matplotlib.pyplot as plt%matplotlib inline
## 图像读取、显示# 读取img = Image.open('cat.jpg') # 创建一个PIL图像对象print type(img) # PIL图像对象print img.format,img.size,img.mode# 显示(为显示方便,这里调用plt.imshow显示)plt.imshow(img)# img.show()
<class 'PIL.JpegImagePlugin.JpegImageFile'>JPEG (480, 360) RGB<matplotlib.image.AxesImage at 0x7fce074f3210>

这里写图片描述

## 转换成灰度图像img_gray = img.convert('L')# 显示plt.figureplt.imshow(img_gray)plt.gray()# 保存img_gray.save('img_gray.jpg') # 保存灰度图(默认当前路径)

这里写图片描述

## 转换成指定大小的缩略图img = Image.open('cat.jpg')img_thumbnail = img.thumbnail((32,24))print img.sizeplt.imshow(img)
(32, 24)<matplotlib.image.AxesImage at 0x7fce05b004d0>

这里写图片描述

## 复制和粘贴图像区域img = Image.open('cat.jpg')# 获取制定位置区域的图像 box = (100,100,400,400)region = img.crop(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 = img.resize((128,128))plt.subplot(121)plt.imshow(img_resize)# 旋转img_rotate = img.rotate(45)plt.subplot(122)plt.imshow(img_rotate)
<matplotlib.image.AxesImage at 0x7fce058a4bd0>

这里写图片描述

PIL结合OS模块使用

## 获取指定路径下所有jpg格式的文件名,返回文件名列表import osdef getJpgList(path):    # os.listdir(path): 返回path下所有的目录和文件    # string.endswith(str,start_index = 0,end_index = end): 判断字符串sring是否以指定的后缀str结果,返回True或False    jpgList =[f for f in os.listdir(path) if f.endswith('.jpg')]    return jpgListgetJpgList('/home/meringue/Documents/PythonFile/imageProcessNotes/')
['img_gray.jpg', 'fish-bike.jpg', 'building.jpg', 'cat.jpg', 'cat_thumb.jpg', 'lena.jpg']
## 批量转换图像格式def convertJPG2PNG(path):    filelist = getJpgList(path)    print 'converting...'    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', filenameconvertJPG2PNG('/home/meringue/Documents/PythonFile/imageProcessNotes/')
converting...img_gray.jpg has been converted to img_gray.png successfullyfish-bike.jpg has been converted to fish-bike.png successfullybuilding.jpg has been converted to building.png successfullycat.jpg has been converted to cat.png successfullycat_thumb.jpg has been converted to cat_thumb.png successfullylena.jpg has been converted to lena.png successfully
0 0
原创粉丝点击