图像基本操作:PIL,Matplotlib

PIL:Python图像处理类库

  • PIL安装
sudo apt install python-pip # 安装pip
sudo pip install pillow
  • 读取一幅图像
# 读取一幅图像
from PIL import Image

im = Image.open('filename.jpg')

# 显示图像
im.show()

# 灰度图像
im_l = Image.open('filename.jpg').convert('L')
  • 转换图像格式
# 从文件名列表(filelist)中读取所有的图像文件,并转换成JPEG格式
from PIL import Image
import os

for infile in filelist:
    outfile = os.path.splitext(infile)[0] + ".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print "cannot convert", infile
  • 创建一个包含文件夹中所有图像文件的文件名列表
    imtool.py
import os
def get_imlist(path):
    """返回目录中所有JPG图像的文件名"""
    
    return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')]
  • 创建缩略图
from PIL import Image

im = Image.open('filename.jpg')

# 最长边为128像素的缩略图,图像比例不变
im.thumbnail((128, 128))
  • 裁剪图像
from PIL import Image

im = Image.open('filename.jpg')

# 裁剪指定区域
box = (100, 100, 400, 400) # 四元组的坐标依次是(左,上,右,下),PIL中指定坐标系的左上角坐标为(0,0)
region = im.crop(box) 

# 旋转180°
region = region.transpose(Image.ROTATE_180) 
im.paste(region, box) #粘贴图像区域
  • 调整尺寸和旋转
from PIL import Image

im = Image.open('filename.jpg')

out = im.resize((128, 128))  # 图像比例会改变
out = im.rotate(45) # 逆时针旋转45°

Matplotlib

  • 安装
sudo pip install matplotlib
  • 绘制图像、点和线
form PIL import Image
from pylab import *

# 读取图像到数组中
im = array(Image.open('filename.jpg'))

# 绘制图像
imshow(im)

# 一些点
x = [100, 100, 400, 400]
y = [200, 500, 200, 500]

# 使用红色星状标记绘制点
plot(x, y, 'r*')

# 绘制连接前两个点的线,默认蓝色
plot(x[:2], y[:2])

# 添加标题
title('plotting')
axis('off') # 坐标轴不显示
show() # 会阻断脚本,一般最后调用
plot(x, y)              # 默认为蓝色实线
plot(x, y, 'r*')        # 红色星状标记
plot(x, y, 'go-')       # 带有圆圈标记的绿线
plot(x, y, 'ks:')       # 带有正方形标记的黑色点线
颜色 命令
蓝色 'b'
绿色 'g'
红色 'r'
青色 'c'
品红 'm'
黄色 'y'
黑色 'k'
白色 'w'
线型 命令
实线 '-'
虚线 '--'
点线 ':'
标记 命令
'.'
圆圈 'o'
正方形 's'
星形 '*'
加号 '+'
叉号 'x'
  • 图像轮廓和直方图
from PIL import Image
from pylab import *

# 读取图像到数组中
im = array(Image.open('filename.jpg').convert('L'))

# 新建一个图像
figure()
# 不使用颜色信息
gray()
# 在原点的左上角显示轮廓图像
contour(im, origin='image')
axis('equal')
axis('off')

# 直方图
figure()
hist(im.flatten(), 128) # 小区间的数目,只接受一维数组所以要先压平
show()
  • 交互式标注
from PIL import Image
from pylab import *

im = array(Image.open('filename.jpg'))
imshow(im)
print 'Please click 3 points'
x = ginput(3)       # 把坐标保存在x列表中
print 'you clicked:', x
show()

你可能感兴趣的:(图像基本操作:PIL,Matplotlib)