def get_fer2013_images():
"""
从csv文件得到图片集
:return:
"""
import pandas as pd
import numpy as np
import scipy.misc as sm
import os
# 定义7种表情
emotions = {
'0': 'anger', # 生气
'1': 'disgust', # 厌恶
'2': 'fear', # 恐惧
'3': 'happy', # 开心
'4': 'sad', # 伤心
'5': 'surprised', # 惊讶
'6': 'neutral', # 中性
}
def save_image_from_fer2013(file):
faces_data = pd.read_csv(file)
root = '../data/fer2013/'
# 文件主要三个属性,emotion为表情列,pixels为像素数据列,usage为数据集所属列
data_number = 0
for index in range(len(faces_data)):
# 解析每一行csv文件内容
emotion_data = faces_data.loc[index][0] # emotion
image_data = faces_data.loc[index][1] # pixels
usage_data = faces_data.loc[index][2] # usage
# 将图片数据转换成48*48
image_array = np.array(list(map(float, image_data.split()))).reshape((48, 48))
folder = root + usage_data
emotion_name = emotions[str(emotion_data)]
image_path = os.path.join(folder, emotion_name)
if not os.path.exists(folder):
os.mkdir(folder)
if not os.path.exists(image_path):
os.mkdir(image_path)
# 图片文件名
image_file = os.path.join(image_path, str(index) + '.jpg')
sm.toimage(image_array).save(image_file)
data_number += 1
print('总共有' + str(data_number) + '张图片')
save_image_from_fer2013('../data/fer2013/fer2013.csv')
def get_jaffe_images():
"""
得到按照标签存放的目录结构的数据集同时对人脸进行检测
:return:
"""
import cv2
import os
emotions = {
'AN': 0,
'DI': 1,
'FE': 2,
'HA': 3,
'SA': 4,
'SU': 5,
'NE': 6
}
emotions_reverse = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral']
def detect_face(img):
"""
检测人脸并裁减
:param img:
:return:
"""
cascade = cv2.CascadeClassifier('../data/params/haarcascade_frontalface_alt.xml')
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(rects) == 0:
# 没有检测到人脸
return []
rects[:, 2:] += rects[:, :2]
return rects
folder = '../data/jaffe'
files = os.listdir(folder)
images = []
labels = []
index = 0
for file in files:
img_path = os.path.join(folder, file) # 文件路径
img_label = emotions[str(img_path.split('.')[-3][:2])] # 文件名包含标签
labels.append(img_label)
img = cv2.imread(img_path, 1)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 下面裁减
rects_ = detect_face(img_gray)
for x1, y1, x2, y2 in rects_:
cv2.rectangle(img, (x1+10, y1+20), (x2-10, y2), (0, 255, 255), 2)
img_roi = img_gray[y1+20: y2, x1+10: x2-10]
img_roi = cv2.resize(img_roi, (48, 48))
images.append(img_roi)
# 若不裁减,即原数据集
# images.append(cv2.resize(img_gray, (48, 48)))
index += 1
if not os.path.exists('../data/jaffe/Training'):
os.mkdir('../data/jaffe/Training')
for i in range(len(images)):
path_emotion = '../data/jaffe/Training/{}'.format(emotions_reverse[labels[i]])
if not os.path.exists(path_emotion):
os.mkdir(path_emotion)
cv2.imwrite(os.path.join(path_emotion, '{}.jpg'.format(i)), images[i])
print("load jaffe dataset")
从csv文件得到图片集
最新推荐文章于 2024-06-28 13:50:39 发布