这里每个人我都有这个用于反对检测的代码
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 对象检测代码中加入对象跟踪和计数功能。
以下是实现这一目标的步骤,并附上代码片段来演示这些概念:
- 选择跟踪算法: 你需要一种跟踪算法来将跨帧的检测结果关联起来,从而识别出同一辆车。一些流行的选择包括:
- IOU Tracker: 简单,根据检测边界框之间的重叠来匹配对象。
- Centroid Tracker: 计算跨帧的检测中心点,并基于距离度量关联对象。
- SORT(简单在线和实时跟踪): 一种更先进的算法,使用卡尔曼滤波进行预测和匈牙利算法进行关联。
-
DeepSORT(具有深度关联度量的 SORT): SORT 的扩展,它包含外观信息以进行更可靠的跟踪,在出现遮挡的情况下特别有用。
-
实现跟踪算法: 你选择的方法将决定实现的细节。为了简单起见,让我们演示如何使用 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}")
# ...(你的现有代码) ```
-
跟踪和计数对象: 跟踪算法将为每个检测到的对象分配唯一的 ID。通过跟踪这些 ID,你可以计算唯一对象并解决重复计数问题。
-
处理遮挡: 跟踪算法通常在处理遮挡(当一个对象隐藏在另一个对象后面时)方面存在困难。你可能需要根据你的具体用例和所选算法实现更高级的技术来改进这方面。
通过遵循这些步骤,你将能够增强你的 YOLOv8 对象检测代码,使其包含对象跟踪和更准确的计数功能。请记住,你选择的特定跟踪算法可能会影响性能和准确性,因此根据你的需求进行实验并选择最合适的算法非常重要。
标签:python,object-detection,yolo,yolov8,object-tracking From: 76323172