python中PIL库的常用操作

xiaoxiao2021-02-28  52

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.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.figure plt.imshow(img_gray) plt.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 = 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 os def 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 jpgList getJpgList('/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', filename convertJPG2PNG('/home/meringue/Documents/PythonFile/imageProcessNotes/') converting... 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
转载请注明原文地址: https://www.6miu.com/read-83140.html

最新回复(0)