With the help of OpenCV, we can perform various operations on images. But, the most important operations are reading and saving images. In this tutorial, we will learn how to read and save images with OpenCV in python.
To read an image with OpenCV in Python, you can use the cv2.imread() function. This function takes a string specifying the file path of the image and returns an image.
The image file should be in the same directory as your Python script, or you should specify the full path to the file.
import cv2 image = cv2.imread(r'C:\Users\rohit\OneDrive\Pictures\Saved Pictures\header-background.png',1) cv2.imshow('image', image) cv2.waitKey(0) cv2.destroyAllWindows()
Here, first we imported cv2 and then we used cv2.imread to read the image of the given path. Then we used cv2.imshow to display the image. After this, we used cv2.waitkey(0) to wait for a keypress to close the image. At last, we used cv2.destroyAllWindows() to destroy all windows.
To save an image with OpenCV in Python, you can use the cv2.imwrite() function. This function takes a file path and an image and saves the image to the desktop.
import cv2 image = cv2.imread(r'C:\Users\rohit\OneDrive\Pictures\Saved Pictures\header-background.png',1) img_status = cv2.imwrite('opencv.jpg', image) print("Image is successfully saved: ", img_status)
Here, first we imported cv2 and then we used cv2.imread to read the image of the given path. Then we used cv2.imwrite to save the image as ‘opencv.jpg and declared it as img_status. At last, we printed the img_status as a boolean.
Image is successfully saved: True
Trainings :Python Training in Indore | Data Science Training in Indore | React JS Training in Indore | Blockchain Training in Indore | Data Analytics Training in Indore |
Free Courses and Resource :Clinical Data Managment | Pharmacovigilance | Database Management with SQL Server | Numpy | Pandas | Matplotlib | Power BI | React.js | Dart | Golang | Rust | Hacker Rank | Django | Leetcode | Aptitude Tests | Verbal Aptitude | ExpressJS | MongoDB | Python | Python Data Structures and Algorithms | OpenCV | Tensor Flow |
Interview Questions :Numpy | Pandas | React.js | Golang | Django | ExpressJS | Python |
Top Colleges in India :Indian Institute of Technology Bombay | Jaypee University of Engineering and Technology - Guna |