IMAGE PROCESSING WITH NUMPY

Original article was published on Artificial Intelligence on Medium

IMAGE PROCESSING WITH NUMPY

In today’s article, I am going to discuss about how we can do image processing with Numpy array. I would like to give some example regarding this such as rotate, flip and so on.

reference: www.educuba.com

Role of Pillow Library

Pillow is a preferred image manipulation tool. Python version 2 used Python Image Library (PIL), and Python version 3 uses Pillow Python Library, an upgrade of PIL.

You should first create a virtual environment in Anaconda for different projects. Make sure you have supporting packages like NumPy, SciPy, and Matplotlib to install in the virtual environment you create.

pip install Pillow
or
sudo pip install Pillow

LOADING AN IMAGE WITH PILLOW

Select a test image to load and work with Pillow (PIL) library. Images can be either PNG or JPEG. In this example, we’ll use an image named kolala.jpeg. Either upload the image in the working directory or give your desired path.

The ‘format‘ property on the image will report the image format (e.g. JPEG), the ‘mode‘ will report the pixel channel format (e.g. RGB or CMYK), and the ‘size‘ will report the dimensions of the image in pixels (e.g. 640×480).

The show() function will display the image using your operating systems default application.

from PIL import Imageimage = Image.open('opera_house.jpg')# show the imageimage.show()

CONVERT INTO NUMPY AND THEN IT SAVED INTO IMAGE:

There are two function to do this:

asarray and np.array

The process can be reversed using the Image.fromarray() function.

from PIL import Image
my_image = Image.open(r’path’)
#convert image to numpyarray
data = asarray(my_image)
from PIL import Image
my_image= np.array(my_image)

How to save ndarray as image file

pil_img = Image.fromarray(my_image)
pil_img.save('./my_image.png')

VARIOUS OPERATION PERFORM ON IMAGE

NEGATIVE AND POSITIVE INVERSION

new_image= 255 - my_image

Image.fromarray(my_image).save('data/dst/lena_numpy_inverse.jpg')

RESIZE IMAGE

load_img = np.array(Image.open('image.jpeg').resize((200,200)))

COLOR CHANGE

my_image= image// 32 * 32

new_image= np.concatenate((image, my_image, my_image), axis=1)

Image.fromarray(new_image).save('new_image.png')

TRIM IMAGE

my_image= image[128:384, 128:384]
Image.fromarray(im_trim).save('image.jpeg')

CONCLUSION

There are many other ways are also available for doing same operation such as OpenCV and KerasAPI. There are many operation available you can do it as per your requirements such as black and white, copy image, zoom image, and so on.