Skip to content

Instantly share code, notes, and snippets.

@maweigert
Last active August 14, 2023 18:47
Show Gist options
  • Save maweigert/2242b5c0ebf88a3bc93721c79babc515 to your computer and use it in GitHub Desktop.
Save maweigert/2242b5c0ebf88a3bc93721c79babc515 to your computer and use it in GitHub Desktop.
import numpy as np
from colorsys import rgb_to_hls, hls_to_rgb
def _rgb2hls(im):
return np.stack(np.vectorize(rgb_to_hls)(*im.transpose(2,0,1)/256), axis=-1)
def _hls2rgb(im):
return (255*np.stack(np.vectorize(hls_to_rgb)(*im.transpose(2,0,1)), axis=-1)).astype(np.uint8)
def invert(img):
"""Invert a rgb image via lightness inversion
Parameters
----------
img: np.ndarray
The rgb image to be inverted.
Expects img.shape=(n,m,3) and img.dtype=np.uint8
"""
if not img.ndim==3 and img.shape[-1]==3 and img.dtype==np.uint8:
raise ValueError("input image should be of shape (n,m,3) and type np.uint8!")
tmp = _rgb2hls(img)
tmp[...,1] = 1-tmp[...,1]
return _hls2rgb(tmp)
if __name__ == '__main__':
# test it
from skimage.draw import line_aa
import matplotlib.pyplot as plt
# draw random colored lines
img = 255*np.ones((256,256,3), np.uint8)
for _ in range(10):
rr, cc, val = line_aa(*np.random.randint(0,img.shape[0],4))
img[rr, cc] = np.random.randint(100,255,3)
plt.imshow(np.concatenate([img,invert(img)], axis=1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment