OpenCV+Python:Part1–Working with Images

This post is about opening,displaying and saving images.


This function is used to read an image. Either the image is in the current working directory or the full path is provided as an argument.

The second argument specifies the way the image is read.

1.)cv2.IMREAD_COLOR : x = cv2.imread('image.jpg',1)— Loads a color image. Any transparency of image will be neglected. It is the default flag.

2.)cv2.IMREAD_GRAYSCALE : x = cv2.imread('image.jpg',0)— Loads image in gray-scale mode.
3.)cv2.IMREAD_UNCHANGED : x = cv2.imread('image.jpg',-1)— Loads image as such including alpha channel.

The full code to load an image would look something like this:

import numpy as np
import cv2
x = cv2.imread('image.jpg',1)



This function is used to display an image in a window.The window automatically fits the image size.
There are two arguments again.The first argument provides a name to the window given as a string. The second argument provides the variable in which the image is stored.


The full code to create a window that stays until an exit key is pressed is as follows:


cv2.waitKey(0) takes arguments as milliseconds. Passing 0 makes the function wait until any key is pressed. For 64-bit machine the code has to of this form : cv2.waitKey(0) & 0xFF

cv2.destroyAllWindows() does as the name suggests.



This function is used to save the image after processing.It takes in two arguments. First is the name of the file to written. Second is the variable in which the image is saved.



The whole post can be summarized by the following code. It loads an image from the current working directory and saves it as a png black n white image.

import numpy as np
import cv2
x = cv2.imread('image.jpg',0) #load a jpg image
cv2.imshow('image',x) #display image
cv2.waitKey(0) & 0xFF #wait for key press
cv2.imwrite('image.png',x) #save the image as png
cv2.destroyAllWindows() #destroy all windows

Thats all !!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s