YOLO11解决方案之对象裁剪探索

概述

Ultralytics提供了一系列的解决方案,利用YOLO11解决现实世界的问题,包括物体计数、模糊处理、热力图、安防系统、速度估计、物体追踪等多个方面的应用。

对象裁剪是指从图像或视频中分离并提取特定的检测对象,YOLO11 模型功能可用于准确识别和划分物体,从而实现精确裁剪,以便进一步分析或处理。使用YOLO11 可以方便的对目标对象进行裁剪,可对场景中的单个项目进行深入检查或处理,同时可以显著降低数据量,方便传输和存储。

演示代码

Ultralytics提供了演示代码,展示如何使用距离计算解决方案。

复制代码
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"

# Initialize object cropper object
cropper = solutions.ObjectCropper(
    
    model="yolo11n.pt",  # model for object cropping i.e yolo11x.pt.
    classes=[0, 2],  # crop specific classes i.e. person and car with COCO pretrained model.
    # conf=0.5,  # adjust confidence threshold for the objects.
    # crop_dir="cropped-detections",  # set the directory name for cropped detections
)

# Process video
while cap.isOpened():
    success, im0 = cap.read()

    if not success:
        print("Video frame is empty or processing is complete.")
        break

    results = cropper(im0)

    # print(results)  # access the output

cap.release()
cv2.destroyAllWindows()  # destroy all opened windows

ObjectCropper参数

基本参数

参数 类型 默认值 说明
model str None Ultralytics YOLO 模型文件的路径。
crop_dir str "cropped-detections" 用于存储裁剪检测数据的目录名称。

可视化参数:

参数 类型 默认值 说明
show bool False 在这个方案中,show参数没有作用。

工作原理

ObjectCropper 类的工作原理是对图像中被检测到的物体,根据边框信息,裁剪下来,并保存为独立的图像文件。这个类比较简单。

复制代码
class ObjectCropper(BaseSolution):
    """
   这个类继承自BaseSolution类,根据检测到的边框,把物体裁剪下来保存为独立的文件。
   Attributes:
        crop_dir (str): 指定裁剪图片的保存路径
        crop_idx (int): 裁剪对象的数据
        iou (float): IoU阈值.
        conf (float): 置信度阈值.

    Methods:
        process: 对输入的图像中的检测物体进行裁剪并保存


    def __init__(self, **kwargs):
        
        super().__init__(**kwargs)

        self.crop_dir = self.CFG["crop_dir"]  # Directory for storing cropped detections
        if not os.path.exists(self.crop_dir):
            os.mkdir(self.crop_dir)  # Create directory if it does not exist
        if self.CFG["show"]:
            self.LOGGER.warning(
                f"show=True disabled for crop solution, results will be saved in the directory named: {self.crop_dir}"
            )
        self.crop_idx = 0  # Initialize counter for total cropped objects
        self.iou = self.CFG["iou"]
        self.conf = self.CFG["conf"]

    def process(self, im0):
        
        results = self.model.predict(
            im0, classes=self.classes, conf=self.conf, iou=self.iou, device=self.CFG["device"]
        )[0]

        for box in results.boxes:
            self.crop_idx += 1
            save_one_box(
                box.xyxy,
                im0,
                file=Path(self.crop_dir) / f"crop_{self.crop_idx}.jpg",
                BGR=True,
            )

        # Return SolutionResults
        return SolutionResults(plot_im=im0, total_crop_objects=self.crop_idx)

效果展示

这里使用演示代码和测试视频,展示裁剪的物体图片。

裁剪图片保存在指定目录下:

相关推荐
hey you~1 分钟前
2026年大模型语音机器人知识库导入与调优全指南:从切分到重排序的7个关键步骤
人工智能·机器人·语音识别·向量检索·rag·知识库导入·知识库调优
ch62310 分钟前
《AI 辅助编程实战:从零跑通一个 Excel 报表生成脚本的踩坑与复盘》
人工智能·python
云边云科技_云网融合11 分钟前
持续深化合作 | 云边云科技再次通过亚马逊云科技的能力认证
人工智能·科技
Joy T12 分钟前
Agent 上线前怎么评测:从完成标准、离线测试集到 Trace 回归
人工智能·trace·eval·回归测试
小天源17 分钟前
智叟云集系统架构解析:从品牌 AI 可见度监测到前后端协同
人工智能·react.js·系统架构·node.js·react·ai监测·ai品牌监测
Tangyuewei18 分钟前
Agent 别裸奔进生产:先搭架构、可观测、人审三道闸
人工智能·ai编程
睡后收入26 分钟前
PDF 转 draw.io:把设计文档里的架构图恢复成下一版源文件
人工智能
用户66026761187929 分钟前
换个对话就丢进度?给 AI Coding 留一张能核对的开发状态卡
人工智能
用户8231456152732 分钟前
AI 生成的代码,凭什么说它"可靠"?|5 个陷阱 + 一张自检清单
人工智能
Gu0Qiang35 分钟前
从 0 到 1 打造 AI 提示流编排器:别让 Agent 原地鬼打墙!连续 3 次相同工具调用的柔性引导与硬熔断(开源系列 19)
人工智能·github