Skip to content

Instantly share code, notes, and snippets.

@ssethsara
Last active June 6, 2020 11:33
Show Gist options
  • Save ssethsara/bc4ece5f2d959e6b434b73db29959248 to your computer and use it in GitHub Desktop.
Save ssethsara/bc4ece5f2d959e6b434b73db29959248 to your computer and use it in GitHub Desktop.
This code part i used to change each pixel color to it's nearest main color and give it more cartoon look.But my main intention was to identify dominant primary and secondary colors of those images
# import the necessary packages
import numpy as np
import scipy.spatial as sp
import matplotlib.pyplot as plt
import cv2
#Stored all RGB values of main colors in a array
main_colors = [(0,0,0),
(255,255,255),
(255,0,0),
(0,255,0),
(0,0,255),
(255,255,0),
(0,255,255),
(255,0,255),
]
image = cv2.imread("test.jpg")
#convert BGR to RGB image
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h,w,bpp = np.shape(image)
#Change colors of each pixel
#reference :https://stackoverflow.com/a/48884514/9799700
for py in range(0,h):
for px in range(0,w):
########################
#Used this part to find nearest color
#reference : https://stackoverflow.com/a/22478139/9799700
input_color = (image[py][px][0],image[py][px][1],image[py][px][2])
tree = sp.KDTree(main_colors)
ditsance, result = tree.query(input_color)
nearest_color = main_colors[result]
###################
image[py][px][0]=nearest_color[0]
image[py][px][1]=nearest_color[1]
image[py][px][2]=nearest_color[2]
# show image
plt.figure()
plt.axis("off")
plt.imshow(image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment