微信自动回复+图片识别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tustzhoujian/article/details/81780298

之前写了深度学习环境的搭建,并在环境中搭建了深度神经网络加以训练,最终完成了猫狗图片的分类。那么,是否可以利用训练得到的模型,在其他应用场景完成拓展呢?

本文将利用itchat和图灵机器人(可以不用图灵机器人,不过只能识别图片,不能聊天太枯燥了吧ˇ▽ˇ)搭建私人微信账号,完成私号的消息自动回复以及图片识别。

1、先修知识:

(当然,这里也可以直接利用keras官网提供的基于ImageNet上预训练模型的完成图片识别功能。示例中,我们将利用keras提供的基于imageNet上预训练的xception模型完成图片识别功能。)

2、效果展示

个人聊天窗口:

群聊窗口:@才会回复

3、直接上代码,注释应该够清楚了

#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
# @Author = JasonZhou
# @File  : myItchat.py
# @Date  : 2018/8/15
'''

import itchat
import requests
import cv2
from keras.applications import xception
import numpy as np
import matplotlib.pyplot as plt


KEY = 'd437bcbd717347b58066b929872cc13b'#tuling key,可以自己申请
model = xception.Xception(weights="imagenet")

def get_response(self, msg):
    #构造要发送给图灵机器人服务器的数据
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key' : self.KEY,
        'info' : msg,#发送给tuling的msg
        'userid' : 'JasonZhou89',#自己的用户id,随意填写
    }
    try:
        # 发送一个post请求
        r = requests.post(apiUrl, data=data).json()
        #字典的get方法在字典没有‘text’值时,返回None而不抛出异常
        return r.get('text')
    #为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常
    #如果服务器没有正常交互(返回非json或无法链接),那么就会进入下面的return
    except:
        #返回None
        return


#单人聊天(文本)
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(self, msg):
    #为了保证在图灵key出现问题时仍可以回复,这里设置一个默认的回复
    defaultReply = r'这个问题难住了我--'
    #如果图灵出问题,那么返回就是None
    reply = self.get_response(msg['Text'])
    #a or b,如果a有内容返回a,否则返回b
    return reply or defaultReply

#群聊(文本)
@itchat.msg_register(itchat.content.TEXT, isGroupChat=True)
def group_text_reply(self, msg):
    from_group = ''
    group = itchat.get_chatrooms(update=True)
    for g in group:
        #print(g['NickName'])#打印所有群名
        #只针对想要设置的群进行微信机器人
        if g['NickName'] == u'行业大神交流群': #换成自己群的名称
            from_group = (g['UserName']) #获取群名对应的id
    if msg['FromUserName'] ==from_group:
        # 当然如果只想针对@你的人才回复,可以设置if msg['isAt']:
        if msg['isAt']:
            reply = self.get_response(msg['Text'])
            defaultReply = r'这个问题难住了我--'
            return reply or defaultReply

#利用xception模型对图片进行识别分类,返回分类结果topN
def pred_ped(self, img_path, top_num, preprocess_input, decode_predictions):
    x = cv2.imread(img_path)
    x = x[:, :, ::-1]
    x = cv2.resize(x, (299, 299))
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = self.model.predict(x)
    dps = decode_predictions(preds, top_num)[0]
    return(dps)

#单人聊天(图片)
@itchat.msg_register(itchat.content.PICTURE)
def download_files(self, msg):
    friend = itchat.search_friends(userName=msg['FromUserName'])
    filename = msg['FileName']
    convertfilename = filename.replace('.', '.convert.')
    msg['Text'](filename)#下载图片
    #模型预测图片内容
    dp = self.pred_ped( filename,5,xception.preprocess_input, xception.decode_predictions)
    if dp[4][2]*100 > 1:
        # 将图片内容前5个可能性,用饼图形式返回
        labels = [dp[0][1], dp[1][1], dp[2][1], dp[3][1], dp[4][1]]
        sizes = [int(100 * dp[0][2]), int(100*dp[1][2]), int(100*dp[2][2]), int(100*dp[3][2]), int(100*dp[4][2])]
        colors = 'yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'red'
        explode = 0, 0, 0, 0, 0
    elif dp[3][2]*100 > 1:
        # 将图片内容前4个可能性,用饼图形式返回
        labels = [dp[0][1], dp[1][1], dp[2][1], dp[3][1]]
        sizes = [int(100*dp[0][2]), int(100*dp[1][2]), int(100*dp[2][2]), int(100*dp[3][2])]
        colors = 'yellowgreen', 'gold', 'lightskyblue', 'lightcoral'
        explode = 0, 0, 0, 0
    elif dp[2][2]*100 > 1:
        # 将图片内容前3个可能性,用饼图形式返回
        labels = [dp[0][1], dp[1][1], dp[2][1]]
        sizes = [int(100*dp[0][2]), int(100*dp[1][2]), int(100*dp[2][2])]
        colors = 'yellowgreen', 'gold', 'lightskyblue'
        explode = 0, 0, 0
    elif dp[1][2] * 100 > 1:
        # 将图片内容前2个可能性,用饼图形式返回
        labels = [dp[0][1], dp[1][1]]
        sizes = [int(100*dp[0][2]), int(100*dp[1][2])]
        colors = 'yellowgreen', 'gold'
        explode = 0, 0, 0
    else:
        # 将图片内容以文字类型返回
        itchat.send("这张图片 {:.4f}% 的概率是 {}".format(100 * dp[0][2], dp[0][1]), msg['FromUserName'])
        return
    plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=50)
    plt.axis('equal')
    plt.savefig(r'C:\Users\zhj\Anaconda2\envs\test\algorithm\1.jpg')
    plt.close()
    f = r'C:\Users\zhj\Anaconda2\envs\test\algorithm\1.jpg' #图片地址
    itchat.send_image(f,  msg['FromUserName'])



if __name__ == '__main__':
    itchat.auto_login(hotReload=True)#为了让实验更加方便(修改程序不需要多次扫码),我们使用热启动
    itchat.run()

猜你喜欢

转载自blog.csdn.net/tustzhoujian/article/details/81780298
今日推荐