[PYTHON] I tried to combine Discord Bot and face recognition-for LT-

Introduction

Materials for presentation at LT

I tried to make the face recognition (OpenCV) that I have done so far into a bot

The item description is as follows

Why Discord?

** Somehow! ** **

Until now, I've already made it with Slack Bot.

But I wonder if LINE Bot is ...

That's right, ** Discord can make bots, right? ?? ?? ** **

I researched Discord Bot

Official (discord.py)

It looks fun so I made it ☆

How to make a Discord bot has been updated the other day. (It's a little rough ...)

Module, directory structure, etc.

module

What you need is as follows Install what you need!

pip install discord       #Used when you want to do various things with discord
pip install opencv-python #Required when using OpenCV functions (used with cv2 on python)
pip install os            #You can use functions that depend on os
pip install requests      #Used for HTTP communication
pip install shutil        #High-level manipulation of files and collections of files

Directory structure

The directory structure is as follows

-- dis_test
   -- cascade
      -- haarcascade_frontalface_alt.xml
   -- img
   -- dis.py

Face learning data is here I used.

Discord Bot

program

dis_bot.py


# coding:utf-8

import discord
import time
import requests
import shutil
import cv2
import os

# from scripts.photo_processing import PhotoProcessing

IMG_PATH = "./img/"
IMG_SIZE = (128, 128)

FACE_CASCADE_PATH = "./cascade/haarcascade_frontalface_alt.xml"
FACE_CASCADE = cv2.CascadeClassifier(FACE_CASCADE_PATH)
TOKEN = "TOKEN ID"
client = discord.Client()

now_time = time.time()
times = time.gmtime(now_time)

#bot startup processing
@client.event
async def on_ready():
    channel = client.get_channel(Channel ID)
    await channel.send("Hi! how are you?")

#When receiving a message
@client.event
async def on_message(message):
    #Ignore if sender is a bot
    if message.author.bot:
        return
    
    if message.content.startswith('trim') and len(message.attachments) != 0:
        channel_id = message.channel.id
        url = message.attachments[0].url
        file_name = url.rsplit("/", 1)[1]

        #Save image
        rst = requests.get(url, stream = True)

        open_file = open(IMG_PATH + file_name, "wb")
        shutil.copyfileobj(rst.raw, open_file)
        open_file.close()

        #Image scrutiny
        img_file = cv2.imread(IMG_PATH + file_name, cv2.IMREAD_COLOR)

        # processing
        gray_file = cv2.cvtColor(img_file, cv2.COLOR_BGR2GRAY)
        front_face_list = FACE_CASCADE.detectMultiScale(gray_file, minSize=(50, 50), minNeighbors=3)

        if len(front_face_list) > 0:
            # trimming
            for (x, y, width, height) in front_face_list:

                trim_file = img_file[y:y+height, x:x+width]
                trim_file = cv2.resize(trim_file, IMG_SIZE)

                cv2.imwrite("{0}trim_{1}".format(IMG_PATH, file_name), trim_file)

                await message.channel.send('', file=discord.File("{0}trim_{1}".format(IMG_PATH, file_name)))
        else:
            await message.channel.send("The face was not authenticated.")

        #Image deletion
        os.remove(IMG_PATH + file_name)
        os.remove("{0}trim_{1}".format(IMG_PATH, file_name))

client.run(TOKEN)

Output result Command line trim1.PNG

It recognizes the face properly and trims it trim.PNG

Of course, multiple people can trim trim2.PNG

It seems that the cropped image can be used as an icon! (I don't use it) That's all for Discord Bot x Face Recognition (˘ω˘)

Recommended Posts

I tried to combine Discord Bot and face recognition-for LT-
I tried to operate Linux with Discord Bot
I implemented DCGAN and tried to generate apples
I tried to save the data with discord
[Introduction to PID] I tried to control and play ♬
I tried to make a translation BOT that works on Discord using googletrans
I tried to debug.
I tried to paste
I tried to read and save automatically with VOICEROID2 2
I tried to implement and learn DCGAN with PyTorch
I tried adding post-increment to CPython. Overview and summary
I tried to automatically read and save with VOICEROID2
I tried adding system calls and scheduler to Linux
I tried to implement Grad-CAM with keras and tensorflow
I tried to install scrapy on Anaconda and couldn't
I tried to predict and submit Titanic survivors with Kaggle
I tried to learn PredNet
I tried two ways to combine multiple commits in Git
I tried to organize SVM.
I tried face recognition using Face ++
I tried to get Web information using "Requests" and "lxml"
I tried to implement PCANet
I tried to illustrate the time and time in C language
I tried to display the time and today's weather w
[Introduction to infectious disease model] I tried fitting and playing ♬
I tried to reintroduce Linux
I tried to introduce Pylint
I tried to make a bot that randomly acquires Wikipedia articles and tweets once a day
I tried to enumerate the differences between java and python
I tried to create a bot for PES event notification
I tried to summarize SparseMatrix
I made a discord bot
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to touch jupyter
I tried to implement StarGAN (1)
I tried to make an image classification BOT by combining TensorFlow Lite and LINE Messaging API
I tried to visualize bookmarks flying to Slack with Doc2Vec and PCA
I tried to let Pepper talk about event information and member information
I tried to make a periodical process with Selenium and Python
I tried to create Bulls and Cows with a shell program
I tried to easily detect facial landmarks with python and dlib
I tried to extract players and skill names from sports articles
I tried to implement Deep VQE
I tried to create Quip API
I tried to touch Python (installation)
I tried to implement adversarial validation
I tried to explain Pytorch dataset
I tried Watson Speech to Text
I tried to touch Tesla's API
I tried face detection with MTCNN
I tried to implement hierarchical clustering
I tried to organize about MCMC.
I tried to implement Realness GAN
I tried to move the ball
I tried face recognition with OpenCV
I tried to estimate the interval.
I tried to summarize until I quit the bank and became an engineer
I tried moving the image to the specified folder by right-clicking and left-clicking
I tried to visualize the age group and rate distribution of Atcoder
I tried to make a face diagnosis AI for a female professional golfer ①
I tried to express sadness and joy with the stable marriage problem.