Hello Dear Programmers,
OpenCV and PIL are the two most common libraries in Python to deal with images.
Therefore, while working on an image processing project, you might have felt the need of converting your image from PIL to OpenCV format and vice-versa.
So, here I am providing the code snippet to do that for all who are looking for it.
To convert from PIL to OpenCV, use:
cv2 numpy np PIL Image pil_image=Image. ( ) numpy_image=numpy.array(pil_img) opencv_image=cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)
To convert from OpenCV to PIL, use:
cv2 numpy np PIL Image opencv_image=cv2.imread( ) color_coverted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB) pil_image=Image.fromarray(color_coverted)
I hope it helped you with your project. Please let me know if it did. Thanks.
Buy Me a Coffee - https://www.buymeacoffee.com/agautam