+
15
-

回答

思路:高空固定一个俯拍摄像头

固定摄像头视角:摄像头不动,俯拍整个停车场。

预先标出车位位置:在图像上手动画出每个停车位的区域(如矩形或多边形)。

实时检测车辆:用目标检测模型(如 YOLO)找出画面中所有车辆的位置。

判断车位是否被占:看每个车位区域内有没有检测到车辆。

统计空闲数量:未被占的车位数 = 总车位数 - 被占车位数。

用opencv+yolo

import cv2
import numpy as np
from ultralytics import YOLO

# 1. 加载YOLO模型(检测车辆)
model = YOLO("yolov8n.pt")  # 确保包含'car', 'truck'等类别

# 2. 预定义停车位区域(手动标注,用多边形或矩形)
# 示例:4个车位,每个是四边形顶点 [(x1,y1), (x2,y2), ...]
parking_spaces = [
    np.array([[100,200], [150,200], [150,250], [100,250]]),
    np.array([[160,200], [210,200], [210,250], [160,250]]),
    # ... 更多车位
]

# 3. 打开摄像头(或视频流)
cap = cv2.VideoCapture(0)  # 0为本地摄像头,也可用RTSP地址

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 4. 用YOLO检测车辆(只保留car, truck, bus)
    results = model(frame)
    detections = []
    for box in results[0].boxes:
        cls = int(box.cls)
        conf = float(box.conf)
        if cls in [2, 7, 5] and conf > 0.5:  # COCO: car=2, truck=7, bus=5
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            # 用中心点代表车辆位置
            cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
            detections.append((cx, cy))

    # 5. 判断每个车位是否被占
    occupied_count = 0
    for space in parking_spaces:
        occupied = False
        for (cx, cy) in detections:
            # 判断车辆中心点是否在车位多边形内
            if cv2.pointPolygonTest(space, (cx, cy), False) >= 0:
                occupied = True
                break
        color = (0, 0, 255) if occupied else (0, 255, 0)
        cv2.polylines(frame, [space], True, color, 2)
        if occupied:
            occupied_count += 1

    # 6. 显示剩余车位
    free = len(parking_spaces) - occupied_count
    cv2.putText(frame, f"Free: {free}/{len(parking_spaces)}", 
                (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow("Parking Monitor", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

停车位可手动标注为json数据,然后加载。

网友回复

我知道答案,我要回答