首页 > 编程问答 >目标检测和跟踪 yolov8

目标检测和跟踪 yolov8

时间:2024-07-30 12:30:40浏览次数:6  
标签:python object-detection yolo yolov8 object-tracking

这里每个人我都有这个用于反对检测的代码

from ultralytics import YOLO
import streamlit as st
import cv2
from PIL import Image
import tempfile


def _display_detected_frames(conf, model, st_frame, image):
    """
    Display the detected objects on a video frame using the YOLOv8 model.
    :param conf (float): Confidence threshold for object detection.
    :param model (YOLOv8): An instance of the `YOLOv8` class containing the YOLOv8 model.
    :param st_frame (Streamlit object): A Streamlit object to display the detected video.
    :param image (numpy array): A numpy array representing the video frame.
    :return: None
    """
    # Resize the image to a standard size
    image = cv2.resize(image, (720, int(720 * (9 / 16))))

    # Predict the objects in the image using YOLOv8 model
    res = model.predict(image, conf=conf)

    # Plot the detected objects on the video frame
    res_plotted = res[0].plot()
    st_frame.image(res_plotted,
                   caption='Detected Video',
                   channels="BGR",
                   use_column_width=True
                   )


@st.cache_resource
def load_model(model_path):
    """
    Loads a YOLO object detection model from the specified model_path.

    Parameters:
        model_path (str): The path to the YOLO model file.

    Returns:
        A YOLO object detection model.
    """
    model = YOLO("best.pt")
    return model


def infer_uploaded_image(conf, model):
    """
    Execute inference for uploaded image
    :param conf: Confidence of YOLOv8 model
    :param model: An instance of the `YOLOv8` class containing the YOLOv8 model.
    :return: None
    """
    source_img = st.sidebar.file_uploader(
        label="Choose an image...",
        type=("jpg", "jpeg", "png", 'bmp', 'webp')
    )

    col1, col2 = st.columns(2)

    with col1:
        if source_img:
            uploaded_image = Image.open(source_img)
            # adding the uploaded image to the page with caption
            st.image(
                image=source_img,
                caption="Uploaded Image",
                use_column_width=True
            )

    if source_img:
        if st.button("Execution"):
            with st.spinner("Running..."):
                res = model.predict(uploaded_image,
                                    conf=conf)
                boxes = res[0].boxes
                res_plotted = res[0].plot()[:, :, ::-1]

                with col2:
                    st.image(res_plotted,
                             caption="Detected Image",
                             use_column_width=True)
                    try:
                        with st.expander("Detection Results"):
                            for box in boxes:
                                st.write(box.xywh)
                    except Exception as ex:
                        st.write("No image is uploaded yet!")
                        st.write(ex)


def infer_uploaded_video(conf, model):
    """
    Execute inference for uploaded video
    :param conf: Confidence of YOLOv8 model
    :param model: An instance of the `YOLOv8` class containing the YOLOv8 model.
    :return: None
    """
    source_video = st.sidebar.file_uploader(
        label="Choose a video..."
    )

    if source_video:
        st.video(source_video)

    if source_video:
        if st.button("Execution"):
            with st.spinner("Running..."):
                try:
                    tfile = tempfile.NamedTemporaryFile()
                    tfile.write(source_video.read())
                    vid_cap = cv2.VideoCapture(
                        tfile.name)
                    st_frame = st.empty()
                    while (vid_cap.isOpened()):
                        success, image = vid_cap.read()
                        if success:
                            _display_detected_frames(conf,
                                                     model,
                                                     st_frame,
                                                     image
                                                     )
                        else:
                            vid_cap.release()
                            break
                except Exception as e:
                    st.error(f"Error loading video: {e}")


def infer_uploaded_webcam(conf, model):
    """
    Execute inference for webcam.
    :param conf: Confidence of YOLOv8 model
    :param model: An instance of the `YOLOv8` class containing the YOLOv8 model.
    :return: None
    """
    try:
        flag = st.button(
            label="Stop running"
        )
        vid_cap = cv2.VideoCapture(0)  # local camera
        st_frame = st.empty()
        while not flag:
            success, image = vid_cap.read()
            if success:
                _display_detected_frames(
                    conf,
                    model,
                    st_frame,
                    image
                )
            else:
                vid_cap.release()
                break
    except Exception as e:
        st.error(f"Error loading video: {str(e)}")

我需要帮助来使用 YOLOv8 实现对象跟踪逻辑。我有 11 种不同级别的汽车。最初,当一辆车距离很远时,它被识别为大众汽车,置信度得分为 0.3。然而,当汽车靠近时,它被正确识别为宝马。如果我想添加计数逻辑,它会显示两辆车(大众,宝马),但只有一辆车我需要计算每个类别的汽车总数我是 YOLov8 的新手,请帮助我


当然,我可以帮助你在你的 YOLOv8 对象检测代码中加入对象跟踪和计数功能。

以下是实现这一目标的步骤,并附上代码片段来演示这些概念:

  1. 选择跟踪算法: 你需要一种跟踪算法来将跨帧的检测结果关联起来,从而识别出同一辆车。一些流行的选择包括:
  2. IOU Tracker: 简单,根据检测边界框之间的重叠来匹配对象。
  3. Centroid Tracker: 计算跨帧的检测中心点,并基于距离度量关联对象。
  4. SORT(简单在线和实时跟踪): 一种更先进的算法,使用卡尔曼滤波进行预测和匈牙利算法进行关联。
  5. DeepSORT(具有深度关联度量的 SORT): SORT 的扩展,它包含外观信息以进行更可靠的跟踪,在出现遮挡的情况下特别有用。

  6. 实现跟踪算法: 你选择的方法将决定实现的细节。为了简单起见,让我们演示如何使用 IOU 跟踪器。

```python from ultralytics import YOLO import streamlit as st import cv2 from PIL import Image import tempfile from sort import Sort # 导入 Sort 类

# ...(你的现有代码)

def _display_detected_frames(conf, model, st_frame, image, tracker): """使用 YOLOv8 模型显示视频帧上的检测到的物体,并进行对象跟踪和计数。 :param conf (float): 对象检测的置信度阈值。 :param model (YOLOv8): 包含 YOLOv8 模型的 YOLOv8 类实例。 :param st_frame (Streamlit 对象): 用于显示检测到的视频的 Streamlit 对象。 :param image (numpy 数组): 表示视频帧的 numpy 数组。 :param tracker: 用于对象跟踪的跟踪器对象。 :return: None """ # 将图像大小调整为标准大小 image = cv2.resize(image, (720, int(720 * (9 / 16))))

   # 使用 YOLOv8 模型预测图像中的物体
   res = model.predict(image, conf=conf)

   # 从结果中提取检测结果
   detections = res[0].boxes.data

   # 使用跟踪器更新跟踪结果
   tracked_objects = tracker.update(detections)

   # 在视频帧上绘制跟踪到的物体
   for obj in tracked_objects:
       x1, y1, x2, y2, obj_id = map(int, obj)
       cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
       cv2.putText(image, f"ID: {obj_id}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

   st_frame.image(image,
                  caption='检测到的视频',
                  channels="BGR",
                  use_column_width=True
                  )

# ...(你的现有代码)

def infer_uploaded_video(conf, model): """对上传的视频执行推理 :param conf: YOLOv8 模型的置信度 :param model: 包含 YOLOv8 模型的 YOLOv8 类实例。 :return: None """ source_video = st.sidebar.file_uploader( label="选择一个视频..." )

   if source_video:
       st.video(source_video)

   if source_video:
       if st.button("执行"):
           with st.spinner("正在运行..."):
               try:
                   # 初始化跟踪器
                   tracker = Sort()

                   tfile = tempfile.NamedTemporaryFile()
                   tfile.write(source_video.read())
                   vid_cap = cv2.VideoCapture(
                       tfile.name)
                   st_frame = st.empty()
                   while (vid_cap.isOpened()):
                       success, image = vid_cap.read()
                       if success:
                           _display_detected_frames(conf,
                                                   model,
                                                   st_frame,
                                                   image,
                                                   tracker
                                                   )
                       else:
                           vid_cap.release()
                           break
               except Exception as e:
                   st.error(f"加载视频时出错: {e}")

# ...(你的现有代码) ```

  1. 跟踪和计数对象: 跟踪算法将为每个检测到的对象分配唯一的 ID。通过跟踪这些 ID,你可以计算唯一对象并解决重复计数问题。

  2. 处理遮挡: 跟踪算法通常在处理遮挡(当一个对象隐藏在另一个对象后面时)方面存在困难。你可能需要根据你的具体用例和所选算法实现更高级的技术来改进这方面。

通过遵循这些步骤,你将能够增强你的 YOLOv8 对象检测代码,使其包含对象跟踪和更准确的计数功能。请记住,你选择的特定跟踪算法可能会影响性能和准确性,因此根据你的需求进行实验并选择最合适的算法非常重要。

标签:python,object-detection,yolo,yolov8,object-tracking
From: 76323172

相关文章

  • 从零开始的Python开发日记(7):短信验证功能开发流程
    短信验证功能开发流程在开发一个包含登录、注册以及短信验证的功能时,你需要遵循一个系统的开发流程。以下是实现这一功能的基本步骤,包括所需的技术和代码示例。1.环境配置首先,确保你的开发环境已经配置好,并安装了必要的库和工具。pipinstallfastapiuvicornsqlalche......
  • 【Python数值分析】革命:引领【数学建模】新时代的插值与拟合前沿技术
    目录​编辑第一部分:插值的基本原理及应用1.插值的基本原理1.1插值多项式1.2拉格朗日插值 1.3牛顿插值 1.4样条插值2.插值的Python实现2.1使用NumPy进行插值2.2使用SciPy进行插值2.2.1一维插值​编辑2.2.2二维插值3.插值的应用场景3.1数据平......
  • 在家用电脑上设置 Python 和 Jupyter,尝试打开 Jupyter 笔记本并显示错误,无法获取
    我有最新的Python版本3.12.4和以下版本的Jupyter:SelectedJupytercorepackages...IPython:8.26.0ipykernel:6.29.5ipywidgets:notinstalledjupyter_client:8.6.2jupyter_core:5.7.2jupyter_server:2.14.2jupyterlab......
  • Python - Reloading a module
    Eachmoduleisloadedintomemoryonlyonceduringaninterpretersessionorduringaprogramrun,regardlessofthenumberoftimesitisimportedintoaprogram.Ifmultipleimportsoccur,themodule’scodewillnotbeexecutedagainandagain.Suppose......
  • vscode python 3.7 pylance debugpy 插件 vsix
    可能报错  crashed5timesinthelast3minutes.Theserverwillnotberestarted.  ---pylance 可能报错  cannotreadpropertiesofundefinedreadingresolveEnvironment   --- debugger可能      vscodepython3.7调试没有反应......
  • Python获取秒级时间戳与毫秒级时间戳的方法[通俗易懂]
    参考资料:https://cloud.tencent.com/developer/article/21581481、获取秒级时间戳与毫秒级时间戳、微秒级时间戳代码语言:javascript复制importtimeimportdatetimet=time.time()print(t)#原始时间数据print(int(t))......
  • CEFPython
    在Tkinter界面中直接嵌入Selenium的浏览器视图并不是一件直接的事情,因为Selenium本身并不提供图形界面嵌入的功能。Selenium主要用于自动化web浏览器,但它并不直接控制浏览器窗口的显示方式,而是依赖于WebDriver来与浏览器交互。然而,你可以使用一些替代方案来在Tkinter应用中模拟或......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-58 - 文件下载
    1.简介前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件。因此宏哥就接着讲解和分享一下:自动化测试下载文件。可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就是访问到下载页面,然后定位到要下载的文件的下载按钮后,点击按钮就可以了。其实......
  • Python - Function Annotations
     deffunc(s:str,i:int,j:int)->str:returns[i:j]Theparametersissupposedtobeastring,soweplaceacolonaftertheparameternameandthenwritestr.Parametersiandjaresupposedtobeintegerssowewriteintforthem.Returntypeis......
  • 使用带有 pythonKit XCODE 的嵌入式 Python,在 iOS 应用程序中与 OpenCV-python 签名不
    我根据Beewares使用指南在XCODE中将Python嵌入到我的iOS项目中https://github.com/beeware/Python-Apple-support/blob/main/USAGE.md运行时,我得到pythonKit找不到由ultralytics导入的cv2错误。当我将OpenCV-python添加到我的app_packages文件夹时......