Skip to content

color

Color

Bases: NumpyOp

Randomly change the color balance of an image.

This is a wrapper for functionality provided by the PIL library: https://github.com/python-pillow/Pillow/tree/master/src/PIL.

Parameters:

Name Type Description Default
inputs Union[str, Iterable[str]]

Key(s) of images to be modified.

required
outputs Union[str, Iterable[str]]

Key(s) into which to write the modified images.

required
mode Union[None, str, Iterable[str]]

What mode(s) to execute this Op in. For example, "train", "eval", "test", or "infer". To execute regardless of mode, pass None. To execute in all modes except for a particular one, you can pass an argument like "!infer" or "!train".

None
limit float

Factor range for changing color balance. If limit is a single float, the range will be (-limit, limit). A factor of 0.0 gives a black and white image and a factor of 1.0 gives the original image.

0.54
Image types

uint8

Source code in fastestimator\fastestimator\op\numpyop\univariate\color.py
@traceable()
class Color(NumpyOp):
    """Randomly change the color balance of an image.

    This is a wrapper for functionality provided by the PIL library:
    https://github.com/python-pillow/Pillow/tree/master/src/PIL.

    Args:
        inputs: Key(s) of images to be modified.
        outputs: Key(s) into which to write the modified images.
        mode: What mode(s) to execute this Op in. For example, "train", "eval", "test", or "infer". To execute
            regardless of mode, pass None. To execute in all modes except for a particular one, you can pass an argument
            like "!infer" or "!train".
        limit: Factor range for changing color balance. If limit is a single float, the range will be (-limit, limit).
            A factor of 0.0 gives a black and white image and a factor of 1.0 gives the original image.

    Image types:
        uint8
    """
    def __init__(self,
                 inputs: Union[str, Iterable[str]],
                 outputs: Union[str, Iterable[str]],
                 mode: Union[None, str, Iterable[str]] = None,
                 limit: float = 0.54):
        super().__init__(inputs=inputs, outputs=outputs, mode=mode)
        self.limit = param_to_range(limit)
        self.in_list, self.out_list = True, True

    def forward(self, data: List[np.ndarray], state: Dict[str, Any]) -> List[np.ndarray]:
        return [self._apply_color(elem) for elem in data]

    def _apply_color(self, data: np.ndarray) -> np.ndarray:
        im = Image.fromarray(data)
        factor = 1.0 + random.uniform(self.limit[0], self.limit[1])
        im = ImageEnhance.Color(im).enhance(factor)
        return np.array(im)