Python实现微信自动抠图换底助手

微信抠图小应用

成果展示

所需库

  • removebg
pip install removebg
  • itchat
pip install itchat
  • PIL
pip install PIL

进阶使用

  1. 购买服务器并把应用挂在上服务器长期运行,缺点是不能在电脑端微信聊天了。。
  2. 自己开发各种功能接入
  3. 推荐购买阿里云学生服务器,炒鸡便宜,25岁以下都能购买,几块钱一个月,有了服务器还可以玩各种好玩的。

步骤

  1. 安装所需要的库
  2. 前往remove.bg官网注册帐号并申请一个APIKEY(每个月50次免费使用,有点少,不过不乱玩还是足够的)
  3. 写代码。。

构建思路

  • 微信作为客户端,获取用户发来的信息开启应用并处理
global item #程序运行防止聊天干扰
global no_bg
no_bg=""
item=0
@itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    yanse=['红','橙','黄','绿','青','蓝','紫']
    global no_bg
    global item
    if msg['Type'] == 'Text' and msg['Text']=='抠图':#如果发送的消息是文本
        item=1
        return '程序已启动,请发送需要抠图的图片!如需换背景请在获取到图片后直接回复“红,橙,黄,绿,青,蓝,紫”其中一个颜色'
    elif msg['Type'] == 'Text' and msg['Text']=='退出':
        item=0
        return "程序已退出,如需继续抠图,请发送'抠图'!"
    #如果发送的消息是附件、视屏、图片、语音
    elif msg['Type'] == "Picture" and item==1:
        item=0
        path='./filex' 
        if not os.path.exists(path):
              os.makedirs(path)
        filedpx="./filex/"+msg["FileName"]#得到文件路径,目录需要手动创建
        msg.download(filedpx) #下载
#         rmbg = RemoveBg("qVZfmirnDrTp8y6vTqcghqsc","error.log") # 引号内是你获取的API
        rmbg = RemoveBg("CQF3hdmj7ApkPEBYzqBT6w48","error.log") # 引号内是你获取的API
        rmbg.remove_background_from_img_file(filedpx)
        cxk=msg.fileName.split('.')
        cxk2="."+cxk[1]+"_no_bg."
        cxk.insert(1,cxk2)
        no_bg="./filex/"+('').join(cxk)
        if os.path.exists(no_bg):#判断是否能进行抠图
            itchat.send_msg("抠图已完成,如需继续,请发送‘抠图’!如需换背景请直接回复“红,橙,黄,绿,青,蓝,紫”其中一个颜色',否则发送‘退出’退出程序!",msg['FromUserName'])
            return '@img@%s' % no_bg
        else:
            item=1
            return '无法识别该图,请继续发送图片进行抠图,否则发送‘退出’退出程序!'
    elif msg['Type'] == 'Text' and msg['Text'] in yanse:
        path=str(chuli(no_bg,msg['Text']))
#         print(path)
        itchat.send_image(path,msg['FromUserName'])
        #no_bg=""
    else:
        pass
  • 防止聊天图片干扰应用,提供开启应用关键字(“抠图”)。
if msg['Type'] == 'Text' and msg['Text']=='抠图':#如果发送的消息是文本
        item=1
        return '程序已启动,请发送需要抠图的图片!如需换背景请在获取到图片后直接回复“红,橙,黄,绿,青,蓝,紫”其中一个颜色
  • 开启应用后提示用户发送图片,接收图片并进行处理,处理完后进行返回。
 #如果发送的消息是图片
    elif msg['Type'] == "Picture" and item==1:
        item=0
        path='./filex' 
        if not os.path.exists(path):
              os.makedirs(path)
        filedpx="./filex/"+msg["FileName"]#得到文件路径,目录需要手动创建
        msg.download(filedpx) #下载
#         rmbg = RemoveBg("*************","error.log") # 引号内是你获取的API
        rmbg = RemoveBg("**************","error.log") # 引号内是你获取的API
        rmbg.remove_background_from_img_file(filedpx)
        cxk=msg.fileName.split('.')
        cxk2="."+cxk[1]+"_no_bg."
        cxk.insert(1,cxk2)
        no_bg="./filex/"+('').join(cxk)
        if os.path.exists(no_bg):#判断是否能进行抠图
            itchat.send_msg("抠图已完成,如需继续,请发送‘抠图’!如需换背景请直接回复“红,橙,黄,绿,青,蓝,紫”其中一个颜色',否则发送‘退出’退出程序!",msg['FromUserName'])
            return '@img@%s' % no_bg
        else:
            item=1
            return '无法识别该图,请继续发送图片进行抠图,否则发送‘退出’退出程序!'
  • 提示用户是否需要进行添加纯色背景,如需要只需回复颜色,获取到需求信息后回复图片
elif msg['Type'] == 'Text' and msg['Text'] in yanse:
        path=str(chuli(no_bg,msg['Text']))
#         print(path)
        itchat.send_image(path,msg['FromUserName'])
        #no_bg=""
    else:
        pass
  • 图片换底处理思路自行看代码。
def dw_image(path,yanse):
    # 输入已经去除背景的图像
    switch = {"红":[255,0,0],"橙":[255,165,0],"黄":[255,255,0],"绿":[0,255,0],"青":[0,255,255],"蓝":[0,0,255],"紫":[128,0,128]}
    im = Image.open(path)
    x, y = im.size
    try:
        for i in switch:
            if i==yanse:
        # 使用颜色来填充背景
                p = Image.new('RGBA', im.size, (switch[i][0],switch[i][1],switch[i][2]))
                p.paste(im, (0, 0, x, y), im)
                # 保存转换后的图像 
                path2='./filex/yanse_new.png'
                p.save(path2)
                return path2
    except:
        pass
  • 退出应用关键字(“退出”)
elif msg['Type'] == 'Text' and msg['Text']=='退出':
        item=0
        return "程序已退出,如需继续抠图,请发送'抠图'!"

开发过程问题

  1. 开发中逻辑处理感觉有问题但是又不知道问题在哪。。

  2. 每个用户处理完后进行图片删除不保留,一开始是自己固定时间手动清空文件夹,后面发现有点烦人,就进行一个用户处理完后下一个用户开启阶段清空上一个用户图片。

"""
   如果不保存图片则添加以下代码在收到图片并处理那段
    import shutil
    import os
    shutil.rmtree(r"D:\cxk_python\python练习\filex")
		  
    os.mkdir(r"D:\cxk_python\python练习\filex")
"""
  • 挂在服务器时防止聊天图片干扰该如何开启应用,一开始设置了关键字开启,后面发现不行,就再设定了一个旗帜(item),当关键字开启后旗帜定为True,只有旗帜为True才能开启应用进行图片处理,这样聊天时发送的图片,文字就不会进行干扰。

整体代码

import itchat
import os
from itchat.content import *
from removebg import RemoveBg
from PIL import Image
def chuli(path,yanse):
    # 输入已经去除背景的图像
    switch = {"红":[255,0,0],"橙":[255,165,0],"黄":[255,255,0],"绿":[0,255,0],"青":[0,255,255],"蓝":[0,0,255],"紫":[128,0,128]}
    im = Image.open(path)
    x, y = im.size
    try:
        for i in switch:
            if i==yanse:
        # 使用颜色来填充背景
                p = Image.new('RGBA', im.size, (switch[i][0],switch[i][1],switch[i][2]))
                p.paste(im, (0, 0, x, y), im)
                # 保存转换后的图像 
                path2='./filex/yanse_new.png'
                p.save(path2)
                return path2
    except:
        pass
global item #程序运行防止聊天干扰
global no_bg
no_bg=""
item=0
@itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    yanse=['红','橙','黄','绿','青','蓝','紫']
    global no_bg
    global item
    if msg['Type'] == 'Text' and msg['Text']=='抠图':#如果发送的消息是文本“抠图”
        item=1
        return '程序已启动,请发送需要抠图的图片!如需换背景请在获取到图片后直接回复“红,橙,黄,绿,青,蓝,紫”其中一个颜色'
    elif msg['Type'] == 'Text' and msg['Text']=='退出':
        item=0
        return "程序已退出,如需继续抠图,请发送'抠图'!"
    #如果发送的消息是图片
    elif msg['Type'] == "Picture" and item==1:
        item=0
        path='./filex' 
        if not os.path.exists(path):
              os.makedirs(path)
        filedpx="./filex/"+msg["FileName"]#得到文件路径,目录需要手动创建
        msg.download(filedpx) #下载
#         rmbg = RemoveBg("****","error.log") # 引号内是你获取的API
        rmbg = RemoveBg("*****","error.log") # 引号内是你获取的API
        rmbg.remove_background_from_img_file(filedpx)
        cxk=msg.fileName.split('.')
        cxk2="."+cxk[1]+"_no_bg."
        cxk.insert(1,cxk2)
        no_bg="./filex/"+('').join(cxk)
        if os.path.exists(no_bg):#判断是否能进行抠图
            itchat.send_msg("抠图已完成,如需继续,请发送‘抠图’!如需换背景请直接回复“红,橙,黄,绿,青,蓝,紫”其中一个颜色',否则发送‘退出’退出程序!",msg['FromUserName'])
            return '@img@%s' % no_bg
        else:
            item=1
            return '无法识别该图,请继续发送图片进行抠图,否则发送‘退出’退出程序!'
    elif msg['Type'] == 'Text' and msg['Text'] in yanse:
        path=str(chuli(no_bg,msg['Text']))
#         print(path)
        itchat.send_image(path,msg['FromUserName'])
        #no_bg=""
    else:
        pass
itchat.auto_login(hotReload=True,enableCmdQR=2)
myName = itchat.get_friends(update=True)[0]['UserName']
itchat.run()
发布了21 篇原创文章 · 获赞 14 · 访问量 4106

猜你喜欢

转载自blog.csdn.net/Cxk___/article/details/103250243