图像处理

../_images/34575689432_3de8e9a348_k_d.jpg

大多数图像处理和操作技术可以有效地使用两个库:Python图像库(PIL)和开源计算机视觉(OpenCV)。

下面简要介绍了这两种情况。

Python图像库

Python Imaging Library 或者简称PIL,是Python中用于图像操作的核心库之一。不幸的是,它的开发停滞了,最后一次发布是在2009年。

幸运的是,有一个积极开发的PIL分支称为 Pillow --它更容易安装,在所有主要操作系统上运行,并且支持python 3。

安装

在安装枕头之前,您必须安装枕头的先决条件。在中查找平台的说明 Pillow installation instructions .

之后,很简单:

$ pip install Pillow

例子

from PIL import Image, ImageFilter
#Read image
im = Image.open( 'image.jpg' )
#Display image
im.show()

#Applying a filter to the image
im_sharp = im.filter( ImageFilter.SHARPEN )
#Saving the filtered image to a new file
im_sharp.save( 'image_sharpened.jpg', 'JPEG' )

#Splitting the image into its respective bands, i.e. Red, Green,
#and Blue for RGB
r,g,b = im_sharp.split()

#Viewing EXIF data embedded in image
exif_data = im._getexif()
exif_data

Pillow library在 Pillow tutorial .

开源计算机视觉

开源计算机视觉,通常被称为OpenCV,是一种比PIL更先进的图像处理软件。它已经用几种语言实现,并被广泛使用。

安装

在Python中,使用opencv的图像处理是使用 cv2NumPy 模块。这个 installation instructions for OpenCV 应该指导您自己配置项目。

可以从Python包索引(pypi)下载NumPy:

$ pip install numpy

例子

import cv2
#Read Image
img = cv2.imread('testimg.jpg')
#Display Image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

#Applying Grayscale filter to image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#Saving filtered image to new file
cv2.imwrite('graytest.jpg',gray)

有更多的Python实现的opencv示例 collection of tutorials