Repository navigation
Expand file tree
/
Copy pathbase_classifier.py
More file actions
73 lines (60 loc) · 2.54 KB
/
Copy pathbase_classifier.py
File metadata and controls
73 lines (60 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# BaseClassifier
# Copyright (C) 2024-2026 Collabora Ltd.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
from video_transform import VideoTransform
from backend import analytics
class BaseClassifier(VideoTransform):
"""
GStreamer element for image classification with a machine learning model.
"""
def __init__(self):
super().__init__()
self.logger.info("BaseClassifier initialized.")
def do_forward(self, frame):
"""
Runs classification inference and returns a label with a confidence score.
"""
if self.task_engine:
return self.task_engine.do_forward(frame)
self.logger.error("No model loaded in BaseClassifier.")
return None
def process_frames(self, frames, num_sources, fmt, target):
"""Classify the frame and attach the label as metadata."""
results = self.do_forward(frames)
if not results:
raise RuntimeError("classification returned no results")
self.do_decode(target, results)
def do_decode(self, buf, output):
"""
Decodes classification output and attaches metadata.
"""
if not isinstance(output, dict):
self.logger.error(
f"Unexpected classification output format: {type(output)}"
)
return
label = output.get("label")
score = output.get("score")
if label is None or score is None:
self.logger.warning("Classification result missing label or score.")
return
self.logger.info(f"Classified as {label} with confidence score {score:.2f}")
# Attach classification metadata
meta = analytics.add_relation_meta(buf)
if meta:
analytics.add_object(meta, label, 0, 0, self.width, self.height, score)
self.logger.info(f"Classified as {label} with score {score:.2f}")