Created
July 5, 2021 16:00
-
-
Save panzi/1ceac1cb30bb6b3450aa5227c02eedd3 to your computer and use it in GitHub Desktop.
Python: Convert PIL.Image to OpenCV BGR(A)/grayscale image (NumPy array). This supports the most common image modes, but there are more! Patches for those are welcome.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import numpy as np | |
import cv2 | |
def pil2cv(image: Image) -> np.ndarray: | |
mode = image.mode | |
new_image: np.ndarray | |
if mode == '1': | |
new_image = np.array(image, dtype=np.uint8) | |
new_image *= 255 | |
elif mode == 'L': | |
new_image = np.array(image, dtype=np.uint8) | |
elif mode == 'LA' or mode == 'La': | |
new_image = np.array(image.convert('RGBA'), dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA) | |
elif mode == 'RGB': | |
new_image = np.array(image, dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) | |
elif mode == 'RGBA': | |
new_image = np.array(image, dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA) | |
elif mode == 'LAB': | |
new_image = np.array(image, dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_LAB2BGR) | |
elif mode == 'HSV': | |
new_image = np.array(image, dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_HSV2BGR) | |
elif mode == 'YCbCr': | |
# XXX: not sure if YCbCr == YCrCb | |
new_image = np.array(image, dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_YCrCb2BGR) | |
elif mode == 'P' or mode == 'CMYK': | |
new_image = np.array(image.convert('RGB'), dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) | |
elif mode == 'PA' or mode == 'Pa': | |
new_image = np.array(image.convert('RGBA'), dtype=np.uint8) | |
new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA) | |
else: | |
raise ValueError(f'unhandled image color mode: {mode}') | |
return new_image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment