This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.
Requirements:
- OpenCV 3.4
- Python 3.6+
- Numpy
- Image, Webcam, Video input
- Documentation Source: OpenCV Official Documentation
First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3
Goals:
In this tutorial, I will show you how to save OpenCV output image to a file.
Documentation:
Python: cv2.imwrite(filename, img[, params]) → retval
Saves an image to a specified file.
Parameters:
- filename – Name of the file.
- image – Image to be saved.
- params –
- Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, …. The following parameters are currently supported:
- For JPEG, it can be a quality (CV_IMWRITE_JPEG_QUALITY) from 0 to 100 (the higher is the better). Default value is 95.
- For PNG, it can be the compression level (CV_IMWRITE_PNG_COMPRESSION) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
- For PPM, PGM, or PBM, it can be a binary format flag (CV_IMWRITE_PXM_BINARY), 0 or 1. Default value is 1.
- Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, …. The following parameters are currently supported:
Steps:
- Load Image using cv2.imread()
- Display Image using cv2.imshow()
- Save the output in an image file using cv2.imwrite()
- Wait for keyboard button press using cv2.waitKey()
- Exit window and destroy all windows using cv2.destroyAllWindows()
Example Code:
import cv2 import numpy as np def main(): imgpath = "Hanif.jpg" img = cv2.imread(imgpath) #display the image cv2.imshow('Hanif_Life2Coding', img) outpath = "Hanif_Save.jpg" #save the image cv2.imwrite(outpath, img) cv2.waitKey(0) #destroy a certain window cv2.destroyWindow('Hanif_Life2Coding') if __name__ == "__main__": main()
Output:
Latest posts by Life2Coding (see all)
- How to Create a RGB Color Picker for Images using OpenCV Python - 22 April, 2022
- Combine Several Images Vertically with Padding using OpenCV Python - 21 April, 2022
- Combine Several Images Horizontally with Padding using OpenCV Python - 21 April, 2022