YOLOV8生成热力图
时间: 2025-05-24 08:26:34 浏览: 30
### 使用YOLOv8生成热力图
#### 将YOLOv8模型预测结果转换为热力图格式
为了创建热力图,需要处理YOLOv8模型的输出数据并将其映射至图像空间。这通常涉及提取边界框的位置信息以及对应的置信度分数。
```python
import numpy as np
from PIL import Image, ImageDraw
def create_heatmap_from_predictions(predictions, image_size=(640, 640)):
heatmap = np.zeros(image_size)
for pred in predictions:
box = pred['box']
score = pred['score']
# 增加热量值到对应区域
x_min, y_min, x_max, y_max = map(int, box)
heatmap[y_min:y_max, x_min:x_max] += score
return normalize(heatmap)
def normalize(array):
"""Normalize the array to range [0, 255]."""
min_val = np.min(array)
max_val = np.max(array)
if max_val - min_val != 0:
normalized_array = (array - min_val) / float(max_val - min_val) * 255.
else:
normalized_array = np.zeros_like(array)
return normalized_array.astype(np.uint8)
```
此部分代码展示了如何根据YOLOv8给出的目标检测结果构建基础热度矩阵[^1]。
#### 热力图与原始图片融合展示
一旦有了热量分布的数据结构之后,则需考虑怎样直观地呈现出来。一种常见的方式就是把计算所得的二维数组转化为伪彩色图像并与输入帧相混合。
```python
from matplotlib.colors import LinearSegmentedColormap
import cv2
def overlay_heatmap_on_image(original_img_path, heatmap_data):
img = cv2.imread(original_img_path)
h, w = img.shape[:2]
resized_heatmap = cv2.resize(heatmap_data, dsize=(w,h), interpolation=cv2.INTER_LINEAR)
colormap = LinearSegmentedColormap.from_list('custom', ['blue','green','yellow','red'], N=256)(resized_heatmap/255.)
result = ((colormap[:, :, :3]*255).astype(np.uint8)*0.7 + img*0.3).astype(np.uint8)
return result
```
上述函数实现了将生成好的热力图覆盖于原图之上形成最终可视化效果的功能[^2]。
#### 实现视频流中的动态热力图更新
对于连续捕获的画面序列来说,在线绘制随时间变化的趋势尤为重要。下面这段程序片段说明了针对每一帧执行前述两步操作的过程:
```python
cap = cv2.VideoCapture(video_source)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
detections = yolov8_model.detect(frame) # Assume this function returns list of dicts with 'box' and 'score'
heat_map_frame = create_heatmap_from_predictions(detections, frame.shape[:-1])
combined_output = overlay_heatmap_on_image(None, heat_map_frame) # Pass None since we're working directly on frames
cv2.imshow('Heat Map Visualization', combined_output)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
```
该循环读取来自摄像头或其他来源的一系列影像,并持续刷新屏幕上的热点显示直至用户终止进程[^3]。
阅读全文
相关推荐


















