You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Yolov5对检测到的目标进行模糊处理?

Yolov5检测目标的模糊处理实现方法

实现步骤

  1. 读取原始图像:直接读取原始图像用于修改目标区域,避免使用results.render()生成的带框图像。
  2. 提取检测框坐标:通过模型输出的results.xyxy[0]获取每个目标的左上角(xmin, ymin)、右下角(xmax, ymax)坐标,以及置信度、类别信息。
  3. 目标区域模糊处理:使用OpenCV的高斯模糊函数,对每个检测框覆盖的图像区域进行模糊操作。
  4. 替换并展示结果:将模糊后的区域替换回原图像,最终显示处理后的效果。

完整代码示例

import torch
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt

# 加载自定义Yolov5模型
model = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5/runs/train/exp6/weights/last.pt', force_reload=True)

# 读取原始图像并转换颜色通道
img_path = os.path.join("uc.jpg")
img = cv2.imread(img_path)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # OpenCV默认BGR格式,转成Matplotlib兼容的RGB

# 模型推理
results = model(img_rgb)

# 提取检测框坐标(转为numpy数组方便处理)
detections = results.xyxy[0].cpu().numpy()

# 遍历每个检测框,执行模糊处理
for det in detections:
    xmin, ymin, xmax, ymax, conf, cls = det
    # 将浮点坐标转为整数,适配图像切片操作
    xmin, ymin, xmax, ymax = int(xmin), int(ymin), int(xmax), int(ymax)
    # 提取目标区域
    target_area = img_rgb[ymin:ymax, xmin:xmax]
    # 高斯模糊:核大小(51,51),数值越大模糊程度越高(必须为奇数)
    blurred_area = cv2.GaussianBlur(target_area, (51, 51), 0)
    # 将模糊后的区域替换回原图像
    img_rgb[ymin:ymax, xmin:xmax] = blurred_area

# 可选:如果需要保留检测框,取消以下代码注释
# for det in detections:
#     xmin, ymin, xmax, ymax, conf, cls = det
#     xmin, ymin, xmax, ymax = int(xmin), int(ymin), int(xmax), int(ymax)
#     cv2.rectangle(img_rgb, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)

# 显示处理后的图像
%matplotlib inline
plt.imshow(img_rgb)
plt.axis('off')
plt.show()

关键说明

  • 坐标处理:results.xyxy[0]返回张量格式的检测结果,转为numpy数组后更便于提取和操作坐标。
  • 模糊参数调整:高斯模糊的核大小可按需修改,比如(31,31)对应轻度模糊,(71,71)对应重度模糊,核大小必须为奇数。
  • 颜色通道转换:OpenCV读取的图像默认是BGR格式,而Matplotlib显示需要RGB格式,转换通道可避免颜色失真。

内容的提问来源于stack exchange,提问作者mete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 23:45:42