#!/usr/bin/python
# coding:utf8
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import csv
#检测人脸
def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),flags=cv2.CASCADE_SCALE_IMAGE)
# scaleFactor=1.1:这个是每次缩小图像的比例,默认是1.1
# minNeighbors=3:匹配成功所需要的周围矩形框的数目,每一个特征匹配到的区域都是一个矩形框,
# 只有多个矩形框同时存在的时候,才认为是匹配成功,比如人脸,这个默认值是3。
#CASCADE_SCALE_IMAGE = 2, 正常比例检测
if len(rects) == 0:
return []
#数组切片
rects[:, 2:] += rects[:, :2]
return rects
#将级联算法加载到一个变量中
cascade = cv2.CascadeClassifier("D:/bydocument/haarcascade_frontalface_alt.xml")
f = "D:/bydocument/JAFFE/"
fs = os.listdir(f) #列出路径下所有文件和文件夹
data = np.zeros([213, 48*48], dtype=np.uint8) #构建全0矩阵,dtype=np.uint8创建图像容器
label = np.zeros([213], dtype=int)
#print(data)
#print(len(label))
i = 0
#具体文件夹考虑
for f1 in fs:
#print(f1) 用来检查是否全部文件夹都查询到了
tmp_path = os.path.join(f, f1) #每张图片的全路径 os.path.join用于以/连接路径
#print(tmp_path[len(f):])
#print(tmp_path)
if not os.path.isdir(tmp_path): #isdir判断路径是否为目录
img = cv2.imread(tmp_path, 1) #
dst = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #读取图片并转化
rects = detect(dst, cascade)
for x1, y1, x2, y2 in rects:
cv2.rectangle(img,(x1+10,y1+20),(x2-10,y2),(0,255,255),2)
# 调整截取脸部区域大小
img_roi = np.uint8([y2-(y1+20), (x2-10)-(x1+10)])
roi = dst[y1+20:y2, x1+10:x2-10]
img_roi = roi
re_roi = cv2.resize(img_roi, (48,48))
# 获得表情label
img_label = tmp_path[len(f):]
# print(img_label)
if img_label == 'anger':
label[i] = 0
elif img_label == 'disgust':
label[i] = 1
elif img_label == 'fear':
label[i] = 2
elif img_label == 'happiness':
label[i] = 3
elif img_label == 'sadness':
label[i] = 4
elif img_label == 'surprise':
label[i] = 5
elif img_label == 'neutral':
label[i] = 6
else:
print("get label error.......\n")
data[i][0:48*48] = np.ndarray.flatten(re_roi) #将图像二维像素扁平化
i = i + 1
# cv2.imshow("src", dst)
# cv2.imshow("img", img)
# if cv2.waitKey() == 32:
# continue
with open(r"D:/bydocument/JAFFEface.csv","w") as csvfile: #r只读的方式打开文件,w 写入文件,文件不存在则创建新文件
writer = csv.writer(csvfile)
writer.writerow(['emotions', 'pixels'])
for i in range(len(label)):
data_list = list(data[i])
b = " ".join(str(x) for x in data_list)
l = np.hstack([label[i], b])
writer.writerow(l)
这个是其他博主对于JAFFE数据集的处理代码,我对其中标签的部分进行了一点改动,但是生成的CSV文件,不管标签还是数据依旧全部是0,希望大家能给一下意见谢谢。