About Lesson
In this Python OpenCV lesson we are going to learn about Python OpenCV Writing to Image, we will learn that how you can write to an image in OpenCV, how you can work with keyboard events and also how you can convert a tif image to jpg image.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import cv2 lena_image = cv2.imread('lena.tif') cv2.imshow("Lena Image", lena_image) k = cv2.waitKey(0) #if user press escape key, we are going to close the window if k == 27: cv2.destroyAllWindows() #if the user press s key we are going to save the image elif k == ord('s'): cv2.imwrite('newimage.jpg', lena_image) cv2.destroyAllWindows() |
First of we are going to read or load our image.
1 |
lena_image = cv2.imread('lena.tif') |
After that we are going to create our wait key.
1 |
k = cv2.waitKey(0) |
In here we are checking if the user press escape key, we are going to close the window.
1 2 |
if k == 27: cv2.destroyAllWindows() |
And if the user press s key we are going to save the image, for this we are going to use cv2.imwrite() function.
1 2 3 |
elif k == ord('s'): cv2.imwrite('newimage.jpg', lena_image) cv2.destroyAllWindows() |
You can run the complete code and after that press s key you will see that we have a new image with jpg format in our working directory.
![Python OpenCV Writing Image](https://geekscoders.com/wp-content/uploads/2021/03/python-opencv-writing-image.jpg)