Skip to content

Instantly share code, notes, and snippets.

@austindoeswork
Created November 29, 2017 21:05
Show Gist options
  • Save austindoeswork/be67cb994f86e5b129659d7e2fa57eed to your computer and use it in GitHub Desktop.
Save austindoeswork/be67cb994f86e5b129659d7e2fa57eed to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from sklearn.cluster import KMeans
import cv2
import sys
def getPixelFeatures(img):
D = img.reshape((img.shape[0] * img.shape[1], 3))
r = np.arange(0, img.shape[0])
c = np.arange(0, img.shape[1])
rc = np.array([[i,j] for i in r for j in c])
D = np.concatenate((rc,D), axis = 1).astype(float)
return D
# Get command line args
if len(sys.argv) < 3:
print("USAGE: cv.py img k")
img = cv2.imread(sys.argv[1])
# img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (0,0), fx=0.3, fy=0.3)
k = int(sys.argv[2])
km = KMeans(n_clusters = k)
D = getPixelFeatures(img)
D_norm = D / D.max(axis=0)
print(D_norm)
km.fit(D_norm)
print(km.labels_)
colors = km.labels_.reshape((img.shape[0], img.shape[1]))
# colors = colors * (255/np.max(colors))
fig = plt.figure()
def f(x, y):
return np.cos(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(img, animated=True, cmap='gray')
0
# grow = [0, 0, 0, 0, 0,
growl = list(range(1,20))
growl = growl[::-1]
growc = [1,1,1]
growr = list(range(1,20))
grow = growl + growc + growr
print(grow)
temp = 0
def updatefig(*args):
global temp
f = args[0]
color = colors.copy()
# print(color)
# color[color == f%k] = 255
color[color == temp] = 255
color[color != 255] = 0
kernel = np.ones((5,5),np.uint8)
color = cv2.dilate(color.astype(np.uint8), kernel, iterations = grow[f%len(grow)])
if f % len(grow) == len(grow)-1:
temp = temp + 1
if temp == k:
temp = 0
im.set_array(color)
# x += np.pi / 15.
# y += np.pi / 20.
# im.set_array(f(x, y))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=10, blit=True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment