用Python实现人工智能(人脸识别)年龄、情绪分类
python实现柱状图统计
·
用的是IDEA运行的
import os
import webbrowser
from icrawler.builtin import BingImageCrawler
from aip import AipFace # 人脸检测
import base64 # 导包
from pyecharts.charts import Bar
from pyecharts import options as opts
# 用于统计不同年龄阶段人数的频数
count = [0, 0, 0, 0] # 分别对应婴儿、少年、青年、老人,顺序可根据实际定义调整
def bing_image_crawler(keyword, max_num):
"""
通过Bing搜索下载图片,具体参数自行调配
:param keyword: 关键字
:param max_num: 最大尝试次数
"""
bing_crawler = BingImageCrawler(
feeder_threads=2,
parser_threads=4,
downloader_threads=8,
storage={'root_dir': 'bing'} # 存储到bing目录下
)
bing_crawler.crawl(keyword=keyword, max_num=max_num)
def get_file_content(file_path):
"""
对本地文件进行BASE64编码,以便于后续上传服务器
:param file_path: 文件的路径,项目根目录的文件直接写文件名
:return: 编码后的字符串
"""
file = open(file_path, 'rb') # 打开文件
# 开始读取
data = file.read()
# 进行BASE64编码
content = base64.b64encode(data)
# 还需要使用utf-8解码
base = content.decode('utf-8')
# 关闭文件流
file.close()
return base
def detect_face(img_base64):
"""
检测人脸并获取年龄相关信息
:param img_base64: 图片编码
:return: 返回JSON原始数据
"""
# 三个身份识别码
APP_ID = '16966840'
API_KEY = 'B0e6QoxUB0gwQxxzWT6fCgMU'
SECRET_KEY = 'rGQji0R0X76e4CP9rbcdPbcNRdS6EwC9'
# 创建人脸检测对象
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
# 获取年龄信息以及其他可能需要的人脸基础信息
options = {'face_field': 'age'}
# 向服务器发起请求
json = client.detect(img_base64, 'BASE64', options)
return json
def parse_json(json):
"""
从服务器返回的JSON数据中提取所需的年龄数据,并划分年龄阶段
:param json: 服务器返回的JSON数据
:return: 解析的内容,对应年龄阶段的索引(0:婴儿,1:少年,2:青年,3:老人),-1表示人脸检测失败
"""
# 先判断人脸检测是否成功
code = json['error_code']
if code == 0:
age = json['result']['face_list'][0]['age']
if age < 3:
return 0 # 婴儿
elif age < 18:
return 1 # 少年
elif age < 60:
return 2 # 青年
else:
return 3 # 老人
else:
print("失败")
return -1
def classify():
"""
按照人脸的年龄阶段进行分类,分类绘制统计图
:return:
"""
root_dir = 'bing' # 图片根目录
# 返回当前目录下的所有文件列表
file_list = os.listdir(root_dir)
print(file_list)
# 遍历目录
for i in file_list:
# 拼接出目录+文件名的格式
path = root_dir + '/' + i
print(path)
# 只有文件才给百度
if os.path.isfile(path):
# 转码
base = get_file_content(path)
# 百度人脸检测
json = detect_face(base)
# 解析数据
age_stage = parse_json(json)
# 全局变量
global count
# 统计数量
if age_stage == -1: # 不是人脸
continue
else:
count[age_stage] += 1
# 拼接分类文件夹的路径
dic = root_dir + '/' + ["婴儿", "少年", "青年", "老人"][age_stage]
# 如果上面的文件夹不存在,则创建
if not os.path.exists(dic):
# 创建文件夹
os.makedirs(dic)
# 把当前分析的图片移动到对应的子目录中
# 参数1:源文件的位置
# 参数2:目标文件位置
os.rename(path, dic + '/' + i)
def draw_chart(key_word):
"""
画图
:param key_word: 图表标题
"""
global count
# V1 版本开始支持链式调用
bar = (
Bar()
.add_xaxis(["婴儿", "少年", "青年", "老人"])
.add_yaxis(key_word, count)
.set_global_opts(title_opts=opts.TitleOpts(title=key_word + "年龄分布情况"))
)
bar.render('数据可视化.html')
# 通过代码调用浏览器打开结果
webbrowser.open('数据可视化.html')
if __name__ == '__main__':
# 录入要爬取的关键字和数量
keyword = input('请输入要爬取的图片名称:')
max_num = int(input('请输入要爬取的数量:'))
# 开始爬取
bing_image_crawler(keyword, max_num)
# 图片识别并分类
classify()
draw_chart(keyword)
要自己在文件夹里面添加爬虫图片的代码:
运行的网页效果:
人类情绪分类代码:
import os
import webbrowser
from icrawler.builtin import BingImageCrawler
from aip import AipFace
import base64
from pyecharts.charts import Bar
from pyecharts import options as opts
# 用于统计不同情绪的数量,假设可能的情绪有 'happy','sad', 'angry', 'neutral' 等
emotion_count = {'happy': 0,'sad': 0, 'angry': 0, 'neutral': 0}
def bing_image_crawler(keyword, max_num):
"""
通过Bing搜索下载图片,具体参数自行调配
:param keyword: 关键字
:param max_num: 最大尝试次数
"""
bing_crawler = BingImageCrawler(
feeder_threads=2,
parser_threads=4,
downloader_threads=8,
storage={'root_dir': 'bing'} # 存储到bing目录下
)
bing_crawler.crawl(keyword=keyword, max_num=max_num)
def get_file_content(file_path):
"""
对本地文件进行BASE64编码,以便于后续上传服务器
:param file_path: 文件的路径,项目根目录的文件直接写文件名
:return: 编码后的字符串
"""
file = open(file_path, 'rb') # 打开文件
# 开始读取
data = file.read()
# 进行BASE54编码
content = base64.b64encode(data)
# 还需要使用utf-8解码
base = content.decode('utf-8')
# 关闭文件流
file.close()
return base
def detect_face(img_base64):
"""
检测人脸
:param img_base64: 图片编码
:return: 返回JSON原始数据
"""
# 三个身份识别码
APP_ID = '16966840'
API_KEY = 'B0e6QoxUB0gwQxxzWT6fCgMU'
SECRET_KEY = 'rGQji0R0X76e4CP9rbcdPbcNRdS6EwC9'
# 创建人脸检测对象
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
# 只要情绪
options = {'face_field': 'emotion'}
# 向服务器发起请求
json = client.detect(img_base64, 'BASE64', options)
return json
def parse_json(json):
"""
从服务器返回的JSON数据中提取所需的数据
:param json: 服务器返回的JSON数据
:return: 提取的情绪,如果失败则返回None
"""
# 先判断人脸检测是否成功
code = json['error_code']
if code == 0:
emotion = json['result']['face_list'][0]['emotion']['type']
return emotion
else:
return None
def classify():
"""
按照人脸的情绪进行分类,统计不同情绪的数量,并将图片移动到以情绪命名的子目录中
:return:
"""
root_dir = 'bing' # 图片根目录
# 返回当前目录下的所有文件列表
file_list = os.listdir(root_dir)
for i in file_list:
# 拼接出目录+文件名的格式
path = root_dir + '/' + i
if os.path.isfile(path):
# 转码
base = get_file_content(path)
# 百度人脸检测
json = detect_face(base)
# 解析数据
emotion = parse_json(json)
# 全局变量
global emotion_count
# 统计不同情绪的数量
if emotion:
if emotion in emotion_count:
emotion_count[emotion] += 1
else:
emotion_count[emotion] = 1
# 拼接以情绪命名的子目录路径
emotion_dir = os.path.join(root_dir, emotion)
# 如果子目录不存在,则创建
if not os.path.exists(emotion_dir):
os.makedirs(emotion_dir)
# 把当前分析的图片移动到对应的情绪子目录中
new_path = os.path.join(emotion_dir, i)
os.rename(path, new_path)
def draw_chart(key_word):
"""
画图
:param key_word: 图表标题
"""
# 获取情绪类别和对应的数量
emotions = list(emotion_count.keys())
counts = list(emotion_count.values())
bar = (
Bar()
.add_xaxis(emotions)
.add_yaxis(key_word, counts)
.set_global_opts(title_opts=opts.TitleOpts(title=key_word + "情绪分布情况"))
)
bar.render('数据可视化.html')
# 通过代码调用浏览器打开结果
webbrowser.open('数据可视化.html')
if __name__ == '__main__':
# 录入要爬取的关键字和数量
keyword = input('请输入要爬取的图片名称:')
max_num = int(input('请输入要爬取的数量:'))
# 开始爬取
bing_image_crawler(keyword, max_num)
# 图片识别并分类
classify()
draw_chart(keyword)
给它导入图片后它会自己爬出来,每次爬的结果都不一样

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)