plt.figure(figsize=(20,20))
plt.subplot(221),plt.imshow(image, cmap=‘gray’),plt.title(‘Original’)
plt.xticks([]), plt.yticks([])
plt.subplot(222),plt.imshow(image_rescaled, cmap=‘gray’),plt.title(‘Rescaled’)
plt.xticks([]), plt.yticks([])
plt.subplot(223),plt.imshow(image_resized, cmap=‘gray’),plt.title(‘Resized’)
plt.xticks([]), plt.yticks([])
plt.subplot(224),plt.imshow(image_downscaled, cmap=‘gray’),plt.title(‘Downscaled’)
plt.xticks([]), plt.yticks([])
plt.show()
4、 Python Imaging Library(PIL)
Python Imaging Library(PIL)
已经成为 Python
事实上的图像处理标准库了,这是由于,PIL
功能非常强大,但API却非常简单易用。
但是由于PIL仅支持到 Python 2.7
,再加上年久失修,于是一群志愿者在 PIL
的基础上创建了兼容的版本,名字叫 Pillow
,支持最新 Python 3.x
,又加入了许多新特性,因此,我们可以跳过 PIL
,直接安装使用 Pillow
。
5、 Pillow
使用 Pillow
生成字母验证码图片:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
随机字母:
def rndChar():
return chr(random.randint(65, 90))
随机颜色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
240 x 60:
width = 60 * 6
height = 60 * 6
image = Image.new(‘RGB’, (width, height), (255, 255, 255))
创建Font对象:
font = ImageFont.truetype(‘/usr/share/fonts/wps-office/simhei.ttf’, 60)
创建Draw对象:
draw = ImageDraw.Draw(image)
填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
输出文字:
for t in range(6):
draw.text((60 * t + 10, 150), rndChar(), font=font, fill=rndColor2())
模糊:
image = image.filter(ImageFilter.BLUR)
image.save(‘code.jpg’, ‘jpeg’)
6、 SimpleCV
SimpleCV
是一个用于构建计算机视觉应用程序的开源框架。使用它,可以访问高性能的计算机视觉库,如 OpenCV,而不必首先了解位深度、文件格式、颜色空间、缓冲区管理、特征值或矩阵等术语。但其对于 Python3 的支持很差很差,在 Python3.7 中使用如下代码:
from SimpleCV import Image, Color, Display
load an image from imgur
img = Image(‘http://i.imgur.com/lfAeZ4n.png’)
use a keypoint detector to find areas of interest
feats = img.findKeypoints()
draw the list of keypoints
feats.draw(color=Color.RED)
show the resulting image.
img.show()
apply the stuff we found to the image.
output = img.applyLayers()
save the results.
output.save(‘juniperfeats.png’)
会报如下错误,因此不建议在 Python3
中使用:
SyntaxError: Missing parentheses in call to ‘print’. Did you mean print(‘unit test’)?
7、 Mahotas
Mahotas
是一个快速计算机视觉算法库,其构建在 Numpy
之上,目前拥有超过100种图像处理和计算机视觉功能,并在不断增长。
使用 Mahotas
加载图像,并对像素进行操作:
import numpy as np
import mahotas
import mahotas.demos
from mahotas.thresholding import soft_threshold
from matplotlib import pyplot as plt
from os import path
f = mahotas.demos.load(‘lena’, as_grey=True)
f = f[128:,128:]
plt.gray()
Show the data:
print(“Fraction of zeros in original image: {0}”.format(np.mean(f==0)))
plt.imshow(f)
plt.show()