OpenCV-Python实战(番外篇)——想要识别猫咪的情绪?从猫脸检测开始

x33g5p2x  于2022-03-11 转载在 Python  
字(7.7k)|赞(0)|评价(0)|浏览(478)

前言

前些天看到朋友分享的猫咪情绪识别软件的消息,可能小伙伴们也都跃跃欲试,想要做一个合格的铲屎官了。但是想要想识别猫的情绪表情,首先从猫脸检测开始吧!
我们已经学习了如何使用 Python Web 框架创建并部署完整的 Web人脸检测应用程序,在本项目中,我们将使用 OpenCVFlask 构建检测猫脸的深度学习 Web 应用程序。

猫脸检测

在开始讲解之前,让我们首先快速浏览下项目结构:

cat_detection
	|——server
	|	├─cat_detection.py
	|	└─image_processing.py
	└─client
		├─request_and_draw_rectangle.py
		└─test_example.png

使用级联检测器检测猫脸

为了更好的进行代码分离,检测程序在 image_processing.py 脚本中执行,其中编码了 ImageProcessing() 类。我们在 ImageProcessing 类中实现 cat_face_detection() 方法,利用 OpenCV 中的 detectMultiScale() 函数执行猫脸检测。

# image_processing.py
class ImageProcessing(object):
    def __init__(self):
        # 在构造函数中实例化猫脸检测器
        self.file_cascade = os.path.join(os.path.join(os.path.dirname(__file__), 'data'), "haarcascade_frontalcatface_extended.xml")
        self.cat_cascade = cv2.CascadeClassifier(self.file_cascade)

    def cat_face_detection(self, image):
        image_array = np.asarray(bytearray(image), dtype=np.uint8)
        img_opencv = cv2.imdecode(image_array, -1)

        output = []
        gray = cv2.cvtColor(img_opencv, cv2.COLOR_BGR2GRAY)
        cats = self.cat_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(25, 25))
        for cat in cats:
            # 返回检测到的猫脸检测框坐标
            x, y, w, h = cat.tolist()
            face = {'box': [x, y, x + w, y + h]}
            output.append(face)
        return output

使用深度学习模型检测图片中的猫

ImageProcessing 类的 cat_detection() 方法使用预训练的 MobileNet SSD 对象检测执行猫检测,它可以检测 20 个类。在本项目中,我们的目标是检测猫,如果 class_id 是一只猫,我们会将检测结果添加到 output 中:

# 在 image_processing.py 中添加 cat_detection() 方法
class ImageProcessing(object):
    def __init__(self):
        # 在构造函数中实例化猫脸检测器
        self.file_cascade = os.path.join(os.path.join(os.path.dirname(__file__), 'data'), "haarcascade_frontalcatface_extended.xml")
        self.cat_cascade = cv2.CascadeClassifier(self.file_cascade)
        # 在构造函数中实例化 SSD 深度学习模型用于检测猫
        self.file_prototxt = os.path.join(os.path.join(os.path.dirname(__file__), 'data'), "MobileNetSSD_deploy.prototxt.txt")
        self.file_caffemodel = os.path.join(os.path.join(os.path.dirname(__file__), 'data'), "MobileNetSSD_deploy.caffemodel")
        self.classes = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus",
                        "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike",
                        "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
        self.net = cv2.dnn.readNetFromCaffe(self.file_prototxt, self.file_caffemodel)
    
    def cat_detection(self, image):
        image_array = np.asarray(bytearray(image), dtype=np.uint8)
        img_opencv = cv2.imdecode(image_array, -1)
        # 图像预处理
        blob = cv2.dnn.blobFromImage(img_opencv, 0.007843, (300, 300), (127.5, 127.5, 127.5))
        # 前向计算
        self.net.setInput(blob)
        detections = self.net.forward()
        # 预处理后图像尺寸
        dim = 300
        
        output = []
        
        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]
            if confidence > 0.1:
                # 获取类别标签
                class_id = int(detections[0, 0, i, 1])
                # 获取对象位置的坐标
                left = int(detections[0, 0, i, 3] * dim)
                top = int(detections[0, 0, i, 4] * dim)
                right = int(detections[0, 0, i, 5] * dim)
                bottom = int(detections[0, 0, i, 6] * dim)
                # 图像尺寸的比例系数
                heightFactor = img_opencv.shape[0] / dim
                widthFactor = img_opencv.shape[1] / dim
                # 检测框坐标
                left = int(widthFactor * left)
                top = int(heightFactor * top)
                right = int(widthFactor * right)
                bottom = int(heightFactor * bottom)
                # 检测目标是否是猫
                if self.classes[class_id] == 'cat':
                    cat = {'box': [left, top, right, bottom]}
                    output.append(cat)
        return output

以上猫检测模型,使用了 MobileNet-SSD 目标检测模型,这里对训练后 MobileNet-SSD 模型架构和模型权重参数文件进行压缩供大家进行下载,也可以自己构建模型训练获得 MobileNet-SSD 模型参数。

将 OpenCV 猫脸检测程序部署在 Web 端

接下来将使用 OpenCV 创建一个深度学习猫检测 Web APIcat_detection 项目对 Web 服务器应用程序实现在 Web 端检测猫,cat_detection.py 脚本负责解析请求并构建对客户端的响应:

# cat_detection.py
from flask import Flask, request, jsonify
import urllib.request
from image_processing import ImageProcessing

app = Flask(__name__)
ip = ImageProcessing()

@app.errorhandler(400)
def bad_request(e):
    return jsonify({'status': 'Not ok', 'message': 'This server could not understand your request'}), 400

@app.errorhandler(404)
def not_found(e):
    return jsonify({'status': 'Not found', 'message': 'Route not found'}), 404

@app.errorhandler(500)
def not_found(e):
    return jsonify({'status': 'Internal error', 'message': 'Internal error occurred in server'}), 500

@app.route('/catfacedetection', methods=['GET', 'POST', 'PUT'])
def detect_cat_faces():
    if request.method == 'GET':
        if request.args.get('url'):
            with urllib.request.urlopen(request.args.get('url')) as url:
                return jsonify({'status': 'Ok', 'result': ip.cat_face_detection(url.read())}), 200
        else:
            return jsonify({'status': 'Bad request', 'message': 'Parameter url is not present'}), 400
    elif request.method == 'POST':
        if request.files.get('image'):
            return jsonify({'status': 'Ok', 'result': ip.cat_face_detection(request.files['image'].read())}), 200
        else:
            return jsonify({'status': 'Bad request', 'message': 'Parameter image is not present'}), 400
    else:
        return jsonify({'status': 'Failure', 'message': 'PUT method not supported for API'}), 405

@app.route('/catdetection', methods=['GET', 'POST', 'PUT'])
def detect_cats():
    if request.method == 'GET':
        if request.args.get('url'):
            with urllib.request.urlopen(request.args.get('url')) as url:
                return jsonify({'status': 'Ok', 'result': ip.cat_detection(url.read())}), 200
        else:
            return jsonify({'status': 'Bad request', 'message': 'Parameter url is not present'}), 400
    elif request.method == 'POST':
        if request.files.get('image'):
            return jsonify({'status': 'Ok', 'result': ip.cat_detection(request.files['image'].read())}), 200
        else:
            return jsonify({'status': 'Bad request', 'message': 'Parameter image is not present'}), 400
    else:
        return jsonify({'status': 'Failure', 'message': 'PUT method not supported for API'}), 405

if __name__ == '__main__':
    app.run(host='0.0.0.0')

如上所示,使用 route() 装饰器将 detect_cat_faces() 函数绑定到 /catfacedetection URL,并将detect_cats() 函数绑定到 /catdetection URL,并且使用 jsonify() 函数创建 application/json MIME 类型的给定参数的 JSON 表示,此 API 支持 GETPOST 请求,我们还通过使用 errorhandler() 装饰函数来注册错误处理程序。

构造请求检测图像中的猫和猫脸

为了测试此API,编写 request_and_draw_rectangle.py 程序:

# request_and_draw_rectangle.py
import cv2
import numpy as np
import requests
from matplotlib import pyplot as plt

def show_img_with_matplotlib(color_img, title, pos):
    img_RGB = color_img[:, :, ::-1]
    ax = plt.subplot(1, 2, pos)
    plt.imshow(img_RGB)
    plt.title(title, fontsize=10)
    plt.axis('off')

CAT_FACE_DETECTION_REST_API_URL = "http://localhost:5000/catfacedetection"
CAT_DETECTION_REST_API_URL = "http://localhost:5000/catdetection"
IMAGE_PATH = "test_example.png"

# 加载图像构建有效负载
image = open(IMAGE_PATH, 'rb').read()
payload = {'image': image}

image_array = np.asarray(bytearray(image), dtype=np.uint8)
img_opencv = cv2.imdecode(image_array, -1)

fig = plt.figure(figsize=(12, 7))
plt.suptitle("Using cat detection API", fontsize=14, fontweight='bold')
show_img_with_matplotlib(img_opencv, "source image", 1)
# 发送 GET 请求
r = requests.post(CAT_DETECTION_REST_API_URL, files=payload)
# 解析返回信息
print("status code: {}".format(r.status_code))
print("headers: {}".format(r.headers))
print("content: {}".format(r.json()))
json_data = r.json()
result = json_data['result']
# 绘制猫脸检测框
for cat in result:
    left, top, right, bottom = cat['box']
    cv2.rectangle(img_opencv, (left, top), (right, bottom), (0, 255, 0), 2)
    cv2.circle(img_opencv, (left, top), 10, (0, 0, 255), -1)
    cv2.circle(img_opencv, (right, bottom), 10, (255, 0, 0), -1)

# 发送 GET 请求
r = requests.post(CAT_FACE_DETECTION_REST_API_URL, files=payload)
# 解析返回信息
print("status code: {}".format(r.status_code))
print("headers: {}".format(r.headers))
print("content: {}".format(r.json()))
json_data = r.json()
result = json_data['result']
# 绘制猫检测框
for face in result:
    left, top, right, bottom = face['box']
    cv2.rectangle(img_opencv, (left, top), (right, bottom), (0, 255, 255), 2)
    cv2.circle(img_opencv, (left, top), 10, (0, 0, 255), -1)
    cv2.circle(img_opencv, (right, bottom), 10, (255, 0, 0), -1)

# 结果可视化
show_img_with_matplotlib(img_opencv, "cat detection", 2)
plt.show()

在以上示例中,我们发送了两个 POST 请求以检测猫脸以及图像中的猫,然后根据结果解析来自两个请求的响应并绘制结果:

后记

可以对以上项目进行修改,例如可以在服务器端直接绘制检测框,返回带有检测框的图像;或者读取摄像头视频帧,从而可以实时看到猫咪的行动状态;或者通过检测到的猫脸进一步进行情绪识别,当然需要首先简单的训练一个猫咪情绪识别模型。

相关链接

OpenCV-Python实战(14)——一文详解人脸检测(仅需6行代码轻松学会4种人脸检测方法)
OpenCV-Python实战(19)——OpenCV与深度学习的碰撞
OpenCV-Python实战(20)——OpenCV计算机视觉项目在Web端的部署
OpenCV-Python实战(21)——OpenCV人脸检测项目在Web端的部署

相关文章