-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKmeans.py
83 lines (77 loc) · 2.61 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from PIL import Image
import numpy as np
import math
import random
import sys
im = Image.open('segmentation.jpg')
pix = im.load()
def Kmeans():
epoch = 0
pic = np.zeros((300,450), dtype=int)
summ = np.zeros((7,3), dtype=int)
num = np.zeros((7,), dtype=int)
photo = np.zeros((300,450,3), dtype=np.uint8)
cluster = []
cluster1 = np.random.random_integers(0, 255, (1, 3))
cluster2 = np.random.random_integers(0, 255, (1, 3))
cluster3 = np.random.random_integers(0, 255, (1, 3))
cluster4 = np.random.random_integers(0, 255, (1, 3))
cluster5 = np.random.random_integers(0, 255, (1, 3))
cluster6 = np.random.random_integers(0, 255, (1, 3))
cluster7 = np.random.random_integers(0, 255, (1, 3))
cluster.append(cluster1)
cluster.append(cluster2)
cluster.append(cluster3)
cluster.append(cluster4)
cluster.append(cluster5)
cluster.append(cluster6)
cluster.append(cluster7)
subtract = np.zeros((3,1), dtype=int)
distance = np.zeros((7,))
while epoch <= 0 :
for i in range (300):
for j in range (450):
for k in range (7):
subtract = np.subtract(pix[i,j], cluster[k])
distance[k] = np.inner(subtract,subtract)
d = distance.argmin()
pic[i,j] = d
for i in range (300):
for j in range (450):
if pic [i,j] == 0 :
summ[0] += pix[i,j]
num[0] += 1
if pic [i,j] == 1 :
summ[1] += pix[i,j]
num[1] += 1
if pic [i,j] == 2 :
summ[2] += pix[i,j]
num[2] += 1
if pic [i,j] == 3 :
summ[3] += pix[i,j]
num[3] += 1
if pic [i,j] == 4 :
summ[4] += pix[i,j]
num[4] += 1
if pic [i,j] == 5 :
summ[5] += pix[i,j]
num[5] += 1
if pic [i,j] == 6 :
summ[6] += pix[i,j]
num[6] += 1
for i in range (7):
if num[i] != 0 :
summ[i] = (summ[i]/num[i])
summ[i] = np.floor(summ[i])
cluster[i] = summ[i]
epoch += 1
for i in range (300):
for j in range (450):
for k in range (7):
if pic[i,j] == k:
photo [i,j] = cluster[k]
img = Image.fromarray(photo)
img.save('myimg.jpeg')
print ('hello yasi!')
def main():
Kmeans()