PIL图像和OpenCV图像数据格式互相转换

本文介绍如何仔PIL和OpenCV之间图像数据的转换,因为有时候在图片处理速度上PIL会更胜一筹,现在这个转换方法写成一个函数,以便它转换具有灰度或 alpha 通道的图像。

PIL图像数据格式转换成OpenCV图像数据格式

1,使用cv2转换色彩的方法

import numpy as np
import cv2

def pil2cv(PIL_image):
    ''' PIL型 -> OpenCV型 '''
    cv2_image = np.array(PIL_image, dtype=np.uint8)
    if cv2_image.ndim == 2:  # 黑白
        pass
    elif cv2_image.shape[2] == 3:  # 彩色的3通道
        new_image = cv2.cvtColor(cv2_image, cv2.COLOR_RGB2BGR)
    elif cv2_image.shape[2] == 4:  # 包含透明的4通道
        cv2_image = cv2.cvtColor(cv2_image, cv2.COLOR_RGBA2BGRA)
    return cv2_image

2,不 使用cv2转换色彩的方法

import numpy as np

def pil2cv(PIL_image):
    ''' PIL型 -> OpenCV型 '''
    cv2_image = np.array(PIL_image, dtype=np.uint8)
    if cv2_image.ndim == 2:  # 黑白
        pass
    elif cv2_image.shape[2] == 3:  # 彩色的3通道
        cv2_image = cv2_image[:, :, ::-1]
    elif cv2_image.shape[2] == 4:  # 包含透明的4通道
        cv2_image = cv2_image[:, :, [2, 1, 0, 3]]

    return cv2_image 

OpenCV图像数据格式转换成PIL图像数据格式

1,使用cv2转换色彩的方法

from PIL import Image
import cv2

def cv2pil(cv2_image):
    ''' OpenCV型 -> PIL型 '''
    pil_image = cv2_image.copy()
    if pil_image.ndim == 2:  # 黑白
        pass
    elif pil_image.shape[2] == 3:   # 彩色的3通道
        pil_image = cv2.cvtColor(pil_image, cv2.COLOR_BGR2RGB)
    elif pil_image.shape[2] == 4:  # 包含透明的4通道
        pil_image = cv2.cvtColor(pil_image, cv2.COLOR_BGRA2RGBA)

    pil_image = Image.fromarray(pil_image)
    return pil_image

2,不使用cv2转换色彩的方法

from PIL import Image

def cv2pil(cv2_image):
    ''' OpenCV型 -> PIL型 '''
    pil_image = cv2_image.copy()
    if pil_image.ndim == 2:   # 黑白
        pass
    elif pil_image.shape[2] == 3:   # 彩色的3通道
        pil_image = pil_image[:, :, ::-1]
    elif pil_image.shape[2] == 4:  # 包含透明的4通道
        pil_image = pil_image[:, :, [2, 1, 0, 3]]
    pil_image = Image.fromarray(new_pil_imageimage)
    return pil_image

参考:
https://qiita.com/derodero24/items/f22c22b22451609908ee