<jupyter_start><jupyter_text>Creating a Rock Paper Scissor Game  1. Load Required Libraries<jupyter_code>import keras
import os

from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Conv2D, MaxPool2D, Dense, Flatten , Dropout
from keras.models import Sequential
from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
from keras.models import load_model

import cv2
import copy
import time<jupyter_output>Using TensorFlow backend.<jupyter_text>2. Prepare data<jupyter_code>train_dir = "rps/rps"
test_dir = "rps-test-set/rps-test-set"

train_rock = os.listdir(train_dir +"/rock")
train_paper = os.listdir(train_dir +"/paper")
train_scissors = os.listdir(train_dir +"/scissors")

test_rock = os.listdir(train_dir +"/rock")
test_scissors = os.listdir(train_dir +"/scissors")
test_paper = os.listdir(train_dir +"/paper")

print("Number of images in the train-set:", len(train_rock) + len(train_paper) + len(train_scissors))
print("Number of images in the test-set:", len(test_rock) + len(test_paper) + len(test_scissors))

print("\nNumber of rocks in the train-set:", len(train_rock))
print("Number of papers in the train-set:", len(train_paper))
print("Number of scissors in the train-set:", len(train_scissors))

print("\nNumber of rocks in the test-set:", len(test_rock))
print("Number of papers in the test-set:", len(test_paper))
print("Number of scissors in the test-set:", len(test_scissors))<jupyter_output>Number of images in the train-set: 2520
Number of images in the test-set: 2520

Number of rocks in the train-set: 840
Number of papers in the train-set: 840
Number of scissors in the train-set: 840

Number of rocks in the test-set: 840
Number of papers in the test-set: 840
Number of scissors in the test-set: 840<jupyter_text>Image Augmentation using Keras<jupyter_code>train_datagen= ImageDataGenerator(rescale= 1/255.0,
                           width_shift_range =0.2 ,
                           height_shift_range=0.2 ,
                           zoom_range=0.2 ,
                           rotation_range=40 ,
                           shear_range=0.2, 
                           horizontal_flip= True)

test_datagen = ImageDataGenerator(rescale= 1/255.0)

train_generator = train_datagen.flow_from_directory(train_dir, target_size=(75,75), class_mode="categorical", batch_size=128)

test_generator = test_datagen.flow_from_directory(test_dir, target_size=(75,75), class_mode="categorical", batch_size=128)<jupyter_output>Found 2520 images belonging to 3 classes.
Found 372 images belonging to 3 classes.<jupyter_text>3. Build Convolution Neural Net Model<jupyter_code>model = Sequential()
model.add(Conv2D(64, (3,3), activation="relu", input_shape=(75,75,3), padding="same"))
model.add(MaxPool2D((2,2)))

model.add(Conv2D(64, (3,3), activation="relu", padding="same"))
model.add(MaxPool2D((2,2)))

model.add(Conv2D(128, (3,3), activation="relu", padding="same"))
model.add(MaxPool2D((2,2)))

model.add(Conv2D(128, (3,3), activation="relu", padding="same"))
model.add(MaxPool2D((2,2)))

model.add(Flatten())

model.add(Dense(512, activation="relu"))
model.add(Dropout(0.2))

model.add(Dense(512, activation= "relu"))
model.add(Dropout(0.2))

model.add(Dense(3, activation="softmax"))


model.summary()
## Create list of keras callbacks

my_callbacks_es = EarlyStopping(monitor='val_accuracy', patience=5, verbose=1)
my_callbacks_rlr = ReduceLROnPlateau(monitor='val_accuracy', pateince=2, factor=0.5, min_lr=0.00001, verbose=1)
my_callbacks_mc = ModelCheckpoint("model.h5",monitor='val_accuracy', save_best_only=True, verbose=1, mode='max')
my_callbacks = [my_callbacks_es, my_callbacks_rlr, my_callbacks_mc]
## compile model

model.compile(loss= "categorical_crossentropy", optimizer='adam', metrics=['accuracy'])
## train model

history= model.fit(train_generator, validation_data=test_generator, 
                  epochs = 25, verbose=1, steps_per_epoch= 20, validation_steps=3,
                  callbacks= my_callbacks)
## load our trained model 

from keras.models import load_model
model = load_model("model.h5")<jupyter_output><empty_output><jupyter_text>4. Using OpenCV to test model with real time video from webcam.<jupyter_code>## start webcam

cap = cv2.VideoCapture(0)

start = True

while True:
    
    ret, frame = cap.read()
    img =  copy.deepcopy(frame)
    
    cv2.rectangle(img, (20,50), (320, 350), (255,0,0), 3)
    
    roi = frame[40:340, 10:310] 
    
    input_img = cv2.resize(roi, (75,75))
    
    
    input_img = np.expand_dims(input_img, axis=0)
    list1 = ['PAPER', "ROCK", "SCISSORS"]
    array= model.predict(input_img)
    id= np.argmax(array)
    text = list1[id]
    cv2.putText(img, "Put your hand in the box", (20,30), cv2.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,255), 2)
    cv2.putText(img, text, (20,380), cv2.FONT_HERSHEY_SIMPLEX, 0.5 , (0,255,255), 2)
    cv2.imshow("frame", img)
    key = cv2.waitKey(1) & 0xFF
    if key== ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13219531560142914, 'fraction_numerical': 0.043668122270742356, 'mean_word_length': 4.758857142857143, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '46877', 'license': 'MIT', 'n_tokens_mistral': 1929, 'n_tokens_neox': 1793, 'n_words': 394, 'path': 'Nakul_ComputerVision_RockPaperScissor.ipynb', 'repo_name': 'prathyu3122/Open-contributions', 'size': '5038'}