Skip to content

Instantly share code, notes, and snippets.

@j20232
Created May 3, 2020 20:09
Show Gist options
  • Save j20232/6f18f6c16d37fcad1164c3030fbb1ff4 to your computer and use it in GitHub Desktop.
Save j20232/6f18f6c16d37fcad1164c3030fbb1ff4 to your computer and use it in GitHub Desktop.
pixelart.py
import numpy as np
import cv2
from sklearn import preprocessing
def convert_to_dot(img, color_num=16, dot_size=10):
lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB) / 255.0
flat_lab = lab.reshape((img.shape[0] * img.shape[1], 3))
Z = preprocessing.StandardScaler().fit_transform(flat_lab).astype(np.float32)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 1, 10.0)
_,label,_= cv2.kmeans(Z, color_num, None, criteria, 20, cv2.KMEANS_PP_CENTERS)
label = label.reshape(img.shape[0:2])
dot_img = img.copy()
for seg_id in np.unique(label):
dot_img[seg_id == label] = np.median(dot_img[seg_id == label].astype(np.uint8), axis = 0)
return cv2.resize(dot_img, dsize=None, fx=1/dot_size, fy=1/dot_size, interpolation=cv2.INTER_NEAREST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment