画像ライブラリの相互変換

タグ:

Pythonで画像を扱う際はPillowやOpenCV2を使うことが多いのですが、nnablaのimage_utilsを使うことが増えたので、相互変換する際のメモを。

import sys
# Pillow
import PIL
import PIL.Image
# OpenCV
import cv2
import numpy as np
# Neural Network Library
import nnabla.utils.image_utils


def main():

    # ------------------------------------------------------ nnabla to nnabla
    print("nnabla")

    o_nnl_image = nnabla.utils.image_utils.imload(sys.argv[1])
    print(type(o_nnl_image), o_nnl_image.shape)  # type, (h, w, c)
    nnabla.utils.image_utils.imsave("test_nnl_to_nnl.png", o_nnl_image)

    # nnabla to OpenCV
    # RGB to BGR
    # o_nnl_image[:, :, ::-1].copy()
    o_cv2_image = cv2.cvtColor(o_nnl_image, cv2.COLOR_BGR2RGB)
    print(type(o_cv2_image), o_cv2_image.shape)  # type, (h, w, c)
    cv2.imwrite("test_nnl_to_cv2.png", o_cv2_image)

    # nnabla to Pillow
    o_pil_image = PIL.Image.fromarray(o_nnl_image)
    print(type(o_pil_image), o_pil_image.size,
          o_pil_image.mode)  # type, w, h, mode
    o_pil_image.save("test_nnl_to_pil.png")

    # ------------------------------------------------------ Pillow to Pillow
    print("Pillow")

    o_pil_image = PIL.Image.open(sys.argv[1])
    print(type(o_pil_image), o_pil_image.size,
          o_pil_image.mode)  # type, w, h, mode
    o_pil_image.save("test_pil_to_pil.png")

    # Pillow to OpenCV
    # PI.Image.Image to numpy.ndarray
    o_image = np.asarray(o_pil_image)
    # RGB to BGR
    # o_cv2_image = o_image[:, :, ::-1].copy()
    o_cv2_image = cv2.cvtColor(o_nnl_image, cv2.COLOR_RGB2BGR)

    print(type(o_cv2_image), o_cv2_image.shape)  # type, (h, w, c)
    cv2.imwrite("test_pil_to_cv2.png", o_cv2_image)

    # Pillow to nnabla
    o_nnl_image = np.asarray(o_pil_image)
    print(type(o_nnl_image), o_nnl_image.shape)  # type, (h, w, c)
    nnabla.utils.image_utils.imsave("test_pil_to_nnl.png", o_nnl_image)

    # ------------------------------------------------------ OpenCV to OpenCV
    print("OpenCV")

    o_cv2_image = cv2.imread(sys.argv[1])
    print(type(o_cv2_image), o_cv2_image.shape)  # type, (h, w, c)
    cv2.imwrite("test_cv2_to_cv2.png", o_cv2_image)

    # OpenCV to nnabla
    # BGR to RGB
    # o_nnl_image = o_cv2_image[:, :, ::-1].copy()
    o_nnl_image = cv2.cvtColor(o_cv2_image, cv2.COLOR_BGR2RGB)
    print(type(o_nnl_image), o_nnl_image.shape)  # type, (h, w, c)
    nnabla.utils.image_utils.imsave("test_cv2_to_nnl.png", o_nnl_image)

    # OpenCV to Pillow
    # BGR to RGB
    # o_image = o_cv2_image[:, :, ::-1].copy()
    o_image = cv2.cvtColor(o_cv2_image, cv2.COLOR_BGR2RGB)
    # numpy.ndarray to PIL.Image.Image
    o_pil_image = PIL.Image.fromarray(o_image)
    print(type(o_pil_image), o_pil_image.size,
          o_pil_image.mode)  # type, w, h, mode
    o_pil_image.save("test_cv2_to_pil.png")


if __name__ == "__main__":
    main()