First Program using OpenCV - Show and Save Image

Hello friends! In last five posts, i have been sharing some important things which you need to know before learning OpenCV and i also explained installation process. I will explain first how to show and save image using OpenCV. Let's see-

Program:
import cv2
import numpy as npy

image = imread('Rit.jpg',-1)
cv2.imshow('windowname',image)

k = cv2.waitkey(0);
if k == 27:
    cv2.destroyAllWindows()
elif k == ord('s')
    cv2.imwrite('saved.jpg',image)
    cv2.destroyAllWindows()


Output:

Line 1:
importing OpenCV library.

Line 2:
importing numpy library( beacuse some functions take numpy array as an argument and also returns numpy array).

Line 3: 
imread(path, flag)

path: path of image where we are reading from. In this post we used to read our image from working. directory.

flag: Flag is just a way to read image. You can  give   1 or 0 or -1  as an argument for flag. 1 reads image   with colors but without transpiracy, 0 reads image   in grayscale and -1 reads image as it is.
 
  We read Rit.jpg image and stored in a variable.

Line 4:
imshow(winName, source) displays image in window.
winName/first argument: name of that window. source: image which we read using imread.

Line 5: 
waitkey(time)

this function returns key pressed on keyboard and   also waits for the time(in milliseconds) given in argument. If we pass 0 as an argument then it waits for infinite time.

Line 6: 
if the key pressed is escape(27).

Line 7: 
destroyAllWindows() close the window which we used to show image.

Line 8: 
if the key pressed is 's'.

Line 9: 
imwrite(path,source) is used to save image. This function is used when we make some changes in image and we want to save.

path: path where you want to save image. In this post we used to save in working directory.

source: image which you want to save.

Line 10: 
same as Line 7.

By R Patidar


Post a comment

1 Comments