-
Notifications
You must be signed in to change notification settings - Fork 1
/
kMeans.py
69 lines (56 loc) · 1.99 KB
/
kMeans.py
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
"""
This module takes the descriptor form ./Desc/ directory
and clusters then into number of specified centers for
each descriptor file. The cluster centers are saved to
./Centers/ directory.
"""
import numpy as np
import cv2
import pickle
import os
import sys
def kMeans(nCenters):
"""
This function takes descriptors stored in ./Desc/
directory one file at time. Loads the first half
and the runs kmeans from cv2 library to find out
cluster centers. Similary it does for the other half.
Finally both the cluster centers are merged and again
runs kmeans to find final cluster centers for that
particular object descriptors.
@param nCenters: Number of cluster centers.
"""
path = os.getcwd()
#Create directory Center if it does not exists
if not os.path.exists('Centers'):
os.makedirs('Centers')
os.chdir('Desc/')
criteria = (cv2.TERM_CRITERIA_MAX_ITER+cv2.TERM_CRITERIA_EPS, 100, 0.00001)
for i in os.listdir(os.getcwd()):
Desc = open(i,"rb") #: File pointer for descriptor file
center = np.zeros((0,128)) #: Populator for cluster centers
print(i)
while 1:
try:
des = pickle.load(Desc) #: Read descriptor into des(numpy array)
print(np.shape(des))
#Checking the version of opencv..
if cv2.__version__[0] == '3':
ret,label,center1=cv2.kmeans(des,int(nCenters),None,criteria,10,cv2.KMEANS_PP_CENTERS)
else:
ret,label,center1=cv2.kmeans(des,int(nCenters),criteria,10,cv2.KMEANS_PP_CENTERS)
del des
center = np.vstack((center,center1)) #: Append cluster centers
except EOFError:
break #: Detect End of file and break while loop
del center1
Center = open(path+"/Centers/"+i,"wb") #: File pointer for centers file
pickle.dump(center,Center) #: Save cluster centers to file
Center.close()
Desc.close()
del path
if __name__ == '__main__':
if(len(sys.argv)!=2):
print('Error. Usage: python kMeans.py numCenters')
else:
kMeans(sys.argv[1])