Saturday 25 June 2016

TUT2: Loading an image with Resizable Window

Hello everyone,

In the previous post we saw how to load an image. In this tutorial, we are going to see how to load an image in Resizable Window. This means that you will be able to resize the image as you want.

Let's start:

1) First import the necessary libraries:

    import cv2
    import numpy as np

2) Read the image:

    img = cv2.imread('hamster.jpg')

3) Create a window:

    cv2.namedWindow('image', cv2.WINDOW_NORMAL)

    Here the function namedWindow('window name', flag) is used to create a window. This window can be later used to show an image. The second parameter 'flag' refers to the type of window you want to create. These flags are given below:
  
           i) cv2.WINDOW_NORMAL :-  Resizable window
          ii) cv2.WINDOW_AUTOSIZE  :- Non-Resizable window. Program automatically assigns a                                                                         size.

There is one more flag that we will see later.

4) Displaying the image:

    cv2.imshow('image',img)

    Remember to use the same Window name in imshow() that you have created using                             namedWindow().

5) Hold the window : 

    cv2.waitKey(0)
    cv2.destroyAllWindows()

    cv2.waitKey(0) waits for a key press indefinitely. Once you press any key, the window closes.
    cv2.destroyAllWindows() closes any opened window.

After you have written the code press CTRL+S to save the code to a desired location. Remember to save the file using .py extension. After this, press F5 to run the code while your code is open in IDLE.
******************************************
Here's the summed up program:

Code:

import cv2
import numpy as np

img=cv2.imread('hamster.jpg')     #by default the second parameter is cv2.IMREAD_COLOR

cv2.namedWindow('image',cv2.WINDOW_NORMAL)        #allowing window to be resizable

cv2.imshow('image',img)

cv2.waitKey(0)
cv2.destroyAllWindows()

****************************************
Output:
  

As you can see I can now resize the displayed image.

That's it for this tutorial. If you have any doubt, you can ask me in the comments section.

ThankYou.

No comments:

Post a Comment