Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open innovation PR #56

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions collect-data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import cv2
import os

if not os.path.exists("data"): #True
os.makedirs("data")
os.makedirs("data/train")
os.makedirs("data/test")
os.makedirs("data/train/rock")
os.makedirs("data/train/paper")
os.makedirs("data/train/scissor")
os.makedirs("data/train/none")
os.makedirs("data/test/rock")
os.makedirs("data/test/paper")
os.makedirs("data/test/scissor")
os.makedirs("data/test/none")


mode = 'TRAIN'
directory = 'data/'+mode+'/' #data/train/

cap=cv2.VideoCapture(0)
cap.set(3, 1280) # 3 - PROPERTY index for WIDTH
cap.set(4, 720) # 4 - PROPERTY index for HEIGHT

while True:
_, frame = cap.read()
frame = cv2.flip(frame, 1)

cv2.putText(frame, "GitHub: Daksh777", (900, 450), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (225,255,255), 1)

count = {'rock': len(os.listdir(directory+"/rock")),
'paper': len(os.listdir(directory+"/paper")),
'scissor': len(os.listdir(directory+"/scissor")),
'none': len(os.listdir(directory+"/none"))}

cv2.putText(frame, "MODE : "+ mode, (900, 50), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (225,255,255), 1)
cv2.putText(frame, "IMAGE COUNT:", (900, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (225,255,255), 1)
cv2.putText(frame, "ROCK : "+str(count['rock']), (900, 120), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,255,255), 1)
cv2.putText(frame, "PAPER : "+str(count['paper']), (900, 140), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,255,255), 1)
cv2.putText(frame, "SCISSORS : "+str(count['scissor']), (900, 160), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,255,255), 1)
cv2.putText(frame, "NONE : "+str(count['none']), (900, 180), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,255,255), 1)

cv2.rectangle(frame, (100, 100), (500, 500), (255, 255, 255), 2)
roi = frame[100:500, 100:500]
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
roi = cv2.adaptiveThreshold(roi, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 91, 1)
roi = cv2.resize(roi, (64, 64))
roi = roi.reshape(64, 64, 1)
cv2.putText(frame, "R.O.I", (270, 550), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,225,0), 2)
cv2.imshow("Frame", frame)
cv2.imshow("ROI", roi)

interrupt = cv2.waitKey(10)
if interrupt & 0xFF == 27:
break
if interrupt & 0xFF == ord('0'):
cv2.imwrite(directory+'rock/'+str(count['rock'])+'.jpg', roi)
if interrupt & 0xFF == ord('1'):
cv2.imwrite(directory+'paper/'+str(count['paper'])+'.jpg', roi)
if interrupt & 0xFF == ord('2'):
cv2.imwrite(directory+'scissor/'+str(count['scissor'])+'.jpg', roi)
if interrupt & 0xFF == ord('3'):
cv2.imwrite(directory+'none/'+str(count['none'])+'.jpg', roi)

cap.release()
cv2.destroyAllWindows()
104 changes: 104 additions & 0 deletions game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
from keras.models import load_model
import cv2
import numpy as np
from random import choice

game_moves = {
0: "rock",
1: "paper",
2: "scissors",
3: "none"
}

def mapper(val):
return game_moves[val]

def calculate_winner(move1, move2):
if move1 == move2:
return "Tie"

if move1 == "rock":
if move2 == "scissors":
return "User"
if move2 == "paper":
return "Computer"

if move1 == "paper":
if move2 == "rock":
return "User"
if move2 == "scissors":
return "Computer"

if move1 == "scissors":
if move2 == "paper":
return "User"
if move2 == "rock":
return "Computer"


model = load_model("model.h5")

cap = cv2.VideoCapture(0)
cap.set(3, 1280) # Property for width
cap.set(4, 720) # Property for height

prev_move = None

while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1)

# User rectangle
cv2.rectangle(frame, (100, 100), (500, 500), (255, 255, 255), 2)
# Computer rectangle
cv2.rectangle(frame, (800, 100), (1200, 500), (255, 255, 255), 2)

# Extraction
roi = frame[100:500, 100:500]
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
roi = cv2.adaptiveThreshold(roi, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 91, 1)
roi = cv2.resize(roi, (64, 64))
roi = roi.reshape(64, 64, 1)

# Prediction
pred = model.predict(np.array([roi]))
move_code = np.argmax(pred[0])
user_move_name = mapper(move_code)

# Winner prediction
if prev_move != user_move_name:
if user_move_name != "none":
computer_move_name = choice(['rock', 'paper', 'scissors'])
winner = calculate_winner(user_move_name, computer_move_name)
else:
computer_move_name = "none"
winner = "Waiting..."
prev_move = user_move_name

# Display text
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, "Your Move: " + user_move_name,
(50, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA)
cv2.putText(frame, "Computer's Move: " + computer_move_name,
(750, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA)
cv2.putText(frame, "Winner: " + winner,
(400, 600), font, 2, (0, 0, 255), 4, cv2.LINE_AA)

if computer_move_name != "none":
icon = cv2.imread(
"images/{}.png".format(computer_move_name))
icon = cv2.resize(icon, (400, 400))
frame[100:500, 800:1200] = icon
else:
icon = cv2.imread("images/none.png")
icon = cv2.resize(icon, (400, 400))
frame[100:500, 800:1200] = icon

cv2.imshow("Rock Paper Scissors", frame)

k = cv2.waitKey(10)
if k == ord('q'):
break

cap.release()
cv2.destroyAllWindows()
Binary file added images/none.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/paper.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/rock.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/scissors.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions train-model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense

classifier = Sequential()

classifier.add(Convolution2D(32, (3, 3), input_shape=(64, 64, 1), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))

classifier.add(Convolution2D(32, (3, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))

classifier.add(Flatten())

classifier.add(Dense(units=128, activation='relu'))
classifier.add(Dense(units=4, activation='softmax'))

classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])


from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255) #epoch

training_set = train_datagen.flow_from_directory('data/train',
target_size=(64, 64),
batch_size=3,
color_mode='grayscale',
class_mode='categorical')

test_set = test_datagen.flow_from_directory('data/test',
target_size=(64, 64),
batch_size=3,
color_mode='grayscale',
class_mode='categorical')

classifier.fit_generator(
training_set,
epochs=10,
validation_data=test_set)

classifier.save("model.h5")