Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import cv2
- import numpy as np
- import matplotlib.pyplot as plt
- import h5py
- def get_file(file_dir):
- a_image = []
- a_label = []
- b_image = []
- b_label = []
- c_image = []
- c_label = []
- d_image = []
- d_label = []
- first0 = True
- first1 = True
- first2 = True
- first3 = True
- for file in os.listdir(file_dir+'/option1'):
- a_image.append(file_dir+'/option1/'+file)
- a_label.append(0)
- del a_image[0]
- del a_label[0]
- for file in os.listdir(file_dir+'/option2'):
- b_image.append(file_dir+'/option2/'+file)
- b_label.append(1)
- del b_image[0]
- del b_label[0]
- for file in os.listdir(file_dir+'/option3'):
- c_image.append(file_dir+'/option3/'+file)
- c_label.append(2)
- del c_image[0]
- del c_label[0]
- for file in os.listdir(file_dir+'/option4'):
- d_image.append(file_dir+'/option4/'+file)
- d_label.append(3)
- del d_image[0]
- del d_label[0]
- image_list = np.hstack((a_image,b_image,c_image,d_image))
- print(image_list)
- label_list = np.hstack((a_label,b_label,c_label,d_label))
- print(label_list)
- temp = np.array([image_list , label_list])
- temp = temp.transpose()
- np.random.shuffle(temp)
- image_list = list(temp[:,0])
- label_list = list(temp[:,1])
- label_list = [float(i) for i in label_list]
- return image_list ,label_list
- image_list , label_list = get_file('gesture_picture')
- image = np.zeros((len(image_list) , 28 ,28))
- label = np.zeros(len(label_list))
- for i in range(len(image)):
- image[i] = np.array(cv2.imread(image_list[i],cv2.IMREAD_GRAYSCALE))
- label[i] = np.array(label_list[i])
- label = label.astype(np.int32)
- import matplotlib.pyplot as plt
- def plot_image(images , labels , idx , num = 10):
- fig = plt.gcf()
- fig.set_size_inches(12 , 14)
- for i in range(num):
- ax = plt.subplot(5,5,i+1)
- ax.imshow(image[i] , cmap = 'binary')
- ax.set_title(label[i])
- ax.set_xticks([])
- ax.set_yticks([])
- plt.show()
- plot_image(image , label , 0 , 25)
- msk = np.random.randn(len(image))<0.8
- img_train = image[msk]
- label_train = label[msk]
- img_test = image[~msk]
- label_test = label[~msk]
- def printshape():
- print(img_train.shape)
- print(label_train.shape)
- print(img_test.shape)
- print(label_test.shape)
- printshape()
- from keras.utils import np_utils
- img_train_nor = np.reshape(img_train/255.0 , (len(img_train),28, 28 ,1))
- img_test_nor = np.reshape(img_test/255.0 , (len(img_test),28 ,28 ,1))
- label_train_hot = np_utils.to_categorical(label_train)
- label_test_hot = np_utils.to_categorical(label_test)
- img_train_nor.shape
- img_test_nor.shape
- from keras.models import Sequential
- from keras.layers import Dense
- from keras.layers import Dense ,Dropout , Activation , Flatten
- from keras.layers import Conv2D , MaxPooling2D , ZeroPadding2D
- model = Sequential()
- model.add(Conv2D(filters = 32 , kernel_size = (3,3) , input_shape = (28,28,1) , activation = 'relu' , padding = 'same'))
- model.add(Dropout(0.25))
- model.add(MaxPooling2D(pool_size = (2 , 2)))
- model.add(Conv2D(64 , (3,3) , activation='relu', padding='same'))
- model.add(Dropout(0.25))
- model.add(MaxPooling2D(pool_size = (2 , 2)))
- model.add(Flatten())
- model.add(Dropout(0.25))
- model.add(Dense(1024 , activation = 'relu'))
- model.add(Dropout(0.25))
- model.add(Dense(4 , activation = 'softmax'))
- model.compile(
- loss = 'categorical_crossentropy',
- optimizer = 'adam',
- metrics = ['accuracy']
- )
- model.fit(img_train_nor , label_train_hot , epochs =3 ,batch_size = 50 ,validation_split = 0.2)
- from keras.models import load_model
- model.save('my_model_cnn.h5') # creates a HDF5 file 'my_model.h5'
- import numpy as np
- import matplotlib.pyplot as plt
- import cv2
- import os
- cap = cv2.VideoCapture(0)
- opened = cap.isOpened
- while(opened):
- n = 0
- (flag , frame) = cap.read(0)
- gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
- img = cv2.resize(gray,(28,28))
- #====
- if(n%150 == 0):
- img = img/255.0
- img = np.array(img)
- img = np.reshape(img , (1, 28 , 28 , 1))
- k = model.predict(img)
- if k.argmax()==0:
- print('空白')
- elif k.argmax()==1:
- print('剪刀')
- elif k.argmax()==2:
- print('石頭')
- elif k.argmax()==3:
- print('布')
- #====
- cv2.imshow('frame',gray)
- if cv2.waitKey(1) & 0xFF == ord('q'):
- break
- #plt.imshow(frame)
- #plt.show()
- n+=1
- cv2.destroyAllWindows()
- from keras.models import load_model
- model = load_model('my_model.h5')
- scores = model.evaluate(img_test_nor , label_test_hot)
Add Comment
Please, Sign In to add comment