使用python-opencv检测图片中的人像

最简单的方法进行图片中的人像检测

使用python-opencv配合yolov3模型进行图片中的人像检测

1、安装python-opencv、numpy

pip install opencv-python
pip install numpy 

2、下载yolo模型文件和配置文件:

下载地址:

 https://download.csdn.net/download/mldxs/88396654yicon-default.png?t=N7T8https://download.csdn.net/download/mldxs/88396654

yolo官网:

YOLO: Real-Time Object DetectionYou only look once (YOLO) is a state-of-the-art, real-time object detection system.icon-default.png?t=N7T8https://pjreddie.com/darknet/yolo/3、搬砖:代码比较简单并且带注释,不过多介绍

import cv2
import numpy as np

# 读取输入图像
image = cv2.imread('input.jpeg')

# 加载YOLOv3模型和类别标签
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
classes = []
with open('coco.data', 'r') as f:
    classes = f.read().strip().split('\n')

# 获取YOLO模型的输出层名称
layer_names = net.getLayerNames()
output_layers = []
unconnected_layers = net.getUnconnectedOutLayers()

# 根据输出层索引获取输出层名称
for i in unconnected_layers:
    output_layers.append(layer_names[i - 1])

# 为每个类别生成随机颜色
colors = np.random.uniform(0, 255, size=(len(classes), 3))

# 获取图像的尺寸
height, width, channels = image.shape

# 创建YOLO模型的输入blob
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

# 将blob设置为模型的输入
net.setInput(blob)
outs = net.forward(output_layers)

class_ids = []
confidences = []
boxes = []

# 处理YOLO模型的输出
for out in outs:
    for detection in out:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]

        # 如果置信度大于0.5并且类别是"person"(0对应COCO数据集中的"person"类)
        if confidence > 0.5 and class_id == 0:
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)

            x = int(center_x - w / 2)
            y = int(center_y - h / 2)

            boxes.append([x, y, w, h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

# 使用非极大值抑制获取最终的检测结果
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
margin = 30  # 定义边框扩展的边距大小

# 绘制边框和类别标签
for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        color = colors[i]

        # 扩展边框的坐标
        x_new = max(0, x - margin)
        y_new = max(0, y - margin)
        w_new = min(image.shape[1], w + 2 * margin)
        h_new = min(image.shape[0], h + 2 * margin)

        # 绘制扩展后的边框
        cv2.rectangle(image, (x_new, y_new), (x_new + w_new, y_new + h_new), color, 2)
        cv2.putText(image, label, (x_new, y_new - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

# 显示带有边框的图像
cv2.imshow('Detected Bodies', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

最终效果:

yolo有很多检测类别,上述代码只对人像进行检测,就是检测类别里的第一项(person)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要用PythonOpencv对人像上半身画线,可以按照以下步骤进行: 1. 导入必要的库和模块:cv2、numpy ```python import cv2 import numpy as np ``` 2. 读取原始图片 ```python img = cv2.imread('path/to/image') ``` 3. 对图片进行剪切,只保留上半身部分 ```python height, width = img.shape[:2] half_height = int(height / 2) upper_body_img = img[0:half_height, :] ``` 4. 绘制上半身轮廓线 ```python gray_img = cv2.cvtColor(upper_body_img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray_img, 100, 200) lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50, minLineLength=50, maxLineGap=10) for line in lines: x1, y1, x2, y2 = line[0] cv2.line(upper_body_img, (x1, y1), (x2, y2), (0, 0, 255), 2) ``` 5. 显示绘制完成的图片 ```python cv2.imshow('image', upper_body_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 将上述代码整合起来,可以得到以下完整代码: ```python import cv2 import numpy as np img = cv2.imread('path/to/image') height, width = img.shape[:2] half_height = int(height / 2) upper_body_img = img[0:half_height, :] gray_img = cv2.cvtColor(upper_body_img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray_img, 100, 200) lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50, minLineLength=50, maxLineGap=10) for line in lines: x1, y1, x2, y2 = line[0] cv2.line(upper_body_img, (x1, y1), (x2, y2), (0, 0, 255), 2) cv2.imshow('image', upper_body_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 运行代码后,就可以看到绘制完成的图片,其上半身部分的轮廓线已经被绘制出来了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值