Tracking und aufnahme der Daten in Spreadsheet

import cv2
import datetime
from collections import defaultdict, deque
from ultralytics import YOLO
from googleapiclient.discovery import build
from google.oauth2 import service_account

# YOLO Setup
model = YOLO('best.pt')  
tracked_objects = set() 
confidence_buffer = defaultdict(deque)  

# Google Sheets Setup
SERVICE_ACCOUNT_FILE = 'credentials.json' 
SCOPES = ['<https://www.googleapis.com/auth/spreadsheets>']
SPREADSHEET_ID = '1i-0HYoiLWieAK4XNKwA-khVLoJhGEkG61E0NbuTsqSo'  
SHEET_NAME = 'Sheet1'  

# Google Sheets API-Service einrichten
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('sheets', 'v4', credentials=credentials)
sheet = service.spreadsheets()

# Funktion zum Schreiben in Google Spreadsheet
def write_to_google_sheets(data):
    body = {
        'values': [data]
    }
    sheet.values().append(
        spreadsheetId=SPREADSHEET_ID,
        range=f"{SHEET_NAME}!A:D",
        valueInputOption='RAW',
        body=body
    ).execute()

# IoU-Berechnung
def calculate_iou(box1, box2):
    x1 = max(box1[0], box2[0])
    y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2])
    y2 = min(box1[3], box2[3])

    intersection = max(0, x2 - x1) * max(0, y2 - y1)
    area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
    area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
    union = area1 + area2 - intersection

    return intersection / union if union > 0 else 0

# IoU- und Confidence-Parameter
iou_threshold = 0.9  
min_confidence_to_confirm = 0.85  

# Stream-URL
stream_url = '<https://s55.ipcamlive.com/streams/37hv25evmnpxnufjc/stream.m3u8>' 

# Video-Capture initialisieren
cap = cv2.VideoCapture(stream_url)

# Größe des Buffers für die gespeicherten Frames
frame_buffer_size = 45

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Stream beendet oder Fehler beim Lesen.")
        break

    # YOLO Inferenz und Tracking
    results = model.track(source=frame, persist=True, conf=0.5, iou=0.7)
    for result in results:
        if result.boxes:
            for box in result.boxes:
                # Überprüfen, ob die Box-ID existiert
                if box.id is None:
                    print("Box ID ist None, überspringe diese Box.")
                    continue

                obj_id = int(box.id)
                class_name = model.names[int(box.cls)]
                object_identifier = f"{class_name}_{obj_id}"
                current_box = box.xyxy[0].tolist() 
                confidence = float(box.conf)

                # Aktuellen Frame und Confidence in den Puffer einfügen
                confidence_buffer[object_identifier].append(confidence)
                if len(confidence_buffer[object_identifier]) > frame_buffer_size:
                    confidence_buffer[object_identifier].popleft()

                # Durchschnittliche Confidence berechnen
                avg_confidence = sum(confidence_buffer[object_identifier]) / len(confidence_buffer[object_identifier])

                # Wenn die durchschnittliche Confidence ausreichend ist
                if avg_confidence >= min_confidence_to_confirm:
                    # Objekt bestätigen und speichern
                    if object_identifier not in tracked_objects:
                        tracked_objects.add(object_identifier)

                        # Datum, Zeit und Klasse erfassen
                        current_time = datetime.datetime.now()
                        date = current_time.strftime('%Y-%m-%d')
                        time = current_time.strftime('%H:%M:%S')
                        row = [date, time, obj_id, class_name]

                        # In Google Spreadsheet schreiben
                        write_to_google_sheets(row)
                        print(f"Daten geschrieben: {row}")

    # Frame anzeigen 
    cv2.imshow('Stream', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()