Files
yolocam-linux/yolocam-gui/yolocam_gui/ui/video_widget.py
T
2026-02-15 12:50:49 -08:00

233 lines
7.2 KiB
Python

# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Video preview widget using OpenCV capture."""
import logging
import os
import re
import numpy as np
from PySide6.QtCore import Qt, QTimer, Signal, Slot
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
from PySide6.QtGui import QImage, QPixmap, QFont
from .theme import COLOR_BG_DARK, COLOR_TEXT_SECONDARY
log = logging.getLogger(__name__)
YOLOCAM_VID = "46f8"
YOLOCAM_PID = "0855"
try:
import cv2
_HAS_CV2 = True
except ImportError:
_HAS_CV2 = False
log.warning("opencv-python not installed, video preview will be disabled")
def find_yolocam_device() -> int:
"""Scan /sys/class/video4linux for the YoloCam S3 UVC device.
Returns the lowest /dev/videoN index matching VID:PID 46f8:0855,
or -1 if not found.
"""
v4l_path = "/sys/class/video4linux"
if not os.path.isdir(v4l_path):
return -1
candidates = []
for entry in sorted(os.listdir(v4l_path)):
dev_path = os.path.join(v4l_path, entry, "device")
if not os.path.isdir(dev_path):
continue
try:
vid_path = os.path.join(dev_path, "..", "idVendor")
pid_path = os.path.join(dev_path, "..", "idProduct")
vid = open(os.path.realpath(vid_path)).read().strip()
pid = open(os.path.realpath(pid_path)).read().strip()
except (OSError, IOError):
continue
if vid == YOLOCAM_VID and pid == YOLOCAM_PID:
m = re.search(r"(\d+)$", entry)
if m:
candidates.append(int(m.group(1)))
if candidates:
return min(candidates)
return -1
class VideoWidget(QWidget):
"""Displays live camera feed from a UVC device, or a placeholder if disconnected."""
color_sampled = Signal(int, int, int)
eyedropper_deactivated = Signal()
def __init__(self, device_index: int = -1, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumSize(320, 240)
self.setStyleSheet(f"background-color: {COLOR_BG_DARK};")
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._label = QLabel()
self._label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
layout.addWidget(self._label)
self._cap = None
self._timer = QTimer(self)
self._timer.timeout.connect(self._grab_frame)
self._last_frame = None
self._eyedropper_active = False
if device_index >= 0:
self.start(device_index)
else:
self._show_placeholder()
def auto_start(self):
"""Auto-detect the YoloCam UVC device and start capture."""
idx = find_yolocam_device()
if idx < 0:
log.info("YoloCam UVC device not found")
self._show_placeholder("YoloCam not detected")
return
log.info("YoloCam UVC device found at /dev/video%d", idx)
self.start(idx)
def start(self, device_index: int = 0):
"""Open the video device and begin grabbing frames."""
if not _HAS_CV2:
self._show_placeholder("OpenCV not available")
return
self.stop()
self._cap = cv2.VideoCapture(device_index)
self._cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
if not self._cap.isOpened():
log.warning("Could not open video device %d", device_index)
self._cap = None
self._show_placeholder()
return
self._timer.start(33)
def stop(self):
"""Stop capturing and release the device."""
self._timer.stop()
if self._cap is not None:
self._cap.release()
self._cap = None
@Slot()
def _grab_frame(self):
if self._cap is None:
return
ret, frame = self._cap.read()
if not ret:
return
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self._last_frame = rgb
h, w, ch = rgb.shape
bytes_per_line = ch * w
qimg = QImage(rgb.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
scaled = qimg.scaled(
self._label.size(),
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
self._label.setPixmap(QPixmap.fromImage(scaled))
def set_eyedropper_mode(self, enabled: bool):
"""Activate or deactivate eyedropper sampling mode."""
self._eyedropper_active = enabled
if enabled:
self.setCursor(Qt.CursorShape.CrossCursor)
else:
self.unsetCursor()
def mousePressEvent(self, event):
if not self._eyedropper_active:
super().mousePressEvent(event)
return
self._eyedropper_active = False
self.unsetCursor()
if self._last_frame is None:
self.eyedropper_deactivated.emit()
return
# Map click position to frame coordinates
click_pos = self._label.mapFromParent(event.position().toPoint())
frame_h, frame_w = self._last_frame.shape[:2]
label_w = self._label.width()
label_h = self._label.height()
scale = min(label_w / frame_w, label_h / frame_h)
scaled_w = frame_w * scale
scaled_h = frame_h * scale
offset_x = (label_w - scaled_w) / 2
offset_y = (label_h - scaled_h) / 2
fx = (click_pos.x() - offset_x) * frame_w / scaled_w
fy = (click_pos.y() - offset_y) * frame_h / scaled_h
if fx < 0 or fx >= frame_w or fy < 0 or fy >= frame_h:
self.eyedropper_deactivated.emit()
return
# Average an 11x11 neighborhood
cx, cy = int(fx), int(fy)
half = 5
x0, x1 = max(0, cx - half), min(frame_w, cx + half + 1)
y0, y1 = max(0, cy - half), min(frame_h, cy + half + 1)
patch = self._last_frame[y0:y1, x0:x1]
avg = patch.mean(axis=(0, 1))
r, g, b = int(avg[0]), int(avg[1]), int(avg[2])
self.color_sampled.emit(r, g, b)
self.eyedropper_deactivated.emit()
def _show_placeholder(self, text: str = "No camera connected"):
self._label.setPixmap(QPixmap())
self._label.setText(text)
placeholder_font = QFont()
placeholder_font.setPointSize(14)
self._label.setFont(placeholder_font)
self._label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY}; background: transparent;")
def closeEvent(self, event):
self.stop()
super().closeEvent(event)