0


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

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

前言

前些天看到朋友分享的

  1. 猫咪情绪识别软件

的消息,可能小伙伴们也都跃跃欲试,想要做一个合格的

  1. 铲屎官

了。但是想要想识别猫的情绪表情,首先从猫脸检测开始吧!
我们已经学习了如何使用

  1. Python Web

框架创建并部署完整的

  1. Web

人脸检测应用程序,在本项目中,我们将使用

  1. OpenCV

  1. Flask

构建检测猫脸的深度学习

  1. Web

应用程序。

猫脸检测

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

  1. cat_detection
  2. |——server
  3. | ├─cat_detection.py
  4. | └─image_processing.py
  5. └─client
  6. ├─request_and_draw_rectangle.py
  7. └─test_example.png

使用级联检测器检测猫脸

为了更好的进行代码分离,检测程序在

  1. image_processing.py

脚本中执行,其中编码了

  1. ImageProcessing()

类。我们在

  1. ImageProcessing

类中实现

  1. cat_face_detection()

方法,利用

  1. OpenCV

中的

  1. detectMultiScale()

函数执行猫脸检测。

  1. # image_processing.pyclassImageProcessing(object):def__init__(self):# 在构造函数中实例化猫脸检测器
  2. self.file_cascade = os.path.join(os.path.join(os.path.dirname(__file__),'data'),"haarcascade_frontalcatface_extended.xml")
  3. self.cat_cascade = cv2.CascadeClassifier(self.file_cascade)defcat_face_detection(self, image):
  4. image_array = np.asarray(bytearray(image), dtype=np.uint8)
  5. img_opencv = cv2.imdecode(image_array,-1)
  6. output =[]
  7. gray = cv2.cvtColor(img_opencv, cv2.COLOR_BGR2GRAY)
  8. cats = self.cat_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(25,25))for cat in cats:# 返回检测到的猫脸检测框坐标
  9. x, y, w, h = cat.tolist()
  10. face ={'box':[x, y, x + w, y + h]}
  11. output.append(face)return output

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

  1. ImageProcessing

类的

  1. cat_detection()

方法使用预训练的

  1. MobileNet SSD

对象检测执行猫检测,它可以检测 20 个类。在本项目中,我们的目标是检测猫,如果

  1. class_id

是一只猫,我们会将检测结果添加到

  1. output

中:

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

以上猫检测模型,使用了

  1. MobileNet-SSD

目标检测模型,这里对训练后

  1. MobileNet-SSD

模型架构和模型权重参数文件进行压缩供大家进行下载,也可以自己构建模型训练获得

  1. MobileNet-SSD

模型参数。

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

接下来将使用

  1. OpenCV

创建一个深度学习猫检测

  1. Web API

  1. cat_detection

项目对

  1. Web

服务器应用程序实现在

  1. Web

端检测猫,

  1. cat_detection.py

脚本负责解析请求并构建对客户端的响应:

  1. # cat_detection.pyfrom flask import Flask, request, jsonify
  2. import urllib.request
  3. from image_processing import ImageProcessing
  4. app = Flask(__name__)
  5. ip = ImageProcessing()
  6. @app.errorhandler(400)defbad_request(e):return jsonify({'status':'Not ok','message':'This server could not understand your request'}),400
  7. @app.errorhandler(404)defnot_found(e):return jsonify({'status':'Not found','message':'Route not found'}),404
  8. @app.errorhandler(500)defnot_found(e):return jsonify({'status':'Internal error','message':'Internal error occurred in server'}),500
  9. @app.route('/catfacedetection', methods=['GET','POST','PUT'])defdetect_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())}),200else:return jsonify({'status':'Bad request','message':'Parameter url is not present'}),400elif request.method =='POST':if request.files.get('image'):return jsonify({'status':'Ok','result': ip.cat_face_detection(request.files['image'].read())}),200else:return jsonify({'status':'Bad request','message':'Parameter image is not present'}),400else:return jsonify({'status':'Failure','message':'PUT method not supported for API'}),405
  10. @app.route('/catdetection', methods=['GET','POST','PUT'])defdetect_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())}),200else:return jsonify({'status':'Bad request','message':'Parameter url is not present'}),400elif request.method =='POST':if request.files.get('image'):return jsonify({'status':'Ok','result': ip.cat_detection(request.files['image'].read())}),200else:return jsonify({'status':'Bad request','message':'Parameter image is not present'}),400else:return jsonify({'status':'Failure','message':'PUT method not supported for API'}),405if __name__ =='__main__':
  11. app.run(host='0.0.0.0')

如上所示,使用

  1. route()

装饰器将

  1. detect_cat_faces()

函数绑定到

  1. /catfacedetection URL

,并将

  1. detect_cats()

函数绑定到

  1. /catdetection URL

,并且使用

  1. jsonify()

函数创建

  1. application/json MIME

类型的给定参数的

  1. JSON

表示,此

  1. API

支持

  1. GET

  1. POST

请求,我们还通过使用

  1. errorhandler()

装饰函数来注册错误处理程序。

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

为了测试此API,编写

  1. request_and_draw_rectangle.py

程序:

  1. # request_and_draw_rectangle.pyimport cv2
  2. import numpy as np
  3. import requests
  4. from matplotlib import pyplot as plt
  5. defshow_img_with_matplotlib(color_img, title, pos):
  6. img_RGB = color_img[:,:,::-1]
  7. ax = plt.subplot(1,2, pos)
  8. plt.imshow(img_RGB)
  9. plt.title(title, fontsize=10)
  10. plt.axis('off')
  11. CAT_FACE_DETECTION_REST_API_URL ="http://localhost:5000/catfacedetection"
  12. CAT_DETECTION_REST_API_URL ="http://localhost:5000/catdetection"
  13. IMAGE_PATH ="test_example.png"# 加载图像构建有效负载
  14. image =open(IMAGE_PATH,'rb').read()
  15. payload ={'image': image}
  16. image_array = np.asarray(bytearray(image), dtype=np.uint8)
  17. img_opencv = cv2.imdecode(image_array,-1)
  18. fig = plt.figure(figsize=(12,7))
  19. plt.suptitle("Using cat detection API", fontsize=14, fontweight='bold')
  20. show_img_with_matplotlib(img_opencv,"source image",1)# 发送 GET 请求
  21. 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()))
  22. json_data = r.json()
  23. result = json_data['result']# 绘制猫脸检测框for cat in result:
  24. left, top, right, bottom = cat['box']
  25. cv2.rectangle(img_opencv,(left, top),(right, bottom),(0,255,0),2)
  26. cv2.circle(img_opencv,(left, top),10,(0,0,255),-1)
  27. cv2.circle(img_opencv,(right, bottom),10,(255,0,0),-1)# 发送 GET 请求
  28. 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()))
  29. json_data = r.json()
  30. result = json_data['result']# 绘制猫检测框for face in result:
  31. left, top, right, bottom = face['box']
  32. cv2.rectangle(img_opencv,(left, top),(right, bottom),(0,255,255),2)
  33. cv2.circle(img_opencv,(left, top),10,(0,0,255),-1)
  34. cv2.circle(img_opencv,(right, bottom),10,(255,0,0),-1)# 结果可视化
  35. show_img_with_matplotlib(img_opencv,"cat detection",2)
  36. plt.show()

在以上示例中,我们发送了两个

  1. POST

请求以检测猫脸以及图像中的猫,然后根据结果解析来自两个请求的响应并绘制结果:
构造请求检测图像中的猫和猫脸

后记

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

相关链接

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


本文转载自: https://blog.csdn.net/LOVEmy134611/article/details/120584236
版权归原作者 盼小辉丶 所有, 如有侵权,请联系我们删除。

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

还没有评论