OpenCV Read and Save Image
OpenCV Reading Images
OpenCV 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 function
The imread() function loads image from the specified file and returns it. The syntax is:
Parameters:
filename: Name of the file to be loaded
flag: The flag specifies the color type of a loaded image:
- CV_LOAD_IMAGE_ANYDEPTH - If we set it as flag, it will return 16-bits/32-bits image when the input has the corresponding depth, otherwise convert it to 8-BIT.
- CV_LOAD_IMAGE_COLOR - If we set it as flag, it always return the converted image to the color one.
- C V_LOAD_IMAGE_GRAYSCALE - If we set it as flag, it always convert image into the grayscale.
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
JPEG files - *.jpeg, *.jpg, *.jpe
Portable Network Graphics - *.png
Portable image format- *.pbm, *.pgm, *.ppm
TIFF files - *.tiff, *.tif
Let's consider the following example:
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 Images
OpenCV imwrite() function is used to save an image to a specified file. The file extension defines the image format. The syntax is the following:
Parameters:
filename- Name of the file to be loaded
image- Image to be saved.
params- The following parameters are currently supported:
- For JPEG, quality can be from 0 to 100. The default value is 95.
- For PNG, quality can be the compress level from 0 to 9. The default value is 1.
- For PPM, PGM, or PBM, it can be a binary format flag 0 or 1. The default value is 1.
Let's consider the following example:
# 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.