mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-30 01:07:07 +03:00
avoid opencv path leak on recurring image writes
OpenCV 4.11's Python bindings keep a reference to every path string passed to cv2.imwrite or cv2.imread (opencv/opencv#28047, fixed in 4.13, which needs numpy 2). Callers that write on every frame or event leaked one string per call for the life of the process, about 8 MB a day from preview frames on two cameras. New write_image and read_image helpers encode and decode in memory and do the file I/O through numpy, so OpenCV never sees the path. Preview frames, review and event thumbnails, face and classification training attempts, and the offline preview frame read now use them.
This commit is contained in:
@@ -61,7 +61,11 @@ from frigate.util.file import (
|
|||||||
get_event_thumbnail_bytes,
|
get_event_thumbnail_bytes,
|
||||||
load_event_snapshot_image,
|
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.object import create_empty_regions_grid
|
||||||
from frigate.util.recording_coverage import (
|
from frigate.util.recording_coverage import (
|
||||||
build_spans,
|
build_spans,
|
||||||
@@ -259,7 +263,7 @@ async def latest_frame(
|
|||||||
|
|
||||||
if preview_path:
|
if preview_path:
|
||||||
logger.debug(f"Using most recent preview frame for {camera_name}")
|
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:
|
if frame is not None:
|
||||||
is_offline = True
|
is_offline = True
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ from frigate.util.image import (
|
|||||||
draw_timestamp,
|
draw_timestamp,
|
||||||
is_better_thumbnail,
|
is_better_thumbnail,
|
||||||
is_label_printable,
|
is_label_printable,
|
||||||
|
write_image,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -647,7 +648,7 @@ class CameraState:
|
|||||||
thumb = cv2.resize(img_frame, dsize=(width, 175), interpolation=cv2.INTER_AREA)
|
thumb = cv2.resize(img_frame, dsize=(width, 175), interpolation=cv2.INTER_AREA)
|
||||||
thumb_path = os.path.join(THUMB_DIR, self.name)
|
thumb_path = os.path.join(THUMB_DIR, self.name)
|
||||||
os.makedirs(thumb_path, exist_ok=True)
|
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:
|
def shutdown(self) -> None:
|
||||||
for obj in self.tracked_objects.values():
|
for obj in self.tracked_objects.values():
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from frigate.log import suppress_stderr_during
|
|||||||
from frigate.util.builtin import EventsPerSecond, InferenceSpeed, load_labels
|
from frigate.util.builtin import EventsPerSecond, InferenceSpeed, load_labels
|
||||||
from frigate.util.classification import resize_classification_image
|
from frigate.util.classification import resize_classification_image
|
||||||
from frigate.util.file import trim_oldest_files
|
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 frigate.util.object import box_overlaps
|
||||||
|
|
||||||
from ..types import DataProcessorMetrics
|
from ..types import DataProcessorMetrics
|
||||||
@@ -748,5 +748,5 @@ def write_classification_attempt(
|
|||||||
|
|
||||||
file = os.path.join(folder, f"{event_id}-{timestamp}-{label}-{score}.webp")
|
file = os.path.join(folder, f"{event_id}-{timestamp}-{label}-{score}.webp")
|
||||||
os.makedirs(folder, exist_ok=True)
|
os.makedirs(folder, exist_ok=True)
|
||||||
cv2.imwrite(file, frame)
|
write_image(file, frame)
|
||||||
trim_oldest_files(folder, max_files)
|
trim_oldest_files(folder, max_files)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ from frigate.data_processing.common.face.recognizer import (
|
|||||||
from frigate.types import TrackedObjectUpdateTypesEnum
|
from frigate.types import TrackedObjectUpdateTypesEnum
|
||||||
from frigate.util.builtin import EventsPerSecond, InferenceSpeed
|
from frigate.util.builtin import EventsPerSecond, InferenceSpeed
|
||||||
from frigate.util.file import trim_oldest_files
|
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 frigate.util.path import safe_join, sanitize_path_component
|
||||||
|
|
||||||
from ..types import DataProcessorMetrics
|
from ..types import DataProcessorMetrics
|
||||||
@@ -488,5 +488,5 @@ class FaceRealTimeProcessor(RealTimeProcessorApi):
|
|||||||
folder, f"{event_id}-{timestamp}-{sub_label}-{score}.webp"
|
folder, f"{event_id}-{timestamp}-{sub_label}-{score}.webp"
|
||||||
)
|
)
|
||||||
os.makedirs(folder, exist_ok=True)
|
os.makedirs(folder, exist_ok=True)
|
||||||
cv2.imwrite(file, frame)
|
write_image(file, frame)
|
||||||
trim_oldest_files(folder, self.config.face_recognition.save_attempts)
|
trim_oldest_files(folder, self.config.face_recognition.save_attempts)
|
||||||
|
|||||||
@@ -22,7 +22,12 @@ from frigate.ffmpeg_presets import (
|
|||||||
parse_preset_hardware_acceleration_encode,
|
parse_preset_hardware_acceleration_encode,
|
||||||
)
|
)
|
||||||
from frigate.models import Previews
|
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
|
from frigate.util.ownership import chown_to_runtime
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -373,7 +378,7 @@ class PreviewRecorder:
|
|||||||
)
|
)
|
||||||
cache_path = get_cache_image_name(self.camera_name, frame_time)
|
cache_path = get_cache_image_name(self.camera_name, frame_time)
|
||||||
|
|
||||||
if not cv2.imwrite(
|
if not write_image(
|
||||||
cache_path,
|
cache_path,
|
||||||
small_frame,
|
small_frame,
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -33,7 +33,11 @@ from frigate.models import ReviewSegment
|
|||||||
from frigate.review.severity import get_review_severity
|
from frigate.review.severity import get_review_severity
|
||||||
from frigate.review.types import SeverityEnum
|
from frigate.review.types import SeverityEnum
|
||||||
from frigate.track.object_processing import ManualEventState
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -147,7 +151,7 @@ class PendingReviewSegment:
|
|||||||
self.thumb_time = datetime.datetime.now().timestamp()
|
self.thumb_time = datetime.datetime.now().timestamp()
|
||||||
self.has_frame = True
|
self.has_frame = True
|
||||||
Path(self.frame_path).parent.mkdir(parents=True, exist_ok=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]
|
self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60]
|
||||||
):
|
):
|
||||||
logger.error("Failed to write review thumbnail to %s", self.frame_path)
|
logger.error("Failed to write review thumbnail to %s", self.frame_path)
|
||||||
@@ -162,7 +166,7 @@ class PendingReviewSegment:
|
|||||||
if self._frame is not None:
|
if self._frame is not None:
|
||||||
self.has_frame = True
|
self.has_frame = True
|
||||||
Path(self.frame_path).parent.mkdir(parents=True, exist_ok=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]
|
self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60]
|
||||||
):
|
):
|
||||||
logger.error("Failed to write review thumbnail to %s", self.frame_path)
|
logger.error("Failed to write review thumbnail to %s", self.frame_path)
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
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):
|
class TestSnapshotBytes(unittest.TestCase):
|
||||||
@@ -34,3 +37,44 @@ class TestSnapshotBytes(unittest.TestCase):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.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)
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import subprocess as sp
|
import subprocess as sp
|
||||||
import threading
|
import threading
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
from collections.abc import Sequence
|
||||||
from multiprocessing import resource_tracker as _mprt
|
from multiprocessing import resource_tracker as _mprt
|
||||||
from multiprocessing import shared_memory as _mpshm
|
from multiprocessing import shared_memory as _mpshm
|
||||||
from string import printable
|
from string import printable
|
||||||
@@ -272,6 +274,38 @@ def get_image_quality_params(ext: str, quality: int | None) -> list[int]:
|
|||||||
return []
|
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(
|
def relative_box_to_absolute(
|
||||||
frame_shape: tuple[int, ...], box: list[float] | tuple[float, ...] | None
|
frame_shape: tuple[int, ...], box: list[float] | tuple[float, ...] | None
|
||||||
) -> tuple[int, int, int, int] | None:
|
) -> tuple[int, int, int, int] | None:
|
||||||
|
|||||||
Reference in New Issue
Block a user