C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
OpenCV Read and Save ImageOpenCV Reading ImagesOpenCV allows us to perform multiple operations on the image, but to do that it is necessary to read an image file as input, and then we can perform the various operations on it. OpenCV provides following functions which are used to read and write the images. OpenCV imread functionThe imread() function loads image from the specified file and returns it. The syntax is: cv2.imread(filename[,flag]) Parameters:filename: Name of the file to be loaded flag: The flag specifies the color type of a loaded image:
The imread() function returns a matrix, if the image cannot be read because of unsupported file format, missing file, unsupported or invalid format. Currently, the following file formats are supported. Window bitmaps - *.bmp, *.dib Note: The color images, the decoded images will have the channels stored in the BGR order.Let's consider the following example: #importing the opencv module import cv2 # using imread('path') and 0 denotes read as grayscale image img = cv2.imread(r'C:\Users\DEVANSH SHARMA\cat.jpeg',1) #This is using for display the image cv2.imshow('image',img) cv2.waitKey(3) # This is necessary to be required so that the image doesn't close immediately. #It will run continuously until the key press. cv2.destroyAllWindows() Output: it will display the following image. OpenCV Save ImagesOpenCV imwrite() function is used to save an image to a specified file. The file extension defines the image format. The syntax is the following: cv2.imwrite(filename, img[,params]) Parameters:filename- Name of the file to be loaded image- Image to be saved. params- The following parameters are currently supported:
Let's consider the following example: import cv2 # read image as grey scale img = cv2.imread(r'C:\Users\DEVANSH SHARMA\cat.jpeg', 1) # save image status = cv2.imwrite(r'C:\Users\DEVANSH SHARMA\cat.jpeg', 0, img) print("Image written to file-system : ", status) Output: Image written to file-system : True If the imwrite() function returns the True, which means the file is successfully written in the specified file.
Next TopicBasic Operation On images
|