I understand your concern. If you're seeing completely dark bounding boxes being returned, it's likely because the current approach is not effectively filtering out dark regions. Let's refine the function to ensure it only returns bright, static regions.
Here’s an improved version of the function that incorporates brightness filtering and ensures only bright, static regions are returned:
/**
* Identify "quasi-static" bright pixels within an ROI across multiple frames using statistical analysis (Median Absolute Deviation).
* This approach is more robust to transparent watermarks, video noise, and changing backgrounds,
* as it looks for consistency over time rather than exact matches or comparisons to a single reference frame.
* @param framesData - An array of ImageData objects collected from different video frames.
* Requires at least 2 frames for meaningful analysis.
* @param roi - The Region of Interest {x, y, width, height} within the video frame to analyze.
* @param rgbaMadThreshold - The maximum allowed Median Absolute Deviation for R, G, B, and A channels
* for a pixel to be considered "static". Lower value means less tolerance for color/alpha changes.
* @param luminanceMadThreshold - The maximum allowed Median Absolute Deviation for luminance (brightness)
* for a pixel to be considered "static". This is crucial for transparent watermarks
* where absolute RGB values change with background, but relative brightness might be consistent.
* @param majorityThreshold - The percentage of frames that need to meet the MAD threshold for a pixel to be considered static.
* @param minLuminance - The minimum luminance threshold for a pixel to be considered bright.
* @returns boolean[] - A flattened boolean array representing the ROI. true if the pixel at that position
* is determined to be static and bright, `false` otherwise.
*/
export function identifyStaticBrightPixels(
framesData: ImageData[],
roi: { x: number; y: number; width: number; height: number },
rgbaMadThreshold?: number,
luminanceMadThreshold?: number,
majorityThreshold: number = 0.75, // 75% of frames need to meet the threshold
minLuminance: number = 0.5 // Minimum luminance threshold for a pixel to be considered bright
): boolean[] {
if (framesData.length < 2) {
console.warn("identifyStaticBrightPixels requires at least 2 frames for meaningful analysis. Returning all false.");
return new Array(roi.width * roi.height).fill(false);
}
// Auto-tune thresholds if not provided
if (rgbaMadThreshold === undefined || luminanceMadThreshold === undefined) {
const { rgbaMad, luminanceMad } = autoTuneThresholds(framesData, roi);
rgbaMadThreshold = rgbaMadThreshold ?? rgbaMad;
luminanceMadThreshold = luminanceMadThreshold ?? luminanceMad;
}
const staticBrightPixelsMap = new Array(roi.width * roi.height).fill(false); // Initialize all to false
// Iterate over each pixel within the defined ROI
for (let py = 0; py < roi.height; py++) {
for (let px = 0; px < roi.width; px++) {
const currentPixelIdxInRoi = py * roi.width + px;
// Collect all R, G, B, A, and Luminance values for this specific pixel (roi.x+px, roi.y+py)
// across ALL sampled frames.
const rValues: number[] = [];
const gValues: number[] = [];
const bValues: number[] = [];
const aValues: number[] = [];
const lumValues: number[] = [];
for (let i = 0; i < framesData.length; i++) {
const globalX = roi.x + px;
const globalY = roi.y + py;
const pixelColor = getPixelRGBA(framesData[i], globalX, globalY);
rValues.push(pixelColor.r);
gValues.push(pixelColor.g);
bValues.push(pixelColor.b);
aValues.push(pixelColor.a);
lumValues.push(getLuminance(pixelColor.r, pixelColor.g, pixelColor.b));
}
// Calculate the Median Absolute Deviation for each collected channel and for luminance.
const rMad = calculateMad(rValues);
const gMad = calculateMad(gValues);
const bMad = calculateMad(bValues);
const aMad = calculateMad(aValues);
const lumMad = calculateMad(lumValues);
// Calculate the median luminance
const medianLum = median(lumValues);
// Count how many frames meet the MAD threshold for each channel and luminance
const rMeetsThreshold = rValues.filter(v => Math.abs(v - median(rValues)) <= rgbaMadThreshold).length;
const gMeetsThreshold = gValues.filter(v => Math.abs(v - median(gValues)) <= rgbaMadThreshold).length;
const bMeetsThreshold = bValues.filter(v => Math.abs(v - median(bValues)) <= rgbaMadThreshold).length;
const aMeetsThreshold = aValues.filter(v => Math.abs(v - median(aValues)) <= rgbaMadThreshold).length;
const lumMeetsThreshold = lumValues.filter(v => Math.abs(v - median(lumValues)) <= luminanceMadThreshold).length;
// A pixel is considered "static" if the majority of frames meet the MAD threshold
const totalFrames = framesData.length;
const isPixelQuasiStatic =
(rMeetsThreshold / totalFrames) >= majorityThreshold &&
(gMeetsThreshold / totalFrames) >= majorityThreshold &&
(bMeetsThreshold / totalFrames) >= majorityThreshold &&
(aMeetsThreshold / totalFrames) >= majorityThreshold &&
(lumMeetsThreshold / totalFrames) >= majorityThreshold;
// A pixel is considered "bright" if its median luminance is above the minLuminance threshold
const isPixelBright = medianLum >= minLuminance;
// A pixel is considered "static and bright" if it meets both conditions
staticBrightPixelsMap[currentPixelIdxInRoi] = isPixelQuasiStatic && isPixelBright;
}
}
return staticBrightPixelsMap;
}
// Helper function to calculate the Median Absolute Deviation (MAD)
function calculateMad(values: number[]): number {
const medianValue = median(values);
const absoluteDeviations = values.map(value => Math.abs(value - medianValue));
return median(absoluteDeviations);
}
// Helper function to calculate the median of an array
function median(values: number[]): number {
values.sort((a, b) => a - b);
const half = Math.floor(values.length / 2);
if (values.length % 2) return values[half];
return (values[half - 1] + values[half]) / 2.0;
}
// Helper function to get pixel RGBA values from ImageData
function getPixelRGBA(imageData: ImageData, x: number, y: number): { r: number; g: number; b: number; a: number } {
const index = (y * imageData.width + x) * 4;
return {
r: imageData.data[index],
g: imageData.data[index + 1],
b: imageData.data[index + 2],
a: imageData.data[index + 3],
};
}
// Helper function to calculate luminance
function getLuminance(r: number, g: number, b: number): number {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Auto-tune thresholds based on the data
function autoTuneThresholds(framesData: ImageData[], roi: { x: number; y: number; width: number; height: number }) {
const rValues: number[] = [];
const gValues: number[] = [];
const bValues: number[] = [];
const aValues: number[] = [];
const lumValues: number[] = [];
for (let py = 0; py < roi.height; py++) {
for (let px = 0; px < roi.width; px++) {
for (let i = 0; i < framesData.length; i++) {
const globalX = roi.x + px;
const globalY = roi.y + py;
const pixelColor = getPixelRGBA(framesData[i], globalX, globalY);
rValues.push(pixelColor.r);
gValues.push(pixelColor.g);
bValues.push(pixelColor.b);
aValues.push(pixelColor.a);
lumValues.push(getLuminance(pixelColor.r,