-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkmean.py
More file actions
76 lines (60 loc) · 2.04 KB
/
kmean.py
File metadata and controls
76 lines (60 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import sampler, pickle
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from sklearn.cluster import KMeans
import numpy as np
from config import Config
frames = None
configs = None
def pixelDensity(x, y):
vec = frames[:,x, y]
binwidth = 25
plt.hist(vec, binwidth, normed=True)
plt.xlim((min(vec), max(vec)))
def cluster(x):
x = x.reshape(configs.nFrames, 1)
kmeans = KMeans(n_clusters=2, random_state=0).fit(x)
nC0 = kmeans.labels_.shape[0] - np.sum(kmeans.labels_)
nC1 = kmeans.labels_.shape[0] - nC0
print "C(Cluster 0):", nC0
print "C(Cluster 1):", nC1
if nC1 > nC0:
print "Centroid 1: Background\nCentroid 0: Foreground"
return kmeans.cluster_centers_[::-1], kmeans.labels_
else:
print "Centroid 0: Background\nCentroid 1: Foreground"
return kmeans.cluster_centers_, kmeans.labels_
def getBgPixel(vec, labels, bCent, fCent):
return bCent
def getBg(clip, cached=None):
bg = []
frames = sampler.getFrames(clip)
configs = Config(frames.shape)
print "Frame Dimension: ", frames.shape
if cached == None:
for i in xrange(configs.dim['x']):
for j in xrange(configs.dim['y']):
print "Pixel: %i, %i"%(i,j)
vec = frames[:, i, j]
cent, labels = cluster(vec)
# probs = probability(vec, cent)
bg.append(getBgPixel(vec, labels, cent[0][0], cent[1][0]))
bg = np.array(bg)
bg = bg.reshape(configs.dim['x'], configs.dim['y'])
with open('bin/bg_kmeans_%s.pkl'%clipName.split('/')[-1], 'wb') as f:
pickle.dump(bg, f)
return bg
# plt.imshow(bg, cmap='gray')
else:
print "!!! Extracting BG from cached files"
with open(cached, 'rb') as f:
bg = pickle.load(f)
return bg
if __name__ == '__main__':
getBg("data/nikwalking.mp4", "bin/k_means_nikwalking.pkl")
# X, Y = 225, 300
#
# vec = frames[:,X,Y]
# pixelDensity(X, Y)
# print cluster(vec)
plt.show()