diff --git a/frigate/api/media.py b/frigate/api/media.py index 69e12b74ca..12459b0b50 100644 --- a/frigate/api/media.py +++ b/frigate/api/media.py @@ -61,7 +61,11 @@ from frigate.util.file import ( get_event_thumbnail_bytes, load_event_snapshot_image, ) -from frigate.util.image import get_image_from_recording, get_image_quality_params +from frigate.util.image import ( + get_image_from_recording, + get_image_quality_params, + read_image, +) from frigate.util.object import create_empty_regions_grid from frigate.util.recording_coverage import ( build_spans, @@ -259,7 +263,7 @@ async def latest_frame( if preview_path: logger.debug(f"Using most recent preview frame for {camera_name}") - frame = cv2.imread(preview_path, cv2.IMREAD_UNCHANGED) + frame = read_image(preview_path, cv2.IMREAD_UNCHANGED) if frame is not None: is_offline = True diff --git a/frigate/camera/state.py b/frigate/camera/state.py index 0f9930de54..a30d536bb1 100644 --- a/frigate/camera/state.py +++ b/frigate/camera/state.py @@ -24,6 +24,7 @@ from frigate.util.image import ( draw_timestamp, is_better_thumbnail, is_label_printable, + write_image, ) logger = logging.getLogger(__name__) @@ -647,7 +648,7 @@ class CameraState: thumb = cv2.resize(img_frame, dsize=(width, 175), interpolation=cv2.INTER_AREA) thumb_path = os.path.join(THUMB_DIR, self.name) os.makedirs(thumb_path, exist_ok=True) - cv2.imwrite(os.path.join(thumb_path, f"{event_id}.webp"), thumb) + write_image(os.path.join(thumb_path, f"{event_id}.webp"), thumb) def shutdown(self) -> None: for obj in self.tracked_objects.values(): diff --git a/frigate/data_processing/real_time/custom_classification.py b/frigate/data_processing/real_time/custom_classification.py index 7b5ab74dbc..53eee0aab5 100644 --- a/frigate/data_processing/real_time/custom_classification.py +++ b/frigate/data_processing/real_time/custom_classification.py @@ -19,7 +19,7 @@ from frigate.log import suppress_stderr_during from frigate.util.builtin import EventsPerSecond, InferenceSpeed, load_labels from frigate.util.classification import resize_classification_image from frigate.util.file import trim_oldest_files -from frigate.util.image import calculate_region +from frigate.util.image import calculate_region, write_image from frigate.util.object import box_overlaps from ..types import DataProcessorMetrics @@ -748,5 +748,5 @@ def write_classification_attempt( file = os.path.join(folder, f"{event_id}-{timestamp}-{label}-{score}.webp") os.makedirs(folder, exist_ok=True) - cv2.imwrite(file, frame) + write_image(file, frame) trim_oldest_files(folder, max_files) diff --git a/frigate/data_processing/real_time/face.py b/frigate/data_processing/real_time/face.py index 9c508b590c..800451848a 100644 --- a/frigate/data_processing/real_time/face.py +++ b/frigate/data_processing/real_time/face.py @@ -28,7 +28,7 @@ from frigate.data_processing.common.face.recognizer import ( from frigate.types import TrackedObjectUpdateTypesEnum from frigate.util.builtin import EventsPerSecond, InferenceSpeed from frigate.util.file import trim_oldest_files -from frigate.util.image import area +from frigate.util.image import area, write_image from frigate.util.path import safe_join, sanitize_path_component from ..types import DataProcessorMetrics @@ -488,5 +488,5 @@ class FaceRealTimeProcessor(RealTimeProcessorApi): folder, f"{event_id}-{timestamp}-{sub_label}-{score}.webp" ) os.makedirs(folder, exist_ok=True) - cv2.imwrite(file, frame) + write_image(file, frame) trim_oldest_files(folder, self.config.face_recognition.save_attempts) diff --git a/frigate/output/preview.py b/frigate/output/preview.py index 4a1b99feb0..9ff20e2f95 100644 --- a/frigate/output/preview.py +++ b/frigate/output/preview.py @@ -22,7 +22,12 @@ from frigate.ffmpeg_presets import ( parse_preset_hardware_acceleration_encode, ) from frigate.models import Previews -from frigate.util.image import copy_yuv_to_position, get_blank_yuv_frame, get_yuv_crop +from frigate.util.image import ( + copy_yuv_to_position, + get_blank_yuv_frame, + get_yuv_crop, + write_image, +) from frigate.util.ownership import chown_to_runtime logger = logging.getLogger(__name__) @@ -373,7 +378,7 @@ class PreviewRecorder: ) cache_path = get_cache_image_name(self.camera_name, frame_time) - if not cv2.imwrite( + if not write_image( cache_path, small_frame, [ diff --git a/frigate/review/maintainer.py b/frigate/review/maintainer.py index 7796482678..b18c413d44 100644 --- a/frigate/review/maintainer.py +++ b/frigate/review/maintainer.py @@ -33,7 +33,11 @@ from frigate.models import ReviewSegment from frigate.review.severity import get_review_severity from frigate.review.types import SeverityEnum from frigate.track.object_processing import ManualEventState -from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop +from frigate.util.image import ( + SharedMemoryFrameManager, + calculate_16_9_crop, + write_image, +) logger = logging.getLogger(__name__) @@ -147,7 +151,7 @@ class PendingReviewSegment: self.thumb_time = datetime.datetime.now().timestamp() self.has_frame = True Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True) - if not cv2.imwrite( + if not write_image( self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60] ): logger.error("Failed to write review thumbnail to %s", self.frame_path) @@ -162,7 +166,7 @@ class PendingReviewSegment: if self._frame is not None: self.has_frame = True Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True) - if not cv2.imwrite( + if not write_image( self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60] ): logger.error("Failed to write review thumbnail to %s", self.frame_path) diff --git a/frigate/test/test_util_image.py b/frigate/test/test_util_image.py index ebdb7b276a..fbc02c12a3 100644 --- a/frigate/test/test_util_image.py +++ b/frigate/test/test_util_image.py @@ -1,9 +1,12 @@ +import os +import sys +import tempfile import unittest import cv2 import numpy as np -from frigate.util.image import get_snapshot_bytes +from frigate.util.image import get_snapshot_bytes, read_image, write_image class TestSnapshotBytes(unittest.TestCase): @@ -34,3 +37,44 @@ class TestSnapshotBytes(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class TestImageFiles(unittest.TestCase): + def setUp(self) -> None: + self.dir = tempfile.TemporaryDirectory() + self.image = np.full((20, 30, 3), 128, np.uint8) + + def tearDown(self) -> None: + self.dir.cleanup() + + def test_round_trip(self): + path = os.path.join(self.dir.name, "frame.png") + + self.assertTrue(write_image(path, self.image)) + np.testing.assert_array_equal(read_image(path), self.image) + + def test_encodes_by_extension_with_params(self): + path = os.path.join(self.dir.name, "frame.webp") + + self.assertTrue(write_image(path, self.image, [cv2.IMWRITE_WEBP_QUALITY, 60])) + with open(path, "rb") as f: + self.assertEqual(f.read(12)[8:], b"WEBP") + + def test_failures_return_falsy(self): + missing_dir = os.path.join(self.dir.name, "missing", "frame.png") + empty = os.path.join(self.dir.name, "empty.png") + open(empty, "wb").close() + + self.assertFalse(write_image(missing_dir, self.image)) + self.assertIsNone(read_image(missing_dir)) + self.assertIsNone(read_image(empty)) + + def test_path_is_not_retained(self): + path = os.path.join(self.dir.name, "frame.webp") + before = sys.getrefcount(path) + + for _ in range(3): + write_image(path, self.image) + read_image(path) + + self.assertEqual(sys.getrefcount(path), before) diff --git a/frigate/util/image.py b/frigate/util/image.py index 909a505b62..c75728a412 100644 --- a/frigate/util/image.py +++ b/frigate/util/image.py @@ -2,9 +2,11 @@ import datetime import logging +import os import subprocess as sp import threading from abc import ABC, abstractmethod +from collections.abc import Sequence from multiprocessing import resource_tracker as _mprt from multiprocessing import shared_memory as _mpshm from string import printable @@ -272,6 +274,38 @@ def get_image_quality_params(ext: str, quality: int | None) -> list[int]: return [] +def write_image(path: str, image: np.ndarray, params: Sequence[int] = ()) -> bool: + """Encode an image by the path's extension and write it to disk. + + OpenCV 4.11 keeps a reference to every path string passed to cv2.imwrite + or cv2.imread (opencv/opencv#28047), so recurring writes encode in memory. + """ + ok, encoded = cv2.imencode(os.path.splitext(path)[1], image, list(params)) + + if not ok: + return False + + try: + encoded.tofile(path) + except OSError: + return False + + return True + + +def read_image(path: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None: + """Read and decode an image without passing the path to OpenCV.""" + try: + data = np.fromfile(path, dtype=np.uint8) + except OSError: + return None + + if data.size == 0: + return None + + return cv2.imdecode(data, flags) + + def relative_box_to_absolute( frame_shape: tuple[int, ...], box: list[float] | tuple[float, ...] | None ) -> tuple[int, int, int, int] | None: