
1. 基本的图像操作和处理
1.1 PIL:Python图像处理类库
- 获取某个目录下的所有图片文件名列表函数
def get_imlist(path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.png')]
这是文件名后缀为.png的图片,也可以改为其它图片。
- 变换图片格式
filelist = get_imlist(path)
for infile in filelist:
outfile = os.path.splitext(infile)[0]+".jpg"
if infile != outfile:
try:
img = Image.open(infile)
if (len(img.split()))==4:
r,g,b,a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save(outfile)
except IOError:
print("Can't convert:", infile)
利用get_imlist()
函数,获得文件名列表。修改文件后缀为".jpg"。
- 创建缩略图
img.thumbnail((128,128))
这行代码可以创建最长边为128像素的缩略图。如果需要保存的话,可以直接用img.save(filename)
。
- 复制和粘贴图像区域
box = (100,100,400,400)
region = img.crop(box)
region = region.transpose(Image.ROTATE_180)
img.paste(region,box)
- 调整尺寸和旋转
out = img.resize((128,128))
out = img.rotate(45)
rotate逆时针方向旋转。
1.2 Matplotlib
- 绘制图像、点和线
from PIL import Image
from pylab import *
img = np.array(Image.open("1.png"))
x = [100,100,400,400]
y = [200,500,200,500]
plot(x,y,'r*')
plot(x[:2],y[:2],'r')
imshow(img)
title('Ploting')
axis('off')
show()
用PyLab库绘图的基本颜色格式命令:
颜色命令 | 颜色 |
---|---|
'b' | 蓝色 |
'g' | 绿色 |
'r' | 红色 |
'c' | 青色 |
'm' | 品红 |
'y' | 黄色 |
'k' | 黑色 |
'w' | 白色 |
用PyLab库绘图的基本线性格式命令
线型命令 | 线型 |
---|---|
'-' | 实线 |
'--' | 虚线 |
':' | 点线 |
用PyLab库绘图的基本绘制标记格式命令
标记 | 标记 |
---|---|
'.' | 点 |
'o' | 圆圈 |
's' | 正方形 |
'*' | 星形 |
'+' | 加号 |
'x' | 叉号❌ |
- 图像轮廓和直方图
from PIL import Image
from pylab import *
img = array(Image.open(filename).convert('L'))
figure()
gray()
contour(img,origin = 'image')
axis('equal')
axis('off')
figure()
hist(img.flatten(),128)
show()
- 交互式标注
from PIL import Image
from pylab import *
img = array(Image.open(filename).convert('L'))
imshow(img)
print("Please click 3 points")
x = ginput(3)
print("you clicked:', x)
show()
网友评论