Skip to content

Commit 2fe71da

Browse files
committed
rearranged files into one implementation
1 parent bd9666b commit 2fe71da

File tree

18 files changed

+234
-220
lines changed

18 files changed

+234
-220
lines changed
Lines changed: 53 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,53 @@
1-
import tkinter as tk
2-
from tkinter import filedialog
3-
from PIL import Image
4-
import numpy as numpy
5-
6-
def getImage(filename):
7-
"""Returns a two dimensional array of a chosen image's pixels"""
8-
9-
"""
10-
root = tk.Tk()
11-
root.withdraw()
12-
file_path = filedialog.askopenfilename()
13-
file = open(file_path)
14-
filename = file.name
15-
print(file.name)
16-
"""
17-
try:
18-
image = Image.open(filename, 'r')
19-
except Exception as e:
20-
print(e)
21-
22-
return image
23-
24-
def ImageToArray(image):
25-
width, height = image.size
26-
pixel_values = list(image.getdata())
27-
color_array = []
28-
for h in range(height):
29-
color_array.append([])
30-
for w in range(width):
31-
color_array[h].append(pixel_values[h*width+w])
32-
return color_array
33-
34-
35-
def ImageToMatrix(image):
36-
array = numpy.asarray(image)
37-
return array
38-
39-
if __name__ == "__main__":
40-
image = getImage()
41-
#matrix = ImageToMatrix(image)
42-
#print(matrix)
43-
array = ImageToArray(image)
44-
for row in array:
45-
print(row)
46-
exit = input("Type any enter to exit")
1+
import tkinter as tk
2+
from tkinter import filedialog
3+
from PIL import Image
4+
import numpy as numpy
5+
6+
def getImage(filename):
7+
"""Returns a two dimensional array of a chosen image's pixels"""
8+
try:
9+
image = Image.open(filename, 'r')
10+
except Exception as e:
11+
print(e)
12+
13+
return image
14+
15+
16+
def selectImage():
17+
root = tk.Tk()
18+
root.withdraw()
19+
file_path = filedialog.askopenfilename()
20+
file = open(file_path)
21+
filename = file.name
22+
print(file.name)
23+
24+
try:
25+
image = Image.open(filename, 'r')
26+
except Exception as e:
27+
print(e)
28+
29+
return image
30+
31+
def ImageToArray(image):
32+
width, height = image.size
33+
pixel_values = list(image.getdata())
34+
color_array = []
35+
for h in range(height):
36+
color_array.append([])
37+
for w in range(width):
38+
color_array[h].append(pixel_values[h*width+w])
39+
return color_array
40+
41+
42+
def ImageToMatrix(image):
43+
array = numpy.asarray(image)
44+
return array
45+
46+
if __name__ == "__main__":
47+
image = getImage()
48+
#matrix = ImageToMatrix(image)
49+
#print(matrix)
50+
array = ImageToArray(image)
51+
for row in array:
52+
print(row)
53+
exit = input("Type any enter to exit")
Lines changed: 82 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,82 @@
1-
import os
2-
import numpy as np
3-
import Extractor
4-
5-
6-
def test(answer_array,index,filename):
7-
test_image = Extractor.getImage(filename)
8-
test = Extractor.ImageToMatrix(test_image)
9-
os.chdir('..')
10-
os.chdir(os.getcwd()+"/trained_digits/")
11-
12-
scores = []
13-
for x in range(10):
14-
trained_filename = str(x) + ".tif"
15-
16-
trained_image = Extractor.getImage(trained_filename)
17-
trained = Extractor.ImageToMatrix(trained_image)
18-
19-
scores.append(matching_score(test, trained))
20-
21-
guess = scores.index(min(scores))
22-
confidence = (1 - min(scores)/(255*28*28)) * 100
23-
os.chdir('..')
24-
os.chdir(os.getcwd()+"/test_images/")
25-
#print(scores)
26-
#print("==================================================================")
27-
#print("Perdict digit: " + str(guess) + ", with confidence " + str(confidence) + "%")
28-
if answer_array[index] == guess:
29-
return 1
30-
return 0
31-
32-
33-
34-
def matching_score(test, digit):
35-
score = 0
36-
for row in range(len(test)):
37-
for col in range(len(test[row])):
38-
if not test[row][col] == 255 and not digit[row][col] == 255:
39-
invert_test = 255 - test[row][col]
40-
invert_memory = 255 - digit[row][col]
41-
score += abs(invert_memory - invert_test)
42-
return score
43-
44-
45-
46-
if __name__ == "__main__":
47-
48-
49-
STOP_AT = 500
50-
PERCENTILE = STOP_AT/100
51-
52-
answer_array = []
53-
answers = open("mnist-test-labels.txt", "r")
54-
index = 0
55-
for line in answers:
56-
answer_array.append(int(line.strip()))
57-
58-
#print(answer_array)
59-
index = 0
60-
correct = 0
61-
percent = 0
62-
os.chdir(os.getcwd()+"/test_images/")
63-
for filename in os.listdir(os.getcwd()):
64-
correct += test(answer_array, index, filename)
65-
index+=1
66-
if index % PERCENTILE == 0:
67-
print(str(percent) + "%")
68-
percent += 1
69-
if index == STOP_AT:
70-
break
71-
72-
print(str(correct/index*100)+"% correct")
73-
74-
1+
import os
2+
import numpy as np
3+
import Extractor
4+
5+
6+
def test(answer_array,index,filename):
7+
8+
FOLDER_NAME = "-Averaged Approach-"
9+
10+
11+
test_image = Extractor.getImage(filename)
12+
test = Extractor.ImageToMatrix(test_image)
13+
os.chdir('..')
14+
os.chdir(os.getcwd()+"/"+FOLDER_NAME+"/")
15+
os.chdir(os.getcwd()+"/trained_digits/")
16+
17+
scores = []
18+
for x in range(10):
19+
trained_filename = str(x) + ".tif"
20+
21+
trained_image = Extractor.getImage(trained_filename)
22+
trained = Extractor.ImageToMatrix(trained_image)
23+
24+
scores.append(matching_score(test, trained))
25+
26+
guess = scores.index(min(scores))
27+
confidence = (1 - min(scores)/(255*28*28)) * 100
28+
os.chdir('..')
29+
os.chdir('..')
30+
os.chdir(os.getcwd()+"/test_images/")
31+
#print(scores)
32+
#print("==================================================================")
33+
#print("Perdict digit: " + str(guess) + ", with confidence " + str(confidence) + "%")
34+
if answer_array[index] == guess:
35+
return 1
36+
return 0
37+
38+
39+
40+
def matching_score(test, digit):
41+
score = 0
42+
for row in range(len(test)):
43+
for col in range(len(test[row])):
44+
if not test[row][col] == 255 and not digit[row][col] == 255:
45+
invert_test = 255 - test[row][col]
46+
invert_memory = 255 - digit[row][col]
47+
score += abs(invert_memory - invert_test)
48+
return score
49+
50+
51+
52+
if __name__ == "__main__":
53+
54+
55+
STOP_AT = 500
56+
PERCENTILE = STOP_AT/100
57+
58+
answer_array = []
59+
os.chdir('..')
60+
answers = open("mnist-test-labels.txt", "r")
61+
62+
index = 0
63+
for line in answers:
64+
answer_array.append(int(line.strip()))
65+
66+
#print(answer_array)
67+
index = 0
68+
correct = 0
69+
percent = 0
70+
os.chdir(os.getcwd()+"/test_images/")
71+
for filename in os.listdir(os.getcwd()):
72+
correct += test(answer_array, index, filename)
73+
index+=1
74+
if index % PERCENTILE == 0:
75+
print(str(percent) + "%")
76+
percent += 1
77+
if index == STOP_AT:
78+
break
79+
80+
print(str(correct/index*100)+"% correct")
81+
82+
Lines changed: 66 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,66 @@
1-
import Extractor
2-
import os
3-
import numpy as np
4-
from PIL import Image
5-
6-
7-
def loop_images():
8-
root = os.getcwd()
9-
for x in range(10):
10-
os.chdir(root +"/train_images_sorted/" + str(x))
11-
i = 0
12-
total = []
13-
for filename in os.listdir(os.getcwd()):
14-
i += 1
15-
image = Extractor.getImage(filename)
16-
matrix = Extractor.ImageToMatrix(image)
17-
data = black_percentage(matrix)
18-
if len(total) == len(data):
19-
total = add_grayscale(data, total)
20-
else:
21-
total = data
22-
array = average_percentage(total ,i)
23-
print("Digit " + str(x) + " is complete")
24-
img = Image.fromarray(array.astype(np.uint8))
25-
img.save("average.tif")
26-
# img.show()
27-
28-
def black_percentage(grayscale):
29-
"""
30-
NumPy 2D array -> same dimension NumPy 2D array
31-
32-
returns black % for each pixel, 1 is completely black, 0 is white
33-
"""
34-
35-
r = np.zeros((grayscale.shape[0], grayscale.shape[1]), dtype=int)
36-
for row in range(len(grayscale)):
37-
for col in range(len(grayscale[row])):
38-
r[row][col] = grayscale[row][col]
39-
return r
40-
41-
def average_percentage(sum_grayscale, num):
42-
r = np.zeros((sum_grayscale.shape[0], sum_grayscale.shape[1]), dtype=int)
43-
for row in range(len(sum_grayscale)):
44-
for col in range(len(sum_grayscale[row])):
45-
r[row][col] = (sum_grayscale[row][col])//num
46-
return r
47-
48-
def add_grayscale(g1, g2):
49-
r = np.zeros((g1.shape[0], g1.shape[1]), dtype=int)
50-
for row in range(len(g1)):
51-
for col in range(len(g1[row])):
52-
r[row][col] = g1[row][col] + g2[row][col]
53-
return r
54-
55-
56-
if __name__ == "__main__":
57-
loop_images();
1+
import Extractor
2+
import os
3+
import numpy as np
4+
from PIL import Image
5+
6+
7+
def loop_images():
8+
FOLDER_NAME = "/-Averaged Approach-"
9+
10+
os.chdir('..')
11+
root = os.getcwd()
12+
try:
13+
new_dir = root+FOLDER_NAME+"/trained_digits/"
14+
os.makedirs(new_dir)
15+
for x in range(10):
16+
os.chdir(root +"/train_images_sorted/" + str(x))
17+
i = 0
18+
total = []
19+
for filename in os.listdir(os.getcwd()):
20+
i += 1
21+
image = Extractor.getImage(filename)
22+
matrix = Extractor.ImageToMatrix(image)
23+
data = black_percentage(matrix)
24+
if len(total) == len(data):
25+
total = add_grayscale(data, total)
26+
else:
27+
total = data
28+
array = average_percentage(total ,i)
29+
print("Digit " + str(x) + " is complete")
30+
31+
os.chdir(new_dir)
32+
img = Image.fromarray(array.astype(np.uint8))
33+
img.save(str(x)+".tif")
34+
except Exception as e:
35+
print("trained_digits directory already exists")
36+
37+
def black_percentage(grayscale):
38+
"""
39+
NumPy 2D array -> same dimension NumPy 2D array
40+
41+
returns black % for each pixel, 1 is completely black, 0 is white
42+
"""
43+
44+
r = np.zeros((grayscale.shape[0], grayscale.shape[1]), dtype=int)
45+
for row in range(len(grayscale)):
46+
for col in range(len(grayscale[row])):
47+
r[row][col] = grayscale[row][col]
48+
return r
49+
50+
def average_percentage(sum_grayscale, num):
51+
r = np.zeros((sum_grayscale.shape[0], sum_grayscale.shape[1]), dtype=int)
52+
for row in range(len(sum_grayscale)):
53+
for col in range(len(sum_grayscale[row])):
54+
r[row][col] = (sum_grayscale[row][col])//num
55+
return r
56+
57+
def add_grayscale(g1, g2):
58+
r = np.zeros((g1.shape[0], g1.shape[1]), dtype=int)
59+
for row in range(len(g1)):
60+
for col in range(len(g1[row])):
61+
r[row][col] = g1[row][col] + g2[row][col]
62+
return r
63+
64+
65+
if __name__ == "__main__":
66+
loop_images();
Binary file not shown.

0 commit comments

Comments
 (0)