Home     Schedule     Mini-Project     Resources
 
Handing Images in Python

There are three ways of reading and writing images in Python, namely using Python Imaging Library (PIL), OpenCV with Python or PyOpenCV. The last one is an alternative wrapper for OpenCV. You will need to install these libraries if you want to use any of them.


Python Imaging Library

Import Python Imaging Library (PIL)
    import Image

Read and write PIL image
    pilimg = Image.open(“example.jpg”)
  pilimg.save(“pil.jpg”)


Convert PIL image to numpy array
    arr = numpy.array(pilimg)

Convert numpy array to PIL image
    pilimg = Image.fromarray(arr)


OpenCV with Python

Import OpenCV
    import cv

Read and write OpenCV image
    cvimg = cv.LoadImage(“example.jpg”)
  cv.SaveImage(“cv.jpg”, cvimg) )



PyOpenCV

Import PyOpenCV
    import pyopencv

Read and write PyOpenCV image
    pcvimg = pyopencv.imread(“example.jpg”)
  pyopencv.imwrite(“pcv.jpg”, pcvimg)


Convert PyOpenCV image to numpy array
    arr = pcvimg.asndarray

Convert numpy array to PyOpenCV image
    pcvimg = pyopencv.asMat(arr)

Convert PyOpenCV image to PIL image
  pilimage = pcvimg.to_pil_image()

Convert PIL image to PyOpenCV image
  pcvimg = pyopencv.Mat.from_pil_image(pilimg)
 
2 Oct 2016