当初有段时间有个app非常的火爆 大家应该都有玩过。就是拍照测年龄的软件,于是我就想能不能直接在微信上实现这个功能。后来查了一些资料发现真的可以实现 于是就做了起来。
代码分两个部分,一个是实现检测人脸功能的部分 另一个是关于功能的一些开启/关闭/添加/删除功能。
# -*- coding: utf-8 -*-
"""
__autor__ : AnE
"""
import requests
import json
import base64
import cv2
CLIENT_ID = "6aOag1T6XXXXXXXXXXXXXXXXXXIP823UU" # 百度的开发者ID
CLIENT_SECRET = "zXb7RjXXXXXXXXXXXXXXXlbYsfeYcZ" # 开发者密匙 需要自己去申请
HEADERS = {'Content-Type':'application/json; charset=UTF-8'}
IMG_FILE = r'.\Photos\timg.jpg'
NEW_IMG_FILE = ""
def getAccessToken(client_id, client_secret):
url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id' \
'=%s&client_secret=%s'%(client_id, client_secret)
res = requests.get(url, headers=HEADERS)
return json.loads(res.text)["access_token"]
def postFace(access_token):
url = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=%s"%access_token
f = open(IMG_FILE, "rb")
img_date = f.read()
f.close()
data = {
"image":base64.b64encode(img_date).decode("utf-8"),
"image_type":"BASE64",
"face_field":"age,beauty,glasses,expression,gender",
"max_face_num":10
}
res = requests.post(url, headers=HEADERS, data=data)
result = json.loads(res.text)
if result["error_msg"] != "pic not has face":
return json.loads(res.text)
else:
return False
def saveFaceImg(img_date):
if not img_date:
return False
img = cv2.imread(IMG_FILE)
NEW_IMG_FILE = ".\\" + IMG_FILE.split(".")[1] + "(1).jpg"
cv2.imwrite(NEW_IMG_FILE, img)
location_list = img_date['result']['face_list']
info_list = {}
for location in location_list:
beautyNum = str(location["beauty"])
sex = str(location["gender"]["type"])
age = str(location["age"])
info_list[age] = [sex,beautyNum]
location = location["location"]
left_top = (int(str(location['left']).split(".")[0]), int(str(location['top']).split(".")[0]))
right_bottom = (left_top[0] + location['width'], left_top[1] + location['height'])
text_location = (int(str((right_bottom[0]-left_top[0])/2+left_top[0]-30).split(".")[0]),left_top[1])
img = cv2.imread(NEW_IMG_FILE)
cv2.rectangle(img, left_top, right_bottom, (0, 255, 0), 4)
cv2.putText(img, age, text_location, cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 1)
cv2.imwrite(NEW_IMG_FILE, img)
return (NEW_IMG_FILE,info_list)
if __name__ == '__main__':
acc = getAccessToken(CLIENT_ID, CLIENT_SECRET)
data = postFace(acc)
saveFaceImg(data)
其中调用的是百度的人脸检测API 所以需要自己去手动申请下百度开发者账号。具体的就不细说了 自己百度吧。然后把里面的CLIENT_ID 和 CLIENT_SECRET更改一下就可以了。
# -*- coding: utf-8 -*-
"""
__autor__ : AnE
"""
import requests
import itchat
import json
import Face
import os
class TurLingAPI:
def __init__(self):
self.Tuling_API_KEY = "4a99xxxxxxxxxxxxxxxef420d0b1"
self.URL = "http://www.tuling123.com/openapi/api"
def turlingReply(self,word): #图灵获取回复
body = {"key": self.Tuling_API_KEY,
"info": word.encode("utf-8")}
res = requests.post(self.URL, data=body, verify=True)
if res:
date = json.loads(res.text)
# print(date["text"])
return date["text"]
else:
print("对不起,未获取到回复信息")
return False
SWITCH = True
SWITCH_P = True
TOKEN = Face.getAccessToken(Face.CLIENT_ID, Face.CLIENT_SECRET)
Turling = TurLingAPI()
group_list = [""]
people_list = [""]
@itchat.msg_register([itchat.content.TEXT,itchat.content.PICTURE], isGroupChat=True)
def group_reply(msg):
print("Group:%s:%s" % (msg.actualNickName, msg.text))
if SWITCH:
if msg.user["NickName"] in group_list:
if msg['isAt']:
replayData = Turling.turlingReply(msg.text)
return "Robot: %s"%replayData
if msg.user["NickName"] in group_list:
if msg["Type"] == "Picture":
msg.download(Face.IMG_FILE)
img_data = Face.postFace(TOKEN)
result = Face.saveFaceImg(img_data)
if result == False:
os.remove(Face.IMG_FILE)
elif result[0]:
text = ""
for i in result[1]:
text = text + "age:%s\nsex:%s\nbeautiful:%s\n" % (i, result[1][i][0], result[1][i][1])
itchat.send_msg(text,msg["FromUserName"])
itchat.send_image(result[0],msg["FromUserName"])
os.remove(Face.IMG_FILE)
os.remove(result[0])
@itchat.msg_register([itchat.content.TEXT,itchat.content.PICTURE],isGroupChat=False)
def cmd(msg):
global SWITCH
global SWITCH_P
p = itchat.search_friends(userName=msg['FromUserName'])["NickName"]
if p != "AnE":
print("People:%s:%s"%(p,msg.text))
if msg["ToUserName"] == "filehelper":
if msg.text == "#shutdown":
SWITCH = False
if msg.text == "#run":
SWITCH = True
if msg.text == "*shutdown":
SWITCH_P = False
if msg.text == "*run":
SWITCH_P = True
if "#add" in msg.text:
group = msg.text.split(" ")[1]
group_list.append(group)
if "#del" in msg.text:
group = msg.text.split(" ")[1]
if group in group_list:
group_list.remove(group)
if "*add" in msg.text:
people = msg.text.split(" ")[1]
people_list.append(people)
if "*del" in msg.text:
people = msg.text.split(" ")[1]
if people in people_list:
people_list.remove(people)
if SWITCH_P and msg["ToUserName"] != "filehelper":
if p in people_list:
if msg["Type"] == "Picture":
msg.download(Face.IMG_FILE)
img_data = Face.postFace(TOKEN)
result = Face.saveFaceImg(img_data)
if result == False:
os.remove(Face.IMG_FILE)
elif result[0]:
text = ""
for i in result[1]:
text = text + "age:%s\nsex:%s\nbeautiful:%s\n" % (i, result[1][i][0], result[1][i][1])
itchat.send_msg(text, msg["FromUserName"])
itchat.send_image(result[0], msg["FromUserName"])
os.remove(Face.IMG_FILE)
os.remove(result[0])
else:
replayData = Turling.turlingReply(msg.text)
return "Robot: %s" % replayData
if __name__ == '__main__':
itchat.auto_login(hotReload=True)
itchat.send("群: 添加 \ 删除(#add \ #del)\n\n好友: 添加 \ 删除(*add \ *del)", "filehelper")
itchat.run()
这个代码不仅实现了能够指定好友发图片给你 自动测试颜值 还可以变成一个智能的聊天机器人。你能够随意添加 删除好友来开关功能。聊天机器人调用了图灵的API所以需要自己去图灵官网申请一个ID。然后替换代码里面的Tuling_API_KEY
python WechatRobot.py
然后会出现一个二维码 用微信扫描 并且登陆就可以了。
登陆成功以后软件会给你文件传输助手发送一个提示消息 只要在文件传输助手里面输入指定的命令就能够添加和删除好友/群组。
#add 群名称
#del 群名称
*add 好友名称
*del 好友名称
w
软件里面的其他功能就让自己使用中发掘吧。我就不过多的叙述了。不懂的可以加我QQ:1281248141 备注一下就可以了。