### Color space conversion

I've been intrigued by Steven Pigeon's series on color spaces lately and wanted to give color space conversion a try in Python. In the following script I've reproduced several of the color spaces Pigeon mentions in the first five parts of the series.

Using NumPy this operation is almost trivial, but I added a few fun tidbits as well. Also note that, as I've mentioned before, PEP 465 has added the infix matrix multiplication operator

Using NumPy this operation is almost trivial, but I added a few fun tidbits as well. Also note that, as I've mentioned before, PEP 465 has added the infix matrix multiplication operator

`@`

to Python 3.5+.#! /usr/bin/env python3.6 # -*- coding: utf-8 -*- # vim:fenc=utf-8 """ Convert colorspaces. """ from typing import List from tqdm import tqdm from functools import reduce from operator import mul import numpy as np import imageio import os ## Colorspaces Kodak_1 = np.array([[ 1, 1, 1], [-1, -1, 1], [ 1, -1, -1]]) Kodak_YCC = np.array([[ 0.299, 0.587, 0.114], [-0.299, -0.587, 0.886], [ 0.701, -0.587, -0.114]]) Ohta = np.array([[ 1/3, 1/3, 1/3], [ 0.5, 0, 1/2], [-1/4, 1/2, -1/4]]) Xerox_YES = np.array([[0.253, 0.684, 0.063], [0.500, -0.500, 0 ], [0.250, 0.250, -0.500]]) YUV = np.array([[ 0.299, 0.587, 0.114], [-0.147, -0.289, 0.436], [ 0.615, -0.515, -0.100]]) YIQ = np.array([[0.299, 0.587, 0.114], [0.596, -0.275, -0.321], [0.212, -0.523, 0.311]]) _spaces = [Kodak_1, Kodak_YCC, Ohta, Xerox_YES, YUV, YIQ] def convert(im: np.array, transform: np.array) -> np.array: """ Convert an image array to another colorspace """ dimensions = len(im.shape) axes = im.shape[:dimensions-1] iters = reduce(mul, axes) # Create a new array (respecting mutability) new_ = np.empty(im.shape) for coordinate in tqdm(np.ndindex(axes), total=iters): pixel = im[coordinate] pixel_prime = transform @ pixel new_[coordinate] = pixel_prime return new_.astype(np.float16) def make_gif(transformed_imgs: List[np.array]) -> None: current_wd = os.getcwd() + '/' with imageio.get_writer(f'{current_wd}colorspaces.gif', mode='I', duration=1.0) as writer: for im in transformed_imgs: writer.append_data(im) def main() -> None: image = imageio.imread('~/Pictures/example.jpg') transforms = [] for space in _spaces: new_image = convert(image, space) transforms.append(new_image) make_gif(transforms) if __name__ == '__main__': main()Running this on an example image results in the following.