Guest User

Untitled

a guest
Jan 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.77 KB | None | 0 0
  1. import os
  2. import cv2
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import h5py
  6.  
  7. def get_file(file_dir):
  8. a_image = []
  9. a_label = []
  10. b_image = []
  11. b_label = []
  12. c_image = []
  13. c_label = []
  14. d_image = []
  15. d_label = []
  16. first0 = True
  17. first1 = True
  18. first2 = True
  19. first3 = True
  20. for file in os.listdir(file_dir+'/option1'):
  21. a_image.append(file_dir+'/option1/'+file)
  22. a_label.append(0)
  23. del a_image[0]
  24. del a_label[0]
  25.  
  26. for file in os.listdir(file_dir+'/option2'):
  27. b_image.append(file_dir+'/option2/'+file)
  28. b_label.append(1)
  29. del b_image[0]
  30. del b_label[0]
  31.  
  32. for file in os.listdir(file_dir+'/option3'):
  33. c_image.append(file_dir+'/option3/'+file)
  34. c_label.append(2)
  35. del c_image[0]
  36. del c_label[0]
  37.  
  38. for file in os.listdir(file_dir+'/option4'):
  39. d_image.append(file_dir+'/option4/'+file)
  40. d_label.append(3)
  41. del d_image[0]
  42. del d_label[0]
  43.  
  44. image_list = np.hstack((a_image,b_image,c_image,d_image))
  45. print(image_list)
  46. label_list = np.hstack((a_label,b_label,c_label,d_label))
  47. print(label_list)
  48.  
  49. temp = np.array([image_list , label_list])
  50. temp = temp.transpose()
  51. np.random.shuffle(temp)
  52.  
  53. image_list = list(temp[:,0])
  54. label_list = list(temp[:,1])
  55. label_list = [float(i) for i in label_list]
  56. return image_list ,label_list
  57.  
  58. image_list , label_list = get_file('gesture_picture')
  59.  
  60. image = np.zeros((len(image_list) , 28 ,28))
  61. label = np.zeros(len(label_list))
  62. for i in range(len(image)):
  63. image[i] = np.array(cv2.imread(image_list[i],cv2.IMREAD_GRAYSCALE))
  64. label[i] = np.array(label_list[i])
  65. label = label.astype(np.int32)
  66. import matplotlib.pyplot as plt
  67. def plot_image(images , labels , idx , num = 10):
  68. fig = plt.gcf()
  69. fig.set_size_inches(12 , 14)
  70. for i in range(num):
  71. ax = plt.subplot(5,5,i+1)
  72. ax.imshow(image[i] , cmap = 'binary')
  73. ax.set_title(label[i])
  74. ax.set_xticks([])
  75. ax.set_yticks([])
  76. plt.show()
  77. plot_image(image , label , 0 , 25)
  78.  
  79. msk = np.random.randn(len(image))<0.8
  80. img_train = image[msk]
  81. label_train = label[msk]
  82. img_test = image[~msk]
  83. label_test = label[~msk]
  84.  
  85. def printshape():
  86. print(img_train.shape)
  87. print(label_train.shape)
  88. print(img_test.shape)
  89. print(label_test.shape)
  90.  
  91. printshape()
  92. from keras.utils import np_utils
  93.  
  94. img_train_nor = np.reshape(img_train/255.0 , (len(img_train),28, 28 ,1))
  95. img_test_nor = np.reshape(img_test/255.0 , (len(img_test),28 ,28 ,1))
  96.  
  97. label_train_hot = np_utils.to_categorical(label_train)
  98. label_test_hot = np_utils.to_categorical(label_test)
  99.  
  100. img_train_nor.shape
  101. img_test_nor.shape
  102.  
  103. from keras.models import Sequential
  104. from keras.layers import Dense
  105. from keras.layers import Dense ,Dropout , Activation , Flatten
  106. from keras.layers import Conv2D , MaxPooling2D , ZeroPadding2D
  107.  
  108. model = Sequential()
  109. model.add(Conv2D(filters = 32 , kernel_size = (3,3) , input_shape = (28,28,1) , activation = 'relu' , padding = 'same'))
  110. model.add(Dropout(0.25))
  111. model.add(MaxPooling2D(pool_size = (2 , 2)))
  112. model.add(Conv2D(64 , (3,3) , activation='relu', padding='same'))
  113. model.add(Dropout(0.25))
  114. model.add(MaxPooling2D(pool_size = (2 , 2)))
  115. model.add(Flatten())
  116. model.add(Dropout(0.25))
  117. model.add(Dense(1024 , activation = 'relu'))
  118. model.add(Dropout(0.25))
  119. model.add(Dense(4 , activation = 'softmax'))
  120.  
  121. model.compile(
  122. loss = 'categorical_crossentropy',
  123. optimizer = 'adam',
  124. metrics = ['accuracy']
  125. )
  126. model.fit(img_train_nor , label_train_hot , epochs =3 ,batch_size = 50 ,validation_split = 0.2)
  127.  
  128.  
  129. from keras.models import load_model
  130. model.save('my_model_cnn.h5') # creates a HDF5 file 'my_model.h5'
  131.  
  132. import numpy as np
  133. import matplotlib.pyplot as plt
  134. import cv2
  135. import os
  136. cap = cv2.VideoCapture(0)
  137. opened = cap.isOpened
  138. while(opened):
  139. n = 0
  140. (flag , frame) = cap.read(0)
  141. gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
  142. img = cv2.resize(gray,(28,28))
  143.  
  144. #====
  145. if(n%150 == 0):
  146. img = img/255.0
  147. img = np.array(img)
  148. img = np.reshape(img , (1, 28 , 28 , 1))
  149. k = model.predict(img)
  150. if k.argmax()==0:
  151. print('空白')
  152. elif k.argmax()==1:
  153. print('剪刀')
  154. elif k.argmax()==2:
  155. print('石頭')
  156. elif k.argmax()==3:
  157. print('布')
  158. #====
  159.  
  160. cv2.imshow('frame',gray)
  161. if cv2.waitKey(1) & 0xFF == ord('q'):
  162. break
  163. #plt.imshow(frame)
  164. #plt.show()
  165. n+=1
  166. cv2.destroyAllWindows()
  167.  
  168. from keras.models import load_model
  169. model = load_model('my_model.h5')
  170. scores = model.evaluate(img_test_nor , label_test_hot)
Add Comment
Please, Sign In to add comment