cut_save_face.py

  1. #!/usr/bin/python
  2. # coding:utf8
  3. import cv2
  4. import os
  5. import numpy as np
  6. import csv
  7. def detect(img, cascade):
  8. """
  9. 使用Haar特征检测分类器完成人脸检测
  10. :param img:
  11. :param cascade:
  12. :return:
  13. """
  14. # detectMultiScale检测出图片中所有的人脸,并将人脸用vector保存各个人脸的坐标、大小(用矩形表示),返回坐标。
  15. rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
  16. flags=cv2.CASCADE_SCALE_IMAGE)
  17. if len(rects) == 0:
  18. return []
  19. rects[:, 2:] += rects[:, :2]
  20. return rects
  21. cascade = cv2.CascadeClassifier(
  22. "E:/Anaconda3/envs/sklearn/Library/etc/haarcascades/haarcascade_frontalface_alt.xml")
  23. f = "jaffe/"
  24. fs = os.listdir(f)
  25. data = np.zeros([213, 48 * 48], dtype=np.uint8)
  26. label = np.zeros([213], dtype=int)
  27. i = 0
  28. for f1 in fs:
  29. tmp_path = os.path.join(f, f1)
  30. if not os.path.isdir(tmp_path):
  31. # print(tmp_path[len(f):])
  32. img = cv2.imread(tmp_path, 1)
  33. # BGR转换为灰度图
  34. dst = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  35. rects = detect(dst, cascade)
  36. for x1, y1, x2, y2 in rects:
  37. cv2.rectangle(img, (x1 + 10, y1 + 20), (x2 - 10, y2), (0, 255, 255), 2)
  38. # 调整截取脸部区域大小
  39. img_roi = np.uint8([y2 - (y1 + 20), (x2 - 10) - (x1 + 10)])
  40. roi = dst[y1 + 20:y2, x1 + 10:x2 - 10]
  41. img_roi = roi
  42. re_roi = cv2.resize(img_roi, (48, 48))
  43. # 获得表情label
  44. img_label = tmp_path[len(f) + 3:len(f) + 5]
  45. # print(img_label)
  46. if img_label == 'AN':
  47. label[i] = 0
  48. elif img_label == 'DI':
  49. label[i] = 1
  50. elif img_label == 'FE':
  51. label[i] = 2
  52. elif img_label == 'HA':
  53. label[i] = 3
  54. elif img_label == 'SA':
  55. label[i] = 4
  56. elif img_label == 'SU':
  57. label[i] = 5
  58. elif img_label == 'NE':
  59. label[i] = 6
  60. else:
  61. print("get label error.......\n")
  62. # flatten返回一个折叠成一维的数组。但是该函数只能适用于numpy对象,即array或者mat,普通的list列表是不行的。
  63. data[i][0:48 * 48] = np.ndarray.flatten(re_roi)
  64. i = i + 1
  65. # cv2.imshow("src", dst)
  66. # cv2.imshow("img", img)
  67. # if cv2.waitKey() == 32:
  68. # continue
  69. with open(r"face.csv", "w") as csvfile:
  70. writer = csv.writer(csvfile)
  71. writer.writerow(['emotion', 'pixels'])
  72. for i in range(len(label)):
  73. data_list = list(data[i])
  74. b = " ".join(str(x) for x in data_list)
  75. # 在水平方向上平铺
  76. l = np.hstack([label[i], b])
  77. writer.writerow(l)
  1. detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
  2. flags=cv2.CASCADE_SCALE_IMAGE)
  • 参数image--待检测图片,一般为灰度图像加快检测速度;
  • 参数scaleFactor--表示在前后两次相继的扫描中,搜索窗口的比例系数。默认为1.1即每次搜索窗口依次扩大10%;
  • 参数minNeighbors--表示构成检测目标的相邻矩形的最小个数(默认为3个)。如果组成检测目标的小矩形的个数和小于 min_neighbors - 1 都会被排除。如果min_neighbors 为 0, 则函数不做任何操作就返回所有的被检候选矩形框,这种设定值一般用在用户自定义对检测结果的组合程序上;
  • 参数flags--flags=0:可以取如下这些值:CASCADE_DO_CANNY_PRUNING=1,利用canny边缘检测来排除一些边缘很少或者很多的图像区域,CASCADE_SCALE_IMAGE=2,正常比例检测,CASCADE_FIND_BIGGEST_OBJECT=4,只检测最大的物体,CASCADE_DO_ROUGH_SEARCH=8 初略的检测

show_facial_expression.py

  1. #!/usr/bin/python
  2. # coding:utf8
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import pandas as pd
  6. emotion = {0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy', 4: 'Sad', 5: 'Surprise', 6: 'Neutral'}
  7. data = pd.read_csv(r'face.csv', dtype='a')
  8. label = np.array(data['emotion'])
  9. img_data = np.array(data['pixels'])
  10. N_sample = label.size
  11. Face_data = np.zeros((N_sample, 48 * 48))
  12. Face_label = np.zeros((N_sample, 7), dtype=int)
  13. # 显示人脸以及对应表情
  14. for i in range(25):
  15. x = img_data[i]
  16. # 使用字符串创建矩阵。
  17. x = np.fromstring(x, dtype=float, sep=' ')
  18. x = x / x.max()
  19. img_x = np.reshape(x, (48, 48))
  20. plt.subplot(5, 5, i + 1)
  21. plt.axis('off')
  22. plt.title(emotion[int(label[i])])
  23. plt.imshow(img_x, plt.cm.gray)
  24. plt.show()

count_facial_expression.py

  1. #!/usr/bin/python
  2. # coding:utf8
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import pandas as pd
  6. emotion = {0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy', 4: 'Sad', 5: 'Surprise', 6: 'Neutral'}
  7. data = pd.read_csv(r'face.csv', dtype='a')
  8. label = np.array(data['emotion'])
  9. img_data = np.array(data['pixels'])
  10. N_sample = label.size
  11. emotions = np.zeros(7)
  12. for i in label:
  13. for j in range(7):
  14. if int(i) == j:
  15. emotions[j] = emotions[j] + 1
  16. print(emotions)
  17. plt.bar(range(7), emotions, 0.5, color=['red', 'green', 'blue'])
  18. plt.xlabel('emotions')
  19. plt.xticks(range(7), ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral'], rotation=0)
  20. plt.ylabel('number')
  21. plt.grid()
  22. plt.show()

train_keras.py

  1. #!/usr/bin/python
  2. # coding:utf8
  3. import numpy as np
  4. import pandas as pd
  5. from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten
  6. from keras.models import Sequential
  7. from keras.preprocessing.image import ImageDataGenerator
  8. # 表情类别
  9. emotion = {0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy', 4: 'Sad', 5: 'Surprise', 6: 'Neutral'}
  10. # 读取数据
  11. data = pd.read_csv(r'face.csv', dtype='a')
  12. # 读取标签列表
  13. label = np.array(data['emotion'])
  14. # 图像列表
  15. img_data = np.array(data['pixels'])
  16. # 图像数量
  17. N_sample = label.size
  18. # (213, 2304)
  19. Face_data = np.zeros((N_sample, 48 * 48))
  20. # (213, 7)
  21. Face_label = np.zeros((N_sample, 7), dtype=np.float)
  22. for i in range(N_sample):
  23. x = img_data[i]
  24. x = np.fromstring(x, dtype=float, sep=' ')
  25. x = x / x.max()
  26. Face_data[i] = x
  27. Face_label[i, int(label[i])] = 1.0
  28. # 训练数据数量
  29. train_num = 200
  30. # 测试数据数量
  31. test_num = 13
  32. # 训练数据
  33. train_x = Face_data[0:train_num, :]
  34. train_y = Face_label[0:train_num, :]
  35. train_x = train_x.reshape(-1, 48, 48, 1) # reshape
  36. # 测试数据
  37. test_x = Face_data[train_num: train_num + test_num, :]
  38. test_y = Face_label[train_num: train_num + test_num, :]
  39. test_x = test_x.reshape(-1, 48, 48, 1) # reshape
  40. # 序贯模型
  41. model = Sequential()
  42. model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(48, 48, 1)))
  43. model.add(MaxPooling2D(pool_size=(2, 2)))
  44. model.add(Conv2D(64, (5, 5), activation='relu'))
  45. model.add(MaxPooling2D(pool_size=(2, 2)))
  46. model.add(Flatten())
  47. model.add(Dense(1024, activation='relu'))
  48. model.add(Dropout(0.5))
  49. model.add(Dense(7, activation='softmax'))
  50. model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
  51. # 扩增数据
  52. datagen = ImageDataGenerator(
  53. featurewise_center=True,
  54. featurewise_std_normalization=True,
  55. rotation_range=20,
  56. width_shift_range=0.2,
  57. height_shift_range=0.2,
  58. horizontal_flip=True)
  59. datagen.fit(train_x)
  60. model.fit_generator(datagen.flow(train_x, train_y, batch_size=10), steps_per_epoch=len(train_x), epochs=20)
  61. model.fit(train_x, train_y, batch_size=10, epochs=100)
  62. score = model.evaluate(test_x, test_y, batch_size=10)
  63. print("score:", score)
  64. model.summary()

输出结果

  1. Epoch 50/50
  2. 10/200 [>.............................] - ETA: 1s - loss: 0.0015 - acc: 1.0000
  3. 20/200 [==>...........................] - ETA: 1s - loss: 7.8377e-04 - acc: 1.0000
  4. 30/200 [===>..........................] - ETA: 1s - loss: 0.0013 - acc: 1.0000
  5. 40/200 [=====>........................] - ETA: 1s - loss: 0.0012 - acc: 1.0000
  6. 50/200 [======>.......................] - ETA: 1s - loss: 0.0013 - acc: 1.0000
  7. 60/200 [========>.....................] - ETA: 1s - loss: 0.0011 - acc: 1.0000
  8. 70/200 [=========>....................] - ETA: 1s - loss: 0.0013 - acc: 1.0000
  9. 80/200 [===========>..................] - ETA: 1s - loss: 0.0012 - acc: 1.0000
  10. 90/200 [============>.................] - ETA: 0s - loss: 0.0011 - acc: 1.0000
  11. 100/200 [==============>...............] - ETA: 0s - loss: 0.0011 - acc: 1.0000
  12. 110/200 [===============>..............] - ETA: 0s - loss: 9.7286e-04 - acc: 1.0000
  13. 120/200 [=================>............] - ETA: 0s - loss: 8.9958e-04 - acc: 1.0000
  14. 130/200 [==================>...........] - ETA: 0s - loss: 8.3767e-04 - acc: 1.0000
  15. 140/200 [====================>.........] - ETA: 0s - loss: 9.1249e-04 - acc: 1.0000
  16. 150/200 [=====================>........] - ETA: 0s - loss: 9.3190e-04 - acc: 1.0000
  17. 160/200 [=======================>......] - ETA: 0s - loss: 9.0101e-04 - acc: 1.0000
  18. 170/200 [========================>.....] - ETA: 0s - loss: 8.6291e-04 - acc: 1.0000
  19. 180/200 [==========================>...] - ETA: 0s - loss: 8.2539e-04 - acc: 1.0000
  20. 190/200 [===========================>..] - ETA: 0s - loss: 7.8394e-04 - acc: 1.0000
  21. 200/200 [==============================] - 2s 9ms/step - loss: 7.8767e-04 - acc: 1.0000
  22. 10/13 [======================>.......] - ETA: 0s
  23. 13/13 [==============================] - 0s 5ms/step
  24. _________________________________________________________________
  25. Layer (type) Output Shape Param #
  26. =================================================================
  27. conv2d_1 (Conv2D) (None, 44, 44, 32) 832
  28. _________________________________________________________________
  29. max_pooling2d_1 (MaxPooling2 (None, 22, 22, 32) 0
  30. _________________________________________________________________
  31. conv2d_2 (Conv2D) (None, 18, 18, 64) 51264
  32. _________________________________________________________________
  33. max_pooling2d_2 (MaxPooling2 (None, 9, 9, 64) 0
  34. _________________________________________________________________
  35. flatten_1 (Flatten) (None, 5184) 0
  36. _________________________________________________________________
  37. dense_1 (Dense) (None, 1024) 5309440
  38. _________________________________________________________________
  39. dropout_1 (Dropout) (None, 1024) 0
  40. _________________________________________________________________
  41. dense_2 (Dense) (None, 7) 7175
  42. =================================================================
  43. Total params: 5,368,711
  44. Trainable params: 5,368,711
  45. Non-trainable params: 0
  46. _________________________________________________________________

train_tensorflow.py

  1. #!/usr/bin/python
  2. # coding:utf8
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import pandas as pd
  6. import tensorflow as tf
  7. def conv_pool_layer(data, weights_size, biases_size):
  8. """
  9. 卷积神经网络的层
  10. :param data:
  11. :param weights_size:
  12. :param biases_size:
  13. :return:
  14. """
  15. weights = tf.Variable(tf.truncated_normal(weights_size, stddev=0.1))
  16. biases = tf.Variable(tf.constant(0.1, shape=biases_size))
  17. conv2d = tf.nn.conv2d(data, weights, strides=[1, 1, 1, 1], padding='SAME')
  18. relu = tf.nn.relu(conv2d + biases)
  19. return tf.nn.max_pool(relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  20. def linear_layer(data, weights_size, biases_size):
  21. weights = tf.Variable(tf.truncated_normal(weights_size, stddev=0.1))
  22. biases = tf.Variable(tf.constant(0.1, shape=biases_size))
  23. return tf.add(tf.matmul(data, weights), biases)
  24. def convolutional_neural_network(x, keep_prob):
  25. """
  26. 卷积神经网络
  27. :param x:
  28. :param keep_prob:
  29. :return:
  30. """
  31. x_image = tf.reshape(x, [-1, 48, 48, 1])
  32. h_pool1 = conv_pool_layer(x_image, [5, 5, 1, 32], [32])
  33. h_pool2 = conv_pool_layer(h_pool1, [5, 5, 32, 64], [64])
  34. h_pool2_flat = tf.reshape(h_pool2, [-1, 12 * 12 * 64])
  35. h_fc1 = tf.nn.relu(linear_layer(h_pool2_flat, [12 * 12 * 64, 1024], [1024]))
  36. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  37. return tf.nn.softmax(linear_layer(h_fc1_drop, [1024, class_sum], [class_sum]))
  38. def batch_data(x, y, batch, num):
  39. ind = np.arange(num)
  40. index = ind[batch * batch_size:(batch + 1) * batch_size]
  41. batch_x = x[index, :]
  42. batch_y = y[index, :]
  43. return batch_x, batch_y
  44. if __name__ == "__main__":
  45. # 表情类别
  46. emotion = {0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy', 4: 'Sad', 5: 'Surprise', 6: 'Neutral'}
  47. # 数据
  48. data = pd.read_csv(r'face.csv', dtype='a')
  49. # 表情标签
  50. label = np.array(data['emotion'])
  51. # 图片数据
  52. img_data = np.array(data['pixels'])
  53. # 图片数量
  54. N_sample = label.size
  55. # 图片矩阵
  56. Face_data = np.zeros((N_sample, 48 * 48))
  57. # 标签矩阵
  58. Face_label = np.zeros((N_sample, 7), dtype=int)
  59. # 遍历将图片和标签构建为矩阵形式
  60. for i in range(N_sample):
  61. x = img_data[i]
  62. x = np.fromstring(x, dtype=float, sep=' ')
  63. x = x / x.max()
  64. Face_data[i] = x
  65. Face_label[i, int(label[i])] = 1
  66. # 参数
  67. dropout = 0.5
  68. class_sum = 7
  69. # dropout减轻过拟合问题
  70. keep_prob = tf.placeholder(tf.float32)
  71. x = tf.placeholder(tf.float32, [None, 48 * 48])
  72. y = tf.placeholder(tf.float32, [None, class_sum])
  73. # 构建卷积神经网络
  74. pred = convolutional_neural_network(x, keep_prob)
  75. # 取前200个作为训练数据,后13个为测试数据
  76. train_num = 200
  77. test_num = 13
  78. train_x = Face_data[0:train_num, :]
  79. train_y = Face_label[0:train_num, :]
  80. test_x = Face_data[train_num: train_num + test_num, :]
  81. test_y = Face_label[train_num: train_num + test_num, :]
  82. batch_size = 20
  83. train_batch_num = int(train_num / batch_size)
  84. test_batch_num = test_num / batch_size
  85. # 训练和评估模型
  86. cross_entropy = -tf.reduce_sum(y * tf.log(pred))
  87. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  88. correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  89. accuracy = tf.reduce_mean(tf.cast(correct_pred, "float"))
  90. total_train_loss = []
  91. total_train_acc = []
  92. total_test_loss = []
  93. total_test_acc = []
  94. train_epoch = 50
  95. with tf.Session() as sess:
  96. sess.run(tf.initialize_all_variables())
  97. for epoch in range(0, train_epoch):
  98. Total_train_loss = 0
  99. Total_train_acc = 0
  100. for train_batch in range(0, train_batch_num):
  101. batch_x, batch_y = batch_data(train_x, train_y, train_batch, train_num)
  102. # 优化操作
  103. sess.run(train_step, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
  104. if train_batch % batch_size == 0:
  105. # 计算损失和准确率
  106. loss, acc = sess.run([cross_entropy, accuracy], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
  107. print("Epoch: " + str(epoch + 1) + ", Batch: " + str(train_batch) + ", Loss= " + "{:.3f}".format(
  108. loss) + ", Training Accuracy= " + "{:.3f}".format(acc))
  109. Total_train_loss = Total_train_loss + loss
  110. Total_train_acc = Total_train_acc + acc
  111. total_train_loss.append(Total_train_loss)
  112. total_train_acc.append(Total_train_acc)
  113. plt.subplot(2, 1, 1)
  114. plt.ylabel('Train loss')
  115. plt.plot(total_train_loss, 'r')
  116. plt.subplot(2, 1, 2)
  117. plt.ylabel('Train accuracy')
  118. plt.plot(total_train_acc, 'r')
  119. plt.savefig("loss_acc.png")
  120. plt.show()

输出结果

  1. Epoch: 1, Batch: 0, Loss= 119.417, Training Accuracy= 0.150
  2. Epoch: 2, Batch: 0, Loss= 49.221, Training Accuracy= 0.250
  3. Epoch: 3, Batch: 0, Loss= 39.813, Training Accuracy= 0.200
  4. Epoch: 4, Batch: 0, Loss= 43.067, Training Accuracy= 0.300
  5. Epoch: 5, Batch: 0, Loss= 28.889, Training Accuracy= 0.500
  6. Epoch: 6, Batch: 0, Loss= 18.173, Training Accuracy= 0.700
  7. Epoch: 7, Batch: 0, Loss= 18.474, Training Accuracy= 0.600
  8. Epoch: 8, Batch: 0, Loss= 15.813, Training Accuracy= 0.800
  9. Epoch: 9, Batch: 0, Loss= 12.878, Training Accuracy= 0.850
  10. Epoch: 10, Batch: 0, Loss= 13.250, Training Accuracy= 0.800
  11. Epoch: 11, Batch: 0, Loss= 8.750, Training Accuracy= 0.950
  12. Epoch: 12, Batch: 0, Loss= 10.424, Training Accuracy= 0.850
  13. Epoch: 13, Batch: 0, Loss= 7.592, Training Accuracy= 1.000
  14. Epoch: 14, Batch: 0, Loss= 7.146, Training Accuracy= 0.950
  15. Epoch: 15, Batch: 0, Loss= 7.377, Training Accuracy= 1.000
  16. Epoch: 16, Batch: 0, Loss= 5.423, Training Accuracy= 1.000
  17. Epoch: 17, Batch: 0, Loss= 6.173, Training Accuracy= 1.000
  18. Epoch: 18, Batch: 0, Loss= 4.069, Training Accuracy= 1.000
  19. Epoch: 19, Batch: 0, Loss= 4.163, Training Accuracy= 1.000
  20. Epoch: 20, Batch: 0, Loss= 3.650, Training Accuracy= 1.000
  21. Epoch: 21, Batch: 0, Loss= 3.317, Training Accuracy= 1.000
  22. Epoch: 22, Batch: 0, Loss= 4.195, Training Accuracy= 1.000
  23. Epoch: 23, Batch: 0, Loss= 2.729, Training Accuracy= 1.000
  24. Epoch: 24, Batch: 0, Loss= 2.448, Training Accuracy= 1.000
  25. Epoch: 25, Batch: 0, Loss= 2.614, Training Accuracy= 1.000
  26. Epoch: 26, Batch: 0, Loss= 2.424, Training Accuracy= 1.000
  27. Epoch: 27, Batch: 0, Loss= 2.707, Training Accuracy= 1.000
  28. Epoch: 28, Batch: 0, Loss= 2.072, Training Accuracy= 1.000
  29. Epoch: 29, Batch: 0, Loss= 1.726, Training Accuracy= 1.000
  30. Epoch: 30, Batch: 0, Loss= 1.701, Training Accuracy= 1.000
  31. Epoch: 31, Batch: 0, Loss= 1.598, Training Accuracy= 1.000
  32. Epoch: 32, Batch: 0, Loss= 1.381, Training Accuracy= 1.000
  33. Epoch: 33, Batch: 0, Loss= 1.826, Training Accuracy= 1.000
  34. Epoch: 34, Batch: 0, Loss= 1.227, Training Accuracy= 1.000
  35. Epoch: 35, Batch: 0, Loss= 1.320, Training Accuracy= 1.000
  36. Epoch: 36, Batch: 0, Loss= 1.110, Training Accuracy= 1.000
  37. Epoch: 37, Batch: 0, Loss= 0.875, Training Accuracy= 1.000
  38. Epoch: 38, Batch: 0, Loss= 1.214, Training Accuracy= 1.000
  39. Epoch: 39, Batch: 0, Loss= 0.982, Training Accuracy= 1.000
  40. Epoch: 40, Batch: 0, Loss= 0.982, Training Accuracy= 1.000
  41. Epoch: 41, Batch: 0, Loss= 0.681, Training Accuracy= 1.000
  42. Epoch: 42, Batch: 0, Loss= 0.839, Training Accuracy= 1.000
  43. Epoch: 43, Batch: 0, Loss= 0.777, Training Accuracy= 1.000
  44. Epoch: 44, Batch: 0, Loss= 0.671, Training Accuracy= 1.000
  45. Epoch: 45, Batch: 0, Loss= 0.859, Training Accuracy= 1.000
  46. Epoch: 46, Batch: 0, Loss= 0.529, Training Accuracy= 1.000
  47. Epoch: 47, Batch: 0, Loss= 0.707, Training Accuracy= 1.000
  48. Epoch: 48, Batch: 0, Loss= 0.491, Training Accuracy= 1.000
  49. Epoch: 49, Batch: 0, Loss= 0.500, Training Accuracy= 1.000
  50. Epoch: 50, Batch: 0, Loss= 0.415, Training Accuracy= 1.000

train_tensorboard.py

  1. #!/usr/bin/python
  2. # coding:utf8
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import pandas as pd
  6. import tensorflow as tf
  7. def conv_pool_layer(data, weights_size, biases_size):
  8. weights = tf.Variable(tf.truncated_normal(weights_size, stddev=0.1))
  9. biases = tf.Variable(tf.constant(0.1, shape=biases_size))
  10. conv2d = tf.nn.conv2d(data, weights, strides=[1, 1, 1, 1], padding='SAME')
  11. relu = tf.nn.relu(conv2d + biases)
  12. return tf.nn.max_pool(relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  13. def linear_layer(data, weights_size, biases_size):
  14. weights = tf.Variable(tf.truncated_normal(weights_size, stddev=0.1))
  15. biases = tf.Variable(tf.constant(0.1, shape=biases_size))
  16. return tf.add(tf.matmul(data, weights), biases)
  17. def convolutional_neural_network(x, keep_prob):
  18. with tf.name_scope('input'):
  19. x_image = tf.reshape(x, [-1, 48, 48, 1])
  20. with tf.name_scope('conv1'):
  21. h_pool1 = conv_pool_layer(x_image, [5, 5, 1, 32], [32])
  22. with tf.name_scope('conv2'):
  23. h_pool2 = conv_pool_layer(h_pool1, [5, 5, 32, 64], [64])
  24. h_pool2_flat = tf.reshape(h_pool2, [-1, 12 * 12 * 64])
  25. with tf.name_scope('fc3'):
  26. h_fc1 = tf.nn.relu(linear_layer(h_pool2_flat, [12 * 12 * 64, 1024], [1024]))
  27. with tf.name_scope('dropout4'):
  28. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  29. with tf.name_scope('softmax5'):
  30. out = tf.nn.softmax(linear_layer(h_fc1_drop, [1024, class_sum], [class_sum]))
  31. return out
  32. def batch_data(x, y, batch, num):
  33. ind = np.arange(num)
  34. index = ind[batch * batch_size:(batch + 1) * batch_size]
  35. batch_x = x[index, :]
  36. batch_y = y[index, :]
  37. return batch_x, batch_y
  38. if __name__ == "__main__":
  39. emotion = {0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy', 4: 'Sad', 5: 'Surprise', 6: 'Neutral'}
  40. data = pd.read_csv(r'face.csv', dtype='a')
  41. label = np.array(data['emotion'])
  42. img_data = np.array(data['pixels'])
  43. N_sample = label.size
  44. Face_data = np.zeros((N_sample, 48 * 48))
  45. Face_label = np.zeros((N_sample, 7), dtype=int)
  46. for i in range(N_sample):
  47. x = img_data[i]
  48. x = np.fromstring(x, dtype=float, sep=' ')
  49. x = x / x.max()
  50. Face_data[i] = x
  51. Face_label[i, int(label[i])] = 1
  52. # 参数
  53. dropout = 0.5
  54. class_sum = 7
  55. # dropout减轻过拟合问题
  56. keep_prob = tf.placeholder(tf.float32)
  57. x = tf.placeholder(tf.float32, [None, 48 * 48])
  58. y = tf.placeholder(tf.float32, [None, class_sum])
  59. pred = convolutional_neural_network(x, keep_prob)
  60. # 取前200个作为训练数据,后13个为测试数据
  61. train_num = 200
  62. test_num = 13
  63. train_x = Face_data[0:train_num, :]
  64. train_y = Face_label[0:train_num, :]
  65. test_x = Face_data[train_num: train_num + test_num, :]
  66. test_y = Face_label[train_num: train_num + test_num, :]
  67. batch_size = 20
  68. train_batch_num = int(train_num / batch_size)
  69. test_batch_num = test_num / batch_size
  70. # 训练和评估模型
  71. with tf.name_scope('cross_entropy'):
  72. cross_entropy = -tf.reduce_sum(y * tf.log(pred))
  73. tf.summary.histogram("cross_entropy", cross_entropy)
  74. # tf.summary.scalar("cross_entropy", cross_entropy)
  75. with tf.name_scope('minimize'):
  76. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  77. with tf.name_scope('accuracy'):
  78. with tf.name_scope('correct_pred'):
  79. correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  80. with tf.name_scope('accuracy'):
  81. accuracy = tf.reduce_mean(tf.cast(correct_pred, "float"))
  82. tf.summary.histogram("accuracy", accuracy)
  83. # 输出包含单个标量值的摘要协议缓冲区
  84. tf.summary.scalar('accuracy', accuracy)
  85. total_train_loss = []
  86. total_train_acc = []
  87. total_test_loss = []
  88. total_test_acc = []
  89. train_epoch = 50
  90. # 合并在默认图形中收集的所有摘要
  91. merged = tf.summary.merge_all()
  92. with tf.Session() as sess:
  93. writer = tf.summary.FileWriter("tmp/logs", sess.graph)
  94. sess.run(tf.global_variables_initializer())
  95. for epoch in range(0, train_epoch):
  96. Total_train_loss = 0
  97. Total_train_acc = 0
  98. for train_batch in range(0, train_batch_num):
  99. batch_x, batch_y = batch_data(train_x, train_y, train_batch, train_num)
  100. # 优化操作
  101. # sess.run(train_step, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
  102. summary, _ = sess.run([merged, train_step], feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
  103. writer.add_summary(summary, train_batch)
  104. if train_batch % batch_size == 0:
  105. # 计算损失和准确率
  106. loss, acc = sess.run([cross_entropy, accuracy], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
  107. print("Epoch: " + str(epoch + 1) + ", Batch: " + str(train_batch) +
  108. ", Loss= " + "{:.3f}".format(loss) +
  109. ", Training Accuracy= " + "{:.3f}".format(acc))
  110. Total_train_loss = Total_train_loss + loss
  111. Total_train_acc = Total_train_acc + acc
  112. total_train_loss.append(Total_train_loss)
  113. total_train_acc.append(Total_train_acc)
  114. writer.close()
  115. plt.subplot(2, 1, 1)
  116. plt.ylabel('Train loss')
  117. plt.plot(total_train_loss, 'r')
  118. plt.subplot(2, 1, 2)
  119. plt.ylabel('Train accuracy')
  120. plt.plot(total_train_acc, 'r')
  121. plt.savefig("face_loss_acc.png")
  122. plt.show()

TensorFlow和Keras完成JAFFE人脸表情识别的更多相关文章

  1. CVPR 2020几篇论文内容点评:目标检测跟踪,人脸表情识别,姿态估计,实例分割等

    CVPR 2020几篇论文内容点评:目标检测跟踪,人脸表情识别,姿态估计,实例分割等 CVPR 2020中选论文放榜后,最新开源项目合集也来了. 本届CPVR共接收6656篇论文,中选1470篇,&q ...

  2. 【Gabor】基于多尺度多方向Gabor融合+分块直方图的表情识别

    Topic:表情识别Env: win10 + Pycharm2018 + Python3.6.8Date:   2019/6/23~25 by hw_Chen2018                  ...

  3. 42 在Raspberry Pi上安装dlib表情识别

    https://www.jianshu.com/p/848014d8dea9 https://www.pyimagesearch.com/2017/05/01/install-dlib-raspber ...

  4. 基于深度学习的人脸性别识别系统(含UI界面,Python代码)

    摘要:人脸性别识别是人脸识别领域的一个热门方向,本文详细介绍基于深度学习的人脸性别识别系统,在介绍算法原理的同时,给出Python的实现代码以及PyQt的UI界面.在界面中可以选择人脸图片.视频进行检 ...

  5. keras系列︱人脸表情分类与识别:opencv人脸检测+Keras情绪分类(四)

    引自:http://blog.csdn.net/sinat_26917383/article/details/72885715 人脸识别热门,表情识别更加.但是表情识别很难,因为人脸的微表情很多,本节 ...

  6. 深度学习项目——基于卷积神经网络(CNN)的人脸在线识别系统

    基于卷积神经网络(CNN)的人脸在线识别系统 本设计研究人脸识别技术,基于卷积神经网络构建了一套人脸在线检测识别系统,系统将由以下几个部分构成: 制作人脸数据集.CNN神经网络模型训练.人脸检测.人脸 ...

  7. 机器学习: Tensor Flow with CNN 做表情识别

    我们利用 TensorFlow 构造 CNN 做表情识别,我们用的是FER-2013 这个数据库, 这个数据库一共有 35887 张人脸图像,这里只是做一个简单到仿真实验,为了计算方便,我们用其中到 ...

  8. UWP通过机器学习加载ONNX进行表情识别

    首先我们先来说说这个ONNX ONNX是一种针对机器学习所设计的开放式的文件格式,用于存储训练好的模型.它使得不同的人工智能框架(如Pytorch, MXNet)可以采用相同格式存储模型数据并交互. ...

  9. Python学习案例之视频人脸检测识别

    前言 上一篇博文与大家分享了简单的图片人脸识别技术,其实在实际应用中,很多是通过视频流的方式进行识别,比如人脸识别通道门禁考勤系统.人脸动态跟踪识别系统等等. 案例 这里我们还是使用 opencv 中 ...

随机推荐

  1. java学习之路--多线程实现的方法

    1 继承Thread类 继承Thread类的方法尽管被我列为一种多线程实现方式,但Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Th ...

  2. FTPService工具类

    package com.vcredit.ddcash.server.commons.net; import com.vcredit.ddcash.server.commons.model.FtpPar ...

  3. kubernetes组成

    kubernetes组成 k8s主要包括: kubectl 客户端命令行工具: 将接收的命令,发送给kube-apiserver,作为对整个平台操作的入口. kube-apiserver REST A ...

  4. 逆向工程之修改关键CALL返回值_破解视频转换专家

    1)注册软件随便输入注册名注册码 2)进入软件根目录,发送到PEID查壳 3)发现无壳 4)发送到OD 4.1)右键菜单选择智能搜索 4.2)找到关键信息点注册 4.3)找到关键信息点双击进入汇编,向 ...

  5. C和C指针小记(十四)-字符串、字符和字节

    1.字符串 C语言没有字符串数据类型,因为字符串以字符串常量的形式出现或存储于字符数组中. 字符串常量和适用于那些程序不会对他们进行修改的字符串. 所有其他字符串都必须存储于字符串数组或动态分配的内存 ...

  6. PowerPoint使用技巧

    1.右键Group两个元素,可以一起移动: 2.Insert 屏幕输入功能: 3.录制旁白: 4.录制完旁白之后可以生成视频: 5.如果不确定所有引用的组件是否可以在别的机器上使用,可以导出只CD,生 ...

  7. caffe中的卷积

    https://www.zhihu.com/question/28385679 如上,将三维的操作转换到二维上面去做,然后调用GEMM库进行矩阵间的运算得到最后结果. 两个矩阵相乘,需要中间的那个维度 ...

  8. 为什么分布式数据库中不使用uuid作为主键?

    分布式数据库当然也有主键的需求,但是为什么不直接使用uuid作为主键呢?作为曾经被这个问题困惑过的人,试着回答一下 1. UUID生成速率低下 Java的UUID依赖于SecureRandom.nex ...

  9. PHP中new self()和new static()的区别探究

    1.new static()是在PHP5.3版本中引入的新特性. 2.无论是new static()还是new self(),都是new了一个新的对象. 3.这两个方法new出来的对象有什么区别呢,说 ...

  10. python中的双冒号作用

    Python序列切片地址可以写为[开始:结束:步长],其中的开始和结束可以省略. 1. range(n)生成[0,n)区间整数 2. 开始start省略时,默认从第0项开始 3. 结尾省略的时候,默认 ...