mirror of
https://github.com/Project-Babble/ProjectBabble.git
synced 2026-11-27 20:36:24 -08:00
autocalibration
This commit is contained in:
1 parent
50d03cec35
commit
4067516016
3 files changed
+110
-156
No files matched your search
@@ -137,6 +137,18 @@ class BabbleProcessor:
|
||||
self.one_euro_filter = OneEuroFilter(
|
||||
noisy_point, min_cutoff=min_cutoff, beta=beta
|
||||
)
|
||||
# Persistent calibrator instance for continuous calibration
|
||||
self._calibrator = None
|
||||
|
||||
def process_output(self, output_array):
|
||||
# Called after model inference, applies calibration if enabled
|
||||
if self.settings.use_calibration:
|
||||
if self._calibrator is None or (hasattr(self._calibrator, 'calibrator') and self._calibrator.calibrator is not None and self._calibrator.calibrator.num_blendshapes != len(output_array)):
|
||||
from osc_calibrate_filter import cal
|
||||
self._calibrator = cal(self.settings)
|
||||
return self._calibrator.cal_osc(output_array)
|
||||
else:
|
||||
return output_array
|
||||
|
||||
def output_images_and_update(self, output_information: CamInfo):
|
||||
try:
|
||||
@@ -267,8 +279,11 @@ class BabbleProcessor:
|
||||
) # copy this frame to have a clean image for blink algo
|
||||
|
||||
run_model(self)
|
||||
if self.settings.use_calibration:
|
||||
self.output = cal.cal_osc(self, self.output)
|
||||
# Replace the old calibration logic with the new persistent calibrator usage
|
||||
# if self.settings.use_calibration:
|
||||
# self.output = cal(self.settings).cal_osc(self.output)
|
||||
# New code:
|
||||
self.output = self.process_output(self.output)
|
||||
# else:
|
||||
# pass
|
||||
# print(self.output)
|
||||
|
||||
@@ -33,8 +33,6 @@ class CameraWidget:
|
||||
self.gui_tracking_fps = f"-TRACKINGFPS{widget_id}-"
|
||||
self.gui_tracking_bps = f"-TRACKINGBPS{widget_id}-"
|
||||
self.gui_output_graph = f"-OUTPUTGRAPH{widget_id}-"
|
||||
self.gui_restart_calibration = f"-RESTARTCALIBRATION{widget_id}-"
|
||||
self.gui_stop_calibration = f"-STOPCALIBRATION{widget_id}-"
|
||||
self.gui_mode_readout = f"-APPMODE{widget_id}-"
|
||||
self.gui_roi_message = f"-ROIMESSAGE{widget_id}-"
|
||||
self.gui_vertical_flip = f"-VERTICALFLIP{widget_id}-"
|
||||
@@ -128,22 +126,6 @@ class CameraWidget:
|
||||
tooltip=lang._instance.get_string("camera.rotationTooltip"),
|
||||
),
|
||||
],
|
||||
[
|
||||
sg.Button(
|
||||
lang._instance.get_string("camera.startCalibration"),
|
||||
key=self.gui_restart_calibration,
|
||||
button_color=button_color,
|
||||
tooltip=lang._instance.get_string("camera.startCalibrationTooltip"),
|
||||
disabled=not self.settings_config.use_calibration,
|
||||
),
|
||||
sg.Button(
|
||||
lang._instance.get_string("camera.stopCalibration"),
|
||||
key=self.gui_stop_calibration,
|
||||
button_color=button_color,
|
||||
tooltip=lang._instance.get_string("camera.startCalibrationTooltip"),
|
||||
disabled=not self.settings_config.use_calibration,
|
||||
),
|
||||
],
|
||||
[
|
||||
sg.Checkbox(
|
||||
f'{lang._instance.get_string("camera.enableCalibration")}:',
|
||||
@@ -388,13 +370,14 @@ class CameraWidget:
|
||||
|
||||
if event == self.use_calibration:
|
||||
if self.settings_config.use_calibration == True:
|
||||
window[self.gui_restart_calibration].update(disabled=False)
|
||||
window[self.gui_stop_calibration].update(disabled=False)
|
||||
print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("info.enabled")}')
|
||||
# Optionally, trigger BlendShapeCalibrator reset/init here if needed
|
||||
playSound(os.path.join("Audio", "start.wav"))
|
||||
else:
|
||||
window[self.gui_restart_calibration].update(disabled=True)
|
||||
window[self.gui_stop_calibration].update(disabled=True)
|
||||
print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("info.disabled")}')
|
||||
# Stop calibration if it was running
|
||||
if self.babble_cnn.calibration_frame_counter is not None:
|
||||
self.babble_cnn.calibration_frame_counter = None
|
||||
|
||||
if event == "{}+UP".format(self.gui_roi_selection):
|
||||
# Event for mouse button up in ROI mode
|
||||
@@ -438,18 +421,15 @@ class CameraWidget:
|
||||
#print(self.camera_list)
|
||||
window[self.gui_camera_addr].update(values=self.camera_list,size=(20,0))
|
||||
|
||||
if event == self.gui_restart_calibration:
|
||||
|
||||
if (
|
||||
values[self.use_calibration] == True
|
||||
): # Don't start recording if the calibration filter is disabled.
|
||||
self.babble_cnn.calibration_frame_counter = 1500
|
||||
self.babble_cnn.calibration_frame_counter = None # Disable old frame counter logic
|
||||
# Optionally, trigger BlendShapeCalibrator reset/init here if needed
|
||||
playSound(os.path.join("Audio", "start.wav"))
|
||||
|
||||
if event == self.gui_stop_calibration:
|
||||
if (
|
||||
self.babble_cnn.calibration_frame_counter != None
|
||||
): # Only assign the variable if we are in calibration mode.
|
||||
self.babble_cnn.calibration_frame_counter = 0
|
||||
# Calibration is now controlled by the checkbox only
|
||||
|
||||
needs_roi_set = self.config.roi_window_h <= 0 or self.config.roi_window_w <= 0
|
||||
|
||||
|
||||
@@ -3,142 +3,101 @@ from math import log
|
||||
from enum import IntEnum
|
||||
from utils.misc_utils import playSound
|
||||
import os
|
||||
|
||||
from lang_manager import LocaleStringManager as lang
|
||||
|
||||
class CamId(IntEnum):
|
||||
CAM = 0
|
||||
SETTINGS = 1
|
||||
|
||||
class BlendShapeCalibrator:
|
||||
"""
|
||||
Continuous calibrator for blend shape model outputs.
|
||||
Tracks independent minimum and maximum values for each blend shape to robustly calibrate and normalize outputs.
|
||||
"""
|
||||
def __init__(self, num_blendshapes, alpha=0.1, beta=0.1, threshold_multiplier=2.0):
|
||||
self.num_blendshapes = num_blendshapes
|
||||
self.alpha = alpha
|
||||
self.beta = beta
|
||||
self.multiplier = threshold_multiplier
|
||||
self.initialized = False
|
||||
self.min = np.full(num_blendshapes, np.inf)
|
||||
self.max = np.full(num_blendshapes, -np.inf)
|
||||
self.mean = np.zeros(num_blendshapes)
|
||||
self.variance = np.zeros(num_blendshapes)
|
||||
self.threshold = np.zeros(num_blendshapes)
|
||||
self.confidence = np.ones(num_blendshapes)
|
||||
self.sample_count = 0
|
||||
|
||||
def update(self, input_array):
|
||||
input_array = np.asarray(input_array)
|
||||
if input_array.shape[0] != self.num_blendshapes:
|
||||
raise ValueError(f"Expected input of length {self.num_blendshapes}, got {input_array.shape[0]}")
|
||||
if not self.initialized:
|
||||
self.min = input_array.astype(float).copy()
|
||||
self.max = input_array.astype(float).copy()
|
||||
self.mean = input_array.astype(float).copy()
|
||||
self.variance = np.zeros(self.num_blendshapes)
|
||||
self.initialized = True
|
||||
# Update min and max independently
|
||||
self.min = np.minimum(self.min, input_array)
|
||||
self.max = np.maximum(self.max, input_array)
|
||||
# Optionally update mean/variance for confidence (legacy)
|
||||
diff = input_array - self.mean
|
||||
std = np.sqrt(self.variance)
|
||||
self.threshold = self.multiplier * std
|
||||
epsilon = 1e-6
|
||||
denom = self.threshold + epsilon
|
||||
confidence = np.exp(-np.abs(diff) / denom)
|
||||
# Only update mean if all (or most) blendshapes are below a low threshold (neutral)
|
||||
neutral_threshold = 0.15
|
||||
neutral_mask = np.abs(input_array) < neutral_threshold
|
||||
if np.sum(neutral_mask) >= int(0.8 * self.num_blendshapes):
|
||||
self.mean[neutral_mask] = self.alpha * input_array[neutral_mask] + (1 - self.alpha) * self.mean[neutral_mask]
|
||||
# Always update variance for tracking
|
||||
self.variance = self.beta * (diff ** 2) + (1 - self.beta) * self.variance
|
||||
self.confidence = confidence
|
||||
self.sample_count += 1
|
||||
return self.min, self.max, self.confidence
|
||||
|
||||
class cal:
|
||||
def __init__(self):
|
||||
self.calibration_frame_counter = None
|
||||
def __init__(self, settings=None):
|
||||
self.calibrator = None
|
||||
self.settings = settings
|
||||
self.calibrated_array = None
|
||||
self.raw_array = None
|
||||
self.confidence = None
|
||||
self.continuous_enabled = getattr(settings, 'continuous_calibration', True) if settings else True
|
||||
|
||||
def cal_osc(self, array):
|
||||
self.raw_array = array
|
||||
# print(self.calibration_frame_counter)
|
||||
if self.calibration_frame_counter == 0:
|
||||
if self.settings.calibration_mode == "Full":
|
||||
self.calibration_frame_counter = None
|
||||
values = np.array(self.val_list)
|
||||
|
||||
# Initialize the min_max_array with shape (2, num_outputs)
|
||||
num_outputs = values.shape[1]
|
||||
self.min_max_array = np.zeros((2, num_outputs))
|
||||
|
||||
# Iterate over each output index
|
||||
for i in range(num_outputs):
|
||||
# Calculate the lower and upper thresholds for the current index
|
||||
lower_threshold = np.percentile(values[:, i], 1)
|
||||
upper_threshold = np.percentile(values[:, i], 99)
|
||||
|
||||
# Filter out values within the thresholds for the current index
|
||||
filtered_values = values[
|
||||
(values[:, i] >= lower_threshold)
|
||||
& (values[:, i] <= upper_threshold),
|
||||
i,
|
||||
]
|
||||
|
||||
# Extract the minimum and maximum values for the current index
|
||||
min_value = np.min(filtered_values)
|
||||
max_value = np.max(filtered_values)
|
||||
|
||||
# Store the min and max values in the min_max_array
|
||||
self.min_max_array[0, i] = min_value
|
||||
self.min_max_array[1, i] = max_value
|
||||
self.settings.calib_array = np.array2string(
|
||||
self.min_max_array, separator=","
|
||||
)
|
||||
self.config_class.save()
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.info")}] Calibration completed.'
|
||||
)
|
||||
|
||||
playSound(os.path.join("Audio", "completed.wav"))
|
||||
|
||||
if self.settings.calibration_mode == "Neutral":
|
||||
self.min_max_array = np.fromstring(
|
||||
self.settings.calib_array.replace("[", "").replace("]", ""), sep=","
|
||||
)
|
||||
self.min_max_array = self.min_max_array.reshape((2, 45))
|
||||
print(f"minmax {self.min_max_array}")
|
||||
max_values = self.min_max_array[1]
|
||||
self.calibration_frame_counter = None
|
||||
values = np.array(self.val_list)
|
||||
# print(f'values: {values}')
|
||||
deadzone_value = self.settings.calib_deadzone
|
||||
# Initialize the min_max_array with shape (2, num_outputs)
|
||||
num_outputs = values.shape[1]
|
||||
self.min_max_array = np.zeros((2, num_outputs))
|
||||
lower_threshold = np.clip(
|
||||
[np.mean(values, axis=0) + deadzone_value], 0, 1
|
||||
).tolist()[0]
|
||||
upper_threshold = max_values.tolist()
|
||||
# upper_threshold = np.ones((1, num_outputs)) # We don't need to adjust the max values.
|
||||
# upper_threshold = self.min_max_array[1]
|
||||
print(lower_threshold)
|
||||
print(upper_threshold)
|
||||
self.min_max_array = np.append(lower_threshold, upper_threshold)
|
||||
# self.min_max_array = np.array([lower_threshold.tolist(), upper_threshold.tolist()])
|
||||
self.settings.calib_array = str([lower_threshold, upper_threshold])
|
||||
self.config_class.save()
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.info")}] Calibration completed.'
|
||||
)
|
||||
|
||||
elif self.calibration_frame_counter != None:
|
||||
self.val_list.append(array)
|
||||
self.calibration_frame_counter -= 1
|
||||
|
||||
self.raw_array = array
|
||||
if (
|
||||
self.settings.calib_array is not None
|
||||
and self.settings.use_calibration
|
||||
and self.settings.calibration_mode == "Full"
|
||||
):
|
||||
self.min_max_array = np.fromstring(
|
||||
self.settings.calib_array.replace("[", "").replace("]", ""), sep=","
|
||||
)
|
||||
self.min_max_array = self.min_max_array.reshape((2, 45))
|
||||
|
||||
calibrated_array = np.zeros_like(array)
|
||||
for i, value in enumerate(array):
|
||||
min_value = self.min_max_array[0, i]
|
||||
max_value = self.min_max_array[1, i]
|
||||
|
||||
if min_value == max_value:
|
||||
calibrated_value = (
|
||||
0.0 # Set to a default value (can be adjusted as needed)
|
||||
)
|
||||
else:
|
||||
calibrated_value = (value - min_value) / (max_value - min_value)
|
||||
|
||||
calibrated_array[i] = calibrated_value
|
||||
array = calibrated_array
|
||||
|
||||
if (
|
||||
self.settings.calib_array is not None
|
||||
and self.settings.use_calibration
|
||||
and self.settings.calibration_mode == "Neutral"
|
||||
):
|
||||
self.min_max_array = np.fromstring(
|
||||
self.settings.calib_array.replace("[", "").replace("]", ""), sep=","
|
||||
)
|
||||
self.min_max_array = self.min_max_array.reshape((2, 45))
|
||||
|
||||
calibrated_array = np.zeros_like(array)
|
||||
for i, value in enumerate(array):
|
||||
min_value = self.min_max_array[0, i]
|
||||
max_value = self.min_max_array[1, i]
|
||||
|
||||
calibrated_value = (value - min_value) / (max_value - min_value)
|
||||
|
||||
calibrated_array[i] = calibrated_value
|
||||
array = calibrated_array
|
||||
# array[4] = log((np.clip(array[4]*10,0,10))+1.0, 11) Log Filter: Move to filter system.
|
||||
array = np.clip(array, 0, 1)
|
||||
return array # Clamp outputs between 0-1
|
||||
if self.calibrator is None or (self.calibrator.num_blendshapes != len(array)):
|
||||
self.calibrator = BlendShapeCalibrator(num_blendshapes=len(array))
|
||||
if self.settings and hasattr(self.settings, 'continuous_calibration'):
|
||||
self.continuous_enabled = self.settings.continuous_calibration
|
||||
if self.continuous_enabled:
|
||||
min_vals, max_vals, confidence = self.calibrator.update(array)
|
||||
# Normalize using running min and max
|
||||
denom = (max_vals - min_vals)
|
||||
denom[denom == 0] = 1e-6 # Prevent division by zero
|
||||
calibrated = (array - min_vals) / denom
|
||||
self.calibrated_array = np.clip(calibrated, 0, 1)
|
||||
self.confidence = confidence
|
||||
# --- Begin patch: propagate calibration to config and widget ---
|
||||
if hasattr(self.settings, 'calib_array'):
|
||||
self.settings.calib_array = np.array2string(np.vstack((min_vals, max_vals)), separator=",")
|
||||
if hasattr(self.settings, 'main_config') and hasattr(self.settings.main_config, 'save'):
|
||||
self.settings.main_config.save()
|
||||
# --- End patch ---
|
||||
print(self.confidence)
|
||||
return self.calibrated_array
|
||||
else:
|
||||
self.calibrated_array = np.clip(array, 0, 1)
|
||||
self.confidence = np.ones_like(array)
|
||||
return self.calibrated_array
|
||||
|
||||
def get_outputs(self):
|
||||
return self.calibrated_array, self.raw_array
|
||||
return self.calibrated_array, self.raw_array, self.confidence
|
||||
|
||||
def get_outputs(self):
|
||||
return self.calibrated_array, self.raw_array, self.confidence
|
||||
Reference in new issue
Block a user