-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
116 lines (83 loc) · 2.75 KB
/
app.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# © RPS Machine learning- Made by Yuval Simon. For www.bogan.cool
import os, random, cv2
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
DIR = "dataset"
CATEGORIES = ['Scissors' ,'Rock', 'Paper']
IMG_SIZE = 64
def make(img):
global IMG_SIZE, img1
try:
img_array = cv2.imread(img)
img_og = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)
img1 = cv2.resize(img_og, (IMG_SIZE, IMG_SIZE))
return img1.reshape(-3, 64, 64, 3)
except cv2.error:
print('Image Preparing Error. (Image/s not found)')
os._exit(0)
data = []
def create_dataset():
for cat in CATEGORIES:
path = os.path.join(DIR, cat)
if cat == 'Scissors':
class_num = 0
elif cat == 'Rock':
class_num = 1
elif cat == 'Paper':
class_num = 2
for i in tqdm(os.listdir(path)):
img_array = cv2.imread(os.path.join(path, i))
img_og = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)
img = cv2.resize(img_og, (IMG_SIZE, IMG_SIZE))
data .append([img, class_num])
create_dataset()
random.shuffle(data)
print(f'\nData Len: {len(data)}')
x = []
y = []
for features,label in data:
x.append(features)
y.append(label)
x = np.array(x)
x = x.reshape(-3, 64, 64, 3)
y = np.array(y)
x = x/255.0
print(f"X Shape: {x.shape[1:]}")
print('\n\n')
print("1. Train Model.\n2. Test Model.")
option = input('\n:')
if option == '1':
model = Sequential()
model.add(Conv2D(256, (3, 3), input_shape=x.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Conv2D(256, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Flatten())
model.add(Dense(64))
model.add(Dense(3, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(x, y, batch_size=32, epochs=3, validation_split=0.3)
model.save("rps.h5")
elif option == '2':
from keras.models import load_model
model = load_model("rps.h5")
try:
path = input('Please specify dir path to the image/s: ')
for i in os.listdir(path):
pred = model.predict([make(f'{path}/{i}')])
print(pred)
obj = CATEGORIES[np.argmax(pred)]
plt.imshow(img1, cmap=plt.cm.binary)
plt.title(obj, fontsize= 18)
plt.show()
except FileNotFoundError:
print('no directory or image/s found.')
os._exit(0)