|
import cv2 |
|
import numpy as np |
|
from ultralytics import YOLO |
|
|
|
|
|
model = YOLO('yolov8n.pt') |
|
|
|
|
|
cap = cv2.VideoCapture(0) |
|
|
|
|
|
if not cap.isOpened(): |
|
print("Error: Could not open camera.") |
|
exit() |
|
|
|
|
|
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320) |
|
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240) |
|
|
|
while True: |
|
|
|
ret, frame = cap.read() |
|
if not ret: |
|
print("Error: Failed to capture image") |
|
break |
|
|
|
|
|
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
night_vision = cv2.applyColorMap(gray, cv2.COLORMAP_HOT) |
|
|
|
|
|
night_vision_rgb = cv2.cvtColor(night_vision, cv2.COLOR_BGR2RGB) |
|
|
|
|
|
results = model(night_vision_rgb, stream=True, imgsz=320) |
|
|
|
|
|
for result in results: |
|
boxes = result.boxes.data.cpu().numpy() |
|
for box in boxes: |
|
x1, y1, x2, y2, score, class_id = map(int, box) |
|
label = f"{model.names[class_id]}: {score:.2f}" |
|
cv2.rectangle(night_vision, (x1, y1), (x2, y2), (0, 255, 0), 1) |
|
cv2.putText(night_vision, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) |
|
|
|
|
|
cv2.imshow('Night Vision YOLOv8x', night_vision) |
|
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord('q'): |
|
break |
|
|
|
|
|
cap.release() |
|
cv2.destroyAllWindows() |
|
|