Image Manipulation

https://d33wubrfki0l68.cloudfront.net/7a499e799f356a6fe2e695eed7a7d663f7c23c9e/e316e/_images/34575689432_3de8e9a348_k_d.jpg
Most image processing and manipulation techniques can be carried outeffectively using two libraries: Python Imaging Library (PIL) and Open SourceComputer Vision (OpenCV).

A brief description of both is given below.

Python Imaging Library

The Python Imaging Library, or PILfor short, is one of the core libraries for image manipulation in Python. Unfortunately,its development has stagnated, with its last release in 2009.

Luckily for you, there’s an actively-developed fork of PIL calledPillow – it’s easier to install, runs onall major operating systems, and supports Python 3.

Installation

Before installing Pillow, you’ll have to install Pillow’s prerequisites. Findthe instructions for your platform in thePillow installation instructions.

After that, it’s straightforward:

  1. $ pip install Pillow

Example

  1. from PIL import Image, ImageFilter
  2. #Read image
  3. im = Image.open( 'image.jpg' )
  4. #Display image
  5. im.show()
  6.  
  7. #Applying a filter to the image
  8. im_sharp = im.filter( ImageFilter.SHARPEN )
  9. #Saving the filtered image to a new file
  10. im_sharp.save( 'image_sharpened.jpg', 'JPEG' )
  11.  
  12. #Splitting the image into its respective bands, i.e. Red, Green,
  13. #and Blue for RGB
  14. r,g,b = im_sharp.split()
  15.  
  16. #Viewing EXIF data embedded in image
  17. exif_data = im._getexif()
  18. exif_data

There are more examples of the Pillow library in thePillow tutorial.

Open Source Computer Vision

Open Source Computer Vision, more commonly known as OpenCV, is a more advancedimage manipulation and processing software than PIL. It has been implementedin several languages and is widely used.

Installation

In Python, image processing using OpenCV is implemented using the cv2 andNumPy modules. The installation instructions for OpenCVshould guide you through configuring the project for yourself.

NumPy can be downloaded from the Python Package Index(PyPI):

  1. $ pip install numpy

Example

  1. import cv2
  2. #Read Image
  3. img = cv2.imread('testimg.jpg')
  4. #Display Image
  5. cv2.imshow('image',img)
  6. cv2.waitKey(0)
  7. cv2.destroyAllWindows()
  8.  
  9. #Applying Grayscale filter to image
  10. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  11.  
  12. #Saving filtered image to new file
  13. cv2.imwrite('graytest.jpg',gray)

There are more Python-implemented examples of OpenCV in this collection oftutorials.

原文: https://docs.python-guide.org/scenarios/imaging/