Basic GUI feature in OpenCV- Image

From Lofaro Lab Wiki
Jump to: navigation, search

In this tutorial you are going to know about basic GUI features of OpenCV. Basic feature includes image and video capturing, getting simple information from the image. You will also do some interesting application using the features. We can start with the image as it is the most fundamental component of starting image processing. Read an image:

You can read a stored image from your computer by using command


imread is a opencv function which can read an image. You can read an image in 3 possible ways which are color, grayscale or unchanged. If you want to read image in your expected way you have 3 methods for that which are as follows


First one will load a color image, second one will be gray and third one will read the image as it is. You might be wondering seeing the number beside the functions. These are called flags which makes it easy to define your expected image within the one basic function


This function takes two arguments one is the image you want to read and other is the expected type flag. For example if you want to read an images robot.jpg in color format you need to command


This will read the image as a color image. You can write few lines of codes to read an image

Import Numpy as np
Import cv2
# Load an image just as it is 
Image= cv2.imread(‘robot.jpg’,-1)

Show the image:

To show the image you just read, you need to use imshow function of OpenCV library.

cv2.imshow(‘image window’,image)

The function has two parameters where the first will define the name of the window where it will show the image and second one is your image. When you open up a window to show the image the code will be following

cv2.imshow(‘image window’,image)

cv2.waitkey() is a keyboard function which waits for specific milliseconds to get a event from the keyboard. In this case it will wait 0 milliseconds so as soon as you press a key from the keyboard the window will disappear. cv2.destroyAllWindow() function will do the job. If you have multiple windows working in same time you can pass the window name as argument to specify which window you want to close.

Save the image:

Saving the image is simple enough. Your function for this task would be cv2.imwrite (‘robot.png’,image) The first argument is the output of the image in the directory you are working and the second argument is your loaded image.

Before completing the tutorial, you should practice a program which will read an image, display it and save it to your computer. An example program is given below

import numpy as np
import cv2
imgage = cv2.imread('robot.jpg',0)
k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
elif k == ord('s'): # wait for 's' key to save and exit