Last active
July 7, 2023 06:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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