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

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)

解析返回信息

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img



既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Python开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024c (备注Python)
img

做了那么多年开发,自学了很多门编程语言,我很明白学习资源对于学一门新语言的重要性,这些年也收藏了不少的Python干货,对我来说这些东西确实已经用不到了,但对于准备自学Python的人来说,或许它就是一个宝藏,可以给你省去很多的时间和精力。

别在网上瞎学了,我最近也做了一些资源的更新,只要你是我的粉丝,这期福利你都可拿走。

我先来介绍一下这些东西怎么用,文末抱走。


(1)Python所有方向的学习路线(新版)

这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

最近我才对这些路线做了一下新的更新,知识体系更全面了。

在这里插入图片描述

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然没有那么全面,但是对于入门来说是没问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

(4)200多本电子书

这些年我也收藏了很多电子书,大概200多本,有时候带实体书不方便的话,我就会去打开电子书看看,书籍可不一定比视频教程差,尤其是权威的技术书籍。

基本上主流的和经典的都有,这里我就不放图了,版权问题,个人看看是没有问题的。

(5)Python知识点汇总

知识点汇总有点像学习路线,但与学习路线不同的点就在于,知识点汇总更为细致,里面包含了对具体知识点的简单说明,而我们的学习路线则更为抽象和简单,只是为了方便大家只是某个领域你应该学习哪些技术栈。

在这里插入图片描述

(6)其他资料

还有其他的一些东西,比如说我自己出的Python入门图文类教程,没有电脑的时候用手机也可以学习知识,学会了理论之后再去敲代码实践验证,还有Python中文版的库资料、MySQL和HTML标签大全等等,这些都是可以送给粉丝们的东西。

在这里插入图片描述

这些都不是什么非常值钱的东西,但对于没有资源或者资源不是很好的学习者来说确实很不错,你要是用得到的话都可以直接抱走,关注过我的人都知道,这些都是可以拿到的。

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
img

2f2f4b1af.png)

(6)其他资料

还有其他的一些东西,比如说我自己出的Python入门图文类教程,没有电脑的时候用手机也可以学习知识,学会了理论之后再去敲代码实践验证,还有Python中文版的库资料、MySQL和HTML标签大全等等,这些都是可以送给粉丝们的东西。

在这里插入图片描述

这些都不是什么非常值钱的东西,但对于没有资源或者资源不是很好的学习者来说确实很不错,你要是用得到的话都可以直接抱走,关注过我的人都知道,这些都是可以拿到的。

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
[外链图片转存中…(img-ObBfnAz9-1712841363023)]

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值