Convert OpenCV image to PIL image in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV.
Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aid in editing, creating and saving images. Support for Python Imaging Library got discontinued in 2011, but a project named pillow forked the original PIL project and added Python3.x support to it. Pillow was announced as a replacement for PIL for future usage. Pillow supports numerous image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders.
The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference.
- Import module
- We will take the input image using imread method of cv2 library.
- path: A string representing the path of the image to be read.
- flag: It specifies how the image should be read. Its default value is cv2.IMREAD_COLOR.
Return Value: This method returns an image that is loaded from the specified file.
- Then we will use cv2.cvtColor() method of cv2 library to change the color convention.
cvtColor(src, code[, dst[, dstCn]])
- src: It is the image whose color space is to be changed.
- code: It is the color space conversion code.
- dst: It is the output image of the same size and depth as src image. It is an optional parameter.
- dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter.
Return Value: It returns an image.
- Displaying the image.
You will notice that both the images will be identical even after conversion. Hence, we can say that we have successfully converted an OpenCV image to a PIL Image.
Given below is the implementation using the above approach.
- OpenCV Image:
- PIL Image: