Python 中的图像处理(PIL(Python Imaging Library))
 
from PIL 
import Image
import matplotlib.pyplot 
as plt
%matplotlib inline 
img = Image.open(
'cat.jpg') 
print type(img) 
print img.format,img.size,img.mode
plt.imshow(img)
 
<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模块使用
 
import os
def getJpgList(path):
    
    
    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:
    
        outfile = os.path.splitext(filename)[
0] + 
'.png'
        if filename != outfile: 
            
try:
            
                Image.open(filename).save(outfile)       
                
print '%s has been converted to %s successfully' %(filename,outfile)
            
except 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