Skip to content

Instantly share code, notes, and snippets.

@SubhrajitPrusty
Last active November 23, 2018 11:33
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 SubhrajitPrusty/0b9f8535cc0195382de7d670885dec1a to your computer and use it in GitHub Desktop.
Save SubhrajitPrusty/0b9f8535cc0195382de7d670885dec1a to your computer and use it in GitHub Desktop.
Generate and show a palette from the current image, video or camera
from PIL import Image, ImageDraw
import cv2
import numpy as np
import os
import sys
if len(sys.argv) < 2:
print("Needs file path ")
sys.exit(1)
fn = sys.argv[1]
if fn == "0":
fn = 0
else:
if not os.path.exists(fn):
print("Invalid path")
sys.exit(1)
cap = cv2.VideoCapture(fn)
while True:
ret, frame = cap.read()
rgbimg = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(rgbimg)
if fn != 0:
img = img.resize((img.width//2, img.height//2))
pal = img.convert('P', palette=Image.ADAPTIVE, colors=6)
pal.putalpha(0)
# pal.show()
colors = pal.getcolors(16*10**5)
colors = [c[1][:3] for c in colors]
colors = sorted(colors)
palheight = int(img.height*0.1)
palwidth = img.width
palimg = Image.new("RGB", (palwidth, palheight), "#000000")
draw = ImageDraw.Draw(palimg)
x = y = 0
shift = palwidth//len(colors)
for c in colors:
draw.rectangle([x,y, x+shift, y+palheight], fill=c)
x+= shift
# palimg.show()
newimg = Image.new("RGB", (img.width, img.height+palheight), "#000000")
newimg.paste(img, (0,0))
newimg.paste(palimg, (0, img.height))
cimg = cv2.cvtColor(np.array(newimg), cv2.COLOR_RGB2BGR)
cv2.imshow("Palette Gen", cimg)
# break
if cv2.waitKey(1) == 27:
break
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment