-
Tamino Huxohl authoredTamino Huxohl authored
util.py 1.27 KiB
from typing import Optional
import numpy as np
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
def to_grayscale(
img: np.ndarray, min_val: Optional[float] = None, max_val: Optional[float] = None
):
"""
Convert an arbitrary image to a grayscale image with a value range of [0, 255].
:param img: the image to be converted to grayscale
:param min_val: minimum value used for normalization, this is helpful if the image has to be normalized relative to others
:param max_val: maximum value used for normalization, this is helpful if the image has to be normalized relative to others
:return: the image in grayscale
"""
if min_val is None:
min_val = img.min()
if max_val is None:
max_val = img.max()
if (max_val - min_val) == 0:
return np.zeros(img.shape, np.uint8)
_img = (img - min_val) / (max_val - min_val)
_img = (_img * 255).astype(np.uint8)
return _img
def grayscale_to_rgb(img: np.ndarray):
"""
Convert a grayscale image to an rgb image by repeating it three times.
:param img: the grayscale image to be converted to rgb
:return: the image in rgb
"""
assert img.ndim == 2, f"grascale image has more than 2 dimensions {img.shape}"
return img.repeat(3).reshape((*img.shape, 3))