From 9d8a235bd95d0c902c7a928d7d261929d974393d Mon Sep 17 00:00:00 2001 From: 283375 Date: Wed, 6 Sep 2023 21:52:32 +0800 Subject: [PATCH] feat: sRGB color space convert util --- src/arcaea_offline_ocr/utils.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/arcaea_offline_ocr/utils.py b/src/arcaea_offline_ocr/utils.py index 33eec22..e968dce 100644 --- a/src/arcaea_offline_ocr/utils.py +++ b/src/arcaea_offline_ocr/utils.py @@ -1,8 +1,10 @@ +import io from collections.abc import Iterable from typing import Callable, Tuple, TypeVar, Union, overload import cv2 import numpy as np +from PIL import Image, ImageCms from .types import Mat, XYWHRect @@ -44,3 +46,25 @@ def apply_factor(item, factor: float): return item * factor elif isinstance(item, Iterable): return item.__class__([i * factor for i in item]) + + +def convert_to_srgb(pil_img: Image.Image): + """ + Convert PIL image to sRGB color space (if possible) + and save the converted file. + + https://stackoverflow.com/a/65667797/16484891 + + CC BY-SA 4.0 + """ + icc = pil_img.info.get("icc_profile", "") + icc_conv = "" + + if icc: + io_handle = io.BytesIO(icc) # virtual file + src_profile = ImageCms.ImageCmsProfile(io_handle) + dst_profile = ImageCms.createProfile("sRGB") + img_conv = ImageCms.profileToProfile(pil_img, src_profile, dst_profile) + icc_conv = img_conv.info.get("icc_profile", "") + + return img_conv if icc != icc_conv else pil_img