Working with images

A short code to destroy the image window or to save the image in a file using keyboard buttons.

prerequisites: images_basic

import cv2
img=cv2.imread("C:\\Users\\amol\\Desktop\\goku.jpg",1)
cv2.imshow("goku",img)
key=cv2.waitKey(0)
if key==27: 
    cv2.destroyAllWindows()
elif key==ord('s'):
    cv2.imwrite('goku.jpg',img)
    cv2.destroyAllWindows()

Here we are storing the entered key in the variable ‘key’

Then we check which key is pressed . The ASCII code for escape button is ’27’ , if ‘escape’ button is pressed then the window will be destroyed

If ‘s’ button is pressed then the image will be saved. For this we use the function ord() and pass the parameter as ‘s’. So on hitting the ‘s’ button on our keyboard the image will be saved automatically.

Leave a Reply