成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

視頻分析:圖表可視化與YoloV10架構的計數、速度和距離估算

開發
本文我將討論YoloV10以及我的視頻分析演示項目,該項目通過圖表可視化估算物體計數、速度和距離,以商業角度出發。

計算機視覺是一個跨學科的科學領域,涉及如何讓計算機從數字圖像或視頻中獲得高級理解。從工程的角度來看,它旨在理解和自動化人類視覺系統能夠完成的任務?,F在,任務分類、物體檢測、分割和關鍵點檢測是主要的實時計算機視覺應用。那么,大家認為它是如何發展的呢?首先,我們簡要討論一下計算機視覺的主要問題。

看看上面的圖片后,您對與計算機視覺挑戰相關的所有關鍵術語有了清晰的理解。這是一個嚴重的問題,盡管它取決于問題的陳述。然而,這種困難通常是每個2D計算機視覺工程師都會遇到的。

六年前,我開始了我的圖像處理職業生涯,進而學習了計算機視覺,掌握了許多基礎知識,然后根據挑戰需求轉向基于深度學習的模型。例如,我會詳細探討和研究許多數學概念,如resnet和vgg19、unet、efficientnet等。然而,當我與許多學生談論早期的計算機視覺時,他們都只提到“YOLO”。此外,大多數人不了解YOLO的后端操作。由于YOLO的廣泛流行以及與其他模型相比的極高準確性,這才是真正重要的。

每個人都希望有現成的解決方案——只需安裝軟件包并讓過程發生——而不必了解后端操作。解決方案就是YOLO(Ultralytics)。我將討論YoloV10以及我的視頻分析演示項目,該項目通過圖表可視化估算物體計數、速度和距離,以商業角度出發。

什么是YOLO?

基于CNN的物體檢測器主要用于推薦系統。YOLO(You Only Look Once)模型用于高性能的物體檢測。YOLO將圖像劃分為網格系統,每個網格在其中檢測物體。它們可以用于基于數據流的實時物體檢測,并且需要很少的計算資源。

目前YoloV10已經發布!YoloV10的主要特點是什么?

實時物體檢測旨在以最小的延遲準確預測圖像中的物體類別和位置。YOLO系列在性能和效率之間取得了平衡,但仍存在依賴NMS和架構效率低下的問題。YoloV10通過引入無NMS訓練和專注于效率和準確性的模型設計策略解決了這些問題。

架構

YOLOv10通過幾個創新改進了之前的YOLO模型:

  • Backbone:使用改進的CSPNet以更好的梯度流和減少計算冗余。
  • Neck:結合PAN層進行有效的多尺度特征融合,聚合不同尺度的特征。
  • One-to-Many Head:在訓練期間為每個物體生成多個預測,豐富了監督信號并提高學習準確性。
  • One-to-one Head:在推理期間為每個物體輸出單一最佳預測,消除了對NMS的需求并減少了延遲。

主要特點:

  • 無NMS訓練:利用一致的雙重分配消除NMS需求,減少推理延遲。
  • 整體模型設計:優化組件以兼顧效率和準確性,具有輕量級分類頭、空間通道解耦下采樣和排名引導塊設計。
  • 增強的模型能力:采用大核卷積和部分自注意模塊,在不顯著增加計算成本的情況下提高性能。

YOLOV10的特別之處

YOLOv10引入了一種突破性的方法進行實時物體檢測,消除了非最大抑制(NMS)的需求,并優化了模型組件以獲得卓越的性能。通過利用一致的雙重分配和整體的效率-準確性驅動的模型設計,YOLOv10實現了最先進的準確性,并減少了計算開銷。其架構包括增強的主干和頸部組件,以及創新的一對多和一對一頭。憑借針對不同應用需求的模型變體,YOLOv10在準確性和效率方面設定了新標準,超越了之前的YOLO版本和其他當代檢測器。例如,YOLOv10-S在COCO數據集上比RT-DETR-R18快1.8倍,具有相似的AP,而YOLOv10-B的延遲減少了46%,參數減少了25%,與YOLOv9-C性能相同。

視頻分析:圖表可視化中的計數、速度、距離估算

在這個項目中,我開發了一個系統,用戶可以即時獲得特定物體的計數、速度和距離估算,并通過圖形進行可視化。這種能力為企業提供了即時且可操作的洞察,帶來了巨大的好處。

我使用了Ultralytics的模型,特別是YOLOv8s和YOLOv8n,以其高準確性、效率和低延遲的物體檢測而著稱。這些模型對于簡化終端分析非常重要,使整個過程更加順暢和有效。

開發體驗非常愉快,并展示了通過先進技術解決商業挑戰的巨大潛力。雖然YoloV8和YoloV10模型也能產生良好的結果,但YoloV10在準確性和延遲方面表現更好。


'''
Final code: Video Analytics Specific Object

Guidance

1. User Input: Specific object
2. Specific Object detection, Speed and distance estimation
3. Graph Analytics: Pie, Area, Multi-Class line

!pip install ultralytics

'''

#Helper function
def create_pie_chart(data):
    fig, ax = plt.subplots(figsize=(4, 3))  # Aspect ratio of 4:3
    ax.pie(data.values(), labels=data.keys(), autopct='%1.1f%%')
    ax.legend()
    ax.set_title("Total Percentage of Individual Class Perspective")
    plt.close(fig)
    return fig

def create_area_plot(class_counts_over_time):
    fig, ax = plt.subplots(figsize=(4, 3))  # Aspect ratio of 4:3
    sorted_keys = sorted(class_counts_over_time.keys())
    for cls in sorted_keys:
        ax.fill_between(range(len(class_counts_over_time[cls])), class_counts_over_time[cls], label=cls, alpha=0.6)
    ax.legend()
    ax.set_title("Distribution of Each Class Over Time")
    ax.set_xlabel("Frame Count")
    ax.set_ylabel("Count")
    plt.close(fig)
    return fig

def create_multiple_line_plot(speed_data, distance_data, frame_count):
    fig, ax = plt.subplots(figsize=(4, 3))  # Aspect ratio of 4:3
    for track_id in speed_data.keys():
        ax.plot(range(frame_count), speed_data[track_id], label=f"Speed {track_id}")
    for track_id in distance_data.keys():
        ax.plot(range(frame_count), distance_data[track_id], label=f"Distance {track_id}")
    ax.legend()
    ax.set_title("Speed and Distance Identification of Each Class")
    ax.set_xlabel("Frame Count")
    ax.set_ylabel("Value")
    plt.close(fig)
    return fig

def create_scatter_plot(data):
    fig, ax = plt.subplots(figsize=(4, 3))  # Aspect ratio of 4:3
    x = list(data.keys())
    y = list(data.values())
    ax.scatter(x, y)
    ax.set_title("Class Distribution Scatter Plot")
    ax.set_xlabel("Class")
    ax.set_ylabel("Count")
    plt.close(fig)
    return fig

def fig_to_img(fig):
    fig.canvas.draw()
    img = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
    img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    return img

def resize_and_place_image(base_image, overlay_image, position):
    overlay_image_resized = cv2.resize(overlay_image, (w // 3, h // 3))
    x, y = position
    base_image[y:y + overlay_image_resized.shape[0], x:x + overlay_image_resized.shape[1]] = overlay_image_resized
    return base_image

def draw_visualizations(frame, data, labels, speed_data, distance_data, class_counts_over_time, frame_count):
    vis_frame = np.zeros((h, w // 3, 3), dtype=np.uint8)

    # Create Pie Chart
    if data:
        pie_chart = create_pie_chart(data)
        pie_chart_img = fig_to_img(pie_chart)
        vis_frame = resize_and_place_image(vis_frame, pie_chart_img, (0, 0))

    # Create Area Plot
    if class_counts_over_time:
        area_plot = create_area_plot(class_counts_over_time)
        area_plot_img = fig_to_img(area_plot)
        vis_frame = resize_and_place_image(vis_frame, area_plot_img, (0, h // 3))

    # Create Multiple Line Plot
    if speed_data or distance_data:
        line_plot = create_multiple_line_plot(speed_data, distance_data, frame_count)
        line_plot_img = fig_to_img(line_plot)
        vis_frame = resize_and_place_image(vis_frame, line_plot_img, (0, 2 * (h // 3)))

    combined_frame = np.hstack((frame, vis_frame))
    return combined_frame

def pad_lists_to_length(data_dict, length, default_value=0):
    for key in data_dict.keys():
        if len(data_dict[key]) < length:
            data_dict[key] += [default_value] * (length - len(data_dict[key]))

'''
Main function:

Specific input based video analytics 
(object count, speed, distance estimation..)

'''

import cv2
import math
import numpy as np
import matplotlib.pyplot as plt
from ultralytics import YOLO
from ultralytics.utils.plotting import Annotator
from ultralytics.solutions import speed_estimation

# Initialize YOLO models
object_detection_model = YOLO("yolov8s.pt")
speed_estimation_model = YOLO("yolov8n.pt")
names = speed_estimation_model.model.names

# Open video file
cap = cv2.VideoCapture("/content/drive/MyDrive/yolo/race.mp4")
assert cap.isOpened(), "Error reading video file"

# Get video properties
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))

# Initialize video writer
out = cv2.VideoWriter("Distribution_speed_distance_visual_scatter_unique1hor_car_overall.avi", cv2.VideoWriter_fourcc(*"MJPG"),15, (w + w // 3, h))

frame_count = 0
data = {}
labels = []
class_counts_over_time = {}
speed_over_time = {}
distance_over_time = {}

# Center point and pixel per meter for distance calculation
center_point = (0, h)
pixel_per_meter = 10

# Line points for speed estimation
line_pts = [(0, 360), (1280, 360)]

# Initialize speed-estimation object
speed_obj = speed_estimation.SpeedEstimator(names=names, reg_pts=line_pts, view_img=False)

# Colors for text and bounding box
txt_color, txt_background, bbox_clr = ((0, 0, 0), (255, 255, 255), (255, 0, 255))

print('Example input: horse:17, person: 0,car: 2, van: 8,bus: 5,tree: 62')
# Allow user to input desired classes
user_input = input("Enter desired classes with their IDs (format: 'class1:id1,class2:id2,...'): ")
# Example input: "person:0,car:2,horse:17"
desired_classes = {}
for item in user_input.split(','):
    cls, cls_id = item.split(':')
    desired_classes[cls.strip()] = int(cls_id.strip())

print("Desired classes:", desired_classes)

while cap.isOpened():
    success, frame = cap.read()
    if not success:
        break

    frame_count += 1

    # Object detection for speed estimation
    speed_tracks = speed_estimation_model.track(frame, persist=True, show=False)
    frame = speed_obj.estimate_speed(frame, speed_tracks)

    # Object detection for distance estimation
    annotator = Annotator(frame, line_width=2)
    results = object_detection_model.track(frame, persist=True)

    if results[0].boxes.id is not None:
        boxes = results[0].boxes.xyxy.cpu()
        track_ids = results[0].boxes.id.int().cpu().tolist()
        clss = results[0].boxes.cls.cpu().tolist()

        for box, track_id, cls in zip(boxes, track_ids, clss):
            cls_name = object_detection_model.names[int(cls)]
            if cls_name in desired_classes and desired_classes[cls_name] == cls:  # Filter desired classes and IDs
                if cls_name not in labels:
                    labels.append(cls_name)

                if cls_name in data:
                    data[cls_name] += 1
                else:
                    data[cls_name] = 1

                annotator.box_label(box, label=str(track_id), color=bbox_clr)
                annotator.visioneye(box, center_point)

                x1, y1 = int((box[0] + box[2]) // 2), int((box[1] + box[3]) // 2)  # Bounding box centroid

                distance = (math.sqrt((x1 - center_point[0]) ** 2 + (y1 - center_point[1]) ** 2)) / pixel_per_meter

                text_size, _ = cv2.getTextSize(f"Distance: {distance:.2f} m", cv2.FONT_HERSHEY_SIMPLEX, 1.2, 3)
                cv2.rectangle(frame, (x1, y1 - text_size[1] - 10), (x1 + text_size[0] + 10, y1), txt_background, -1)
                cv2.putText(frame, f"Distance: {distance:.2f} m", (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 1.2, txt_color, 3)

                if track_id not in distance_over_time:
                    distance_over_time[track_id] = [0] * (frame_count - 1)
                distance_over_time[track_id].append(distance)

                speed = speed_obj.speeds.get(track_id, 0) if hasattr(speed_obj, 'speeds') else 0
                if track_id not in speed_over_time:
                    speed_over_time[track_id] = [0] * (frame_count - 1)
                speed_over_time[track_id].append(speed)

                if cls_name not in class_counts_over_time:
                    class_counts_over_time[cls_name] = [0] * frame_count
                if len(class_counts_over_time[cls_name]) < frame_count:
                    class_counts_over_time[cls_name].extend([0] * (frame_count - len(class_counts_over_time[cls_name])))
                class_counts_over_time[cls_name][-1] += 1

    # Pad lists to current frame count to ensure equal lengths
    pad_lists_to_length(distance_over_time, frame_count)
    pad_lists_to_length(speed_over_time, frame_count)

    # Draw combined visualizations on the frame
    combined_frame = draw_visualizations(frame, data, labels, speed_over_time, distance_over_time, class_counts_over_time, frame_count)

    # Write the frame with visualizations
    out.write(combined_frame)

    # Clear counts for next frame
    data = {}

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# Generate and overlay scatter plot on the final frame
final_frame = np.zeros((h, w, 3), dtype=np.uint8)
scatter_plot = create_scatter_plot(class_counts_over_time)
scatter_plot_img = fig_to_img(scatter_plot)
final_frame = resize_and_place_image(final_frame, scatter_plot_img, (0, 0))

# Save the final frame with the scatter plot
cv2.imwrite("final_frame_with_scatter_plot.png", final_frame)

cap.release()
out.release()
cv2.destroyAllWindows()

# Print overall analytics
total_counts = sum(sum(counts) for counts in class_counts_over_time.values())
print(f"Overall total count: {total_counts}")
for cls, counts in class_counts_over_time.items():
    print(f"Total count for {cls}: {sum(counts)}")

best_speed = max((max(speeds) for speeds in speed_over_time.values()), default=0)
print(f"Overall best speed: {best_speed} m/s")
best_distance = max((max(distances) for distances in distance_over_time.values()), default=0)
print(f"Overall best distance: {best_distance} meters")

輸出:

在我看來,這個模型對于識別物體非常出色,并且可以輕松地針對特定物體進行微調。即使對于那些不熟悉AI或深度學習的人來說,這個程序也非常容易使用且廣泛應用。一個經常出現的重要問題是,為什么AI、深度學習和計算機視覺工程師熱衷于開發這樣的項目。原因是多方面的。這些項目為推動該領域的發展和解決現實問題提供了寶貴的機會。我已經建議每個人盡快完成這項任務。該領域的增長路徑對于所有人都是相同的,但在物體識別和分割項目中仍需解決許多挑戰。

這些挑戰包括:

  • 光線:光線條件的變化會顯著影響物體檢測的準確性。
  • 環境:不同的背景和設置會使識別過程復雜化。
  • 問題定義:識別和解決正確的問題對于這些項目的成功至關重要。
  • 實地工作:在實際條件下的實施和測試是必不可少的,但管理起來可能很困難。

參考資料:

  • https://github.com/VK-Ant/Computervision_Exploration
  • https://docs.ultralytics.com/guides/analytics/
  • https://docs.ultralytics.com/models/yolov10/#holistic-efficiency-accuracy-driven-model-design
責任編輯:趙寧寧 來源: 小白玩轉Python
相關推薦

2024-12-03 15:25:27

2021-10-11 08:04:22

Python數據行程

2015-08-20 10:04:40

可視化

2020-03-01 14:01:22

Echarts數據可視化圖表

2023-10-24 20:38:15

數據分析機器學習

2023-06-11 16:12:14

數據可視化圖表類型

2023-08-01 16:01:59

可視化Seaborn

2021-04-09 10:42:03

數據可視化框架大數據

2022-06-29 08:28:58

數據可視化數據可視化平臺

2017-02-07 15:54:14

數據可視化數據分析

2017-05-23 09:07:48

可視化圖表視覺

2022-08-23 12:32:37

Python可視化圖表

2022-05-30 08:37:34

可視化圖表項目開源

2017-08-15 18:55:57

大數據數據可視化圖表

2023-10-12 08:02:36

2022-07-13 15:54:14

Matplotlib圖表

2019-05-28 11:52:43

可視化圖表數據

2024-08-22 12:49:02

2024-10-14 17:43:05

2023-12-25 15:51:07

探索性數據分析數據可視化
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产91在线 | 中日 | 欧美精品乱码久久久久久按摩 | 欧美1区| 日韩国产精品一区二区三区 | 亚洲免费观看视频 | www.成人久久 | 久在线 | 久久无毛 | 午夜精品在线 | 中文字幕日韩一区 | 国产在线观看一区 | 久久精品国产亚洲 | 日日摸夜夜添夜夜添精品视频 | 玖玖操 | 午夜黄色影院 | 免费一级网站 | 欧美一级大片 | 国产传媒在线观看 | 日韩福利| 国产a级毛毛片 | 精品久久久久久久久久久院品网 | 午夜激情免费 | 亚洲成人精品 | 婷婷久久综合 | a免费观看 | 特黄一级 | 精品一二三区在线观看 | 久草中文在线观看 | 久久这里只有精品首页 | 黄色毛片视频 | 免费a在线 | 成人精品| 一区二区三区四区在线免费观看 | 成人欧美日韩一区二区三区 | av黄色片| 综合久| 亚洲一区在线观看视频 | 精品视频在线观看 | 成人午夜视频在线观看 | 精品国产一区二区三区观看不卡 | 国产av毛片 |