2、 OpenCV
OpenCV
是一个的跨平台计算机视觉库,可以运行在 Linux、Windows 和 Mac OS 操作系统上。它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时也提供了 Python
接口,实现了图像处理和计算机视觉方面的很多通用算法。
下面代码尝试使用一些简单的滤镜,包括图片的平滑处理、高斯模糊等:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread(‘h89817032p0.png’)
kernel = np.ones((5,5),np.float32)/25
dst = cv.filter2D(img,-1,kernel)
blur_1 = cv.GaussianBlur(img,(5,5),0)
blur_2 = cv.bilateralFilter(img,9,75,75)
plt.figure(figsize=(10,10))
plt.subplot(221),plt.imshow(img[:,:,::-1]),plt.title(‘Original’)
plt.xticks([]), plt.yticks([])
plt.subplot(222),plt.imshow(dst[:,:,::-1]),plt.title(‘Averaging’)
plt.xticks([]), plt.yticks([])
plt.subplot(223),plt.imshow(blur_1[:,:,::-1]),plt.title(‘Gaussian’)
plt.xticks([]), plt.yticks([])
plt.subplot(224),plt.imshow(blur_1[:,:,::-1]),plt.title(‘Bilateral’)
plt.xticks([]), plt.yticks([])
plt.show()
可以参考OpenCV图像处理基础(变换和去噪),了解更多 OpenCV 图像处理操作。
3、 Scikit-image
scikit-image
是基于scipy
的图像处理库,它将图片作为numpy
数组进行处理。
例如,可以利用scikit-image
改变图片比例,scikit-image
提供了rescale
、resize
以及downscale_local_mean
等函数。
from skimage import data, color, io
from skimage.transform import rescale, resize, downscale_local_mean
image = color.rgb2gray(io.imread(‘h89817032p0.png’))
image_rescaled = rescale(image, 0.25, anti_aliasing=False)
image_resized = resize(image, (image.shape[0] // 4, image.shape[1] // 4),
anti_aliasing=True)
image_downscaled = downscale_local_mean(image, (4, 3))
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(