Skip to content

Instantly share code, notes, and snippets.

@agness
Last active July 7, 2023 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agness/863918fdb8934bcedb4b97e089d3431e to your computer and use it in GitHub Desktop.
Save agness/863918fdb8934bcedb4b97e089d3431e to your computer and use it in GitHub Desktop.
Given an image file, splits into N bitmaps of identical dimensions, one each for each unique color in the input file.
#!/usr/bin/env python3
# Given an image file, splits into N bitmaps of identical dimensions, one each
# for each unique color in the input file.
# via https://stackoverflow.com/a/65392173
# Requirements
# pip3 install opencv-python
import cv2
import numpy as np
import argparse
# Handle input
parser = argparse.ArgumentParser(description='Split an image by color into bitmap layers.')
parser.add_argument('inputfile', metavar='F', type=str, nargs=1,
help='Filename of image to be split into bitmap layers.')
args = parser.parse_args()
f = args.inputfile[0]
print(f'Opening image {f}...')
# Load image
im = cv2.imread(f)
# Reshape into a tall column of pixels, each with 3 RGB pixels and get unique rows (colors)
colors = np.unique(im.reshape(-1,3), axis=0)
# Iterate over the colors we found
for i,color in enumerate(colors):
print(f'Exporting color {i}: {color[::-1]}') # print in RGB order
res = np.where((im==color).all(axis=-1),255,0)
cv2.imwrite(f'color-{i}.png', res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment