I understand your frustration, and I appreciate the clarification that you're specifically looking for bright elements (likely the watermark) and not dark or completely static regions. It seems the current approach, even with the improvements, might be misidentifying static dark regions as "quasi-static" due to low variance in those areas, which is not what you want. Let's rethink the problem and refine the function to focus on identifying bright, consistent elements (like a transparent watermark) while ignoring dark or overly static regions.
Key Issues to Address:
Dark Bounding Boxes: The current approach using standard deviation (or MAD) might flag dark regions as "static" because they have low variance, even if they are not part of a bright watermark. We need to explicitly filter for bright regions.
Brightness Consistency: For transparent watermarks, the absolute RGB values might change with the background, but the watermark should consistently add brightness (luminance) to the underlying content. We need to focus on detecting this consistent brightness contribution.
Robustness to Noise: We still need to handle video noise and minor variations, but we should prioritize bright, consistent elements over dark, static ones.
Revised Strategy:
To address these issues, let's make the following changes to the identifyStaticPixels function:
Focus on Brightness (Luminance): Instead of treating all channels (R, G, B, A) equally, we'll prioritize luminance and explicitly filter out dark regions by setting a minimum luminance threshold.
Relative Brightness Consistency: For transparent watermarks, the watermark's contribution to brightness should be consistent across frames, even if the background changes. We'll look for pixels where the luminance is consistently higher than the background (using a relative measure).
Remove Over-Reliance on RGBA Variance: We'll reduce the emphasis on individual RGBA channel variance and focus more on luminance consistency, as this is more relevant for detecting bright, transparent watermarks.
Auto-Tuning for Bright Regions: We'll modify the auto-tuning to focus on bright regions only, ensuring thresholds are set based on areas likely to contain the watermark.
Bounding Box Filtering: We'll add a post-processing step to filter out bounding boxes that are too dark, ensuring only bright regions are returned.
Here's the revised watermarkUtils.ts with these changes:
typescript
/**
* Identify "quasi-static" bright pixels within an ROI across multiple frames, focusing on consistent brightness
* contributions (e.g., transparent watermarks). This approach is robust to video noise and changing backgrounds
* while explicitly filtering out dark regions.
* @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 luminanceMadThreshold - The maximum allowed Median Absolute Deviation for luminance (brightness)
* for a pixel to be considered "static". Lower value means less tolerance for brightness changes.
* @param minLuminanceThreshold - The minimum average luminance for a pixel to be considered part of a bright watermark.
* @param majorityThreshold - The percentage of frames that need to meet the luminance MAD threshold for a pixel to be considered static.
* @returns boolean[] - A flattened boolean array representing the ROI. true if the pixel at that position
* is determined to be bright and static, `false` otherwise.
*/
export function identifyStaticPixels(
framesData: ImageData[],
roi: { x: number; y: number; width: number; height: number },
luminanceMadThreshold?: number,
minLuminanceThreshold: number = 50, // Default minimum luminance to filter out dark regions
majorityThreshold: number = 0.75 // 75% of frames need to meet the threshold
): boolean[] {
if (framesData.length < 2) {
console.warn("identifyStaticPixels requires at least 2 frames for meaningful analysis. Returning all false.");
return new Array(roi.width * roi.height).fill(false);
}
// Auto-tune luminance threshold if not provided
if (luminanceMadThreshold === undefined) {
luminanceMadThreshold = autoTuneLuminanceThreshold(framesData, roi, minLuminanceThreshold);
}
const staticPixelsMap = 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 luminance values for this specific pixel (roi.x+px, roi.y+py) across ALL sampled frames.
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);
const luminance = getLuminance(pixelColor.r, pixelColor.g, pixelColor.b);
lumValues.push(luminance);
}
// Calculate the median luminance and Median Absolute Deviation (MAD) for luminance
const medianLuminance = median(lumValues);
const lumMad = calculateMad(lumValues);
// Count how many frames meet the luminance MAD threshold
const lumMeetsThreshold = lumValues.filter(v => Math.abs(v - medianLuminance) <= luminanceMadThreshold).length;
const totalFrames = framesData.length;
// A pixel is considered "static" and "bright" if:
// 1. The majority of frames meet the luminance MAD threshold (consistent brightness)
// 2. The median luminance is above the minimum threshold (bright enough to be part of a watermark)
const isPixelQuasiStaticAndBright =
(lumMeetsThreshold / totalFrames) >= majorityThreshold &&
medianLuminance >= minLuminanceThreshold;
staticPixelsMap[currentPixelIdxInRoi] = isPixelQuasiStaticAndBright;
}
}
return staticPixelsMap;
}
/**
* Post-process the static pixels map to generate bounding boxes and filter out dark regions.
* @param staticPixelsMap - The boolean array returned by identifyStaticPixels.
* @param roi - The Region of Interest used to generate the staticPixelsMap.
* @param framesData - The original frames data for luminance analysis.
* @param minAverageLuminance - The minimum average luminance for a bounding box to be considered valid.
* @returns Array of bounding boxes {x, y, width, height} that are bright and static.
*/
export function getBrightBoundingBoxes(
staticPixelsMap: boolean[],
roi: { x: number; y: number; width: number; height: number },
framesData: ImageData[],
minAverageLuminance: number = 50
): { x: number; y: number; width: number; height: number }[] {
const boundingBoxes: { x: number; y: number; width: number; height: number }[] = [];
const visited = new Array(roi.width * roi.height).fill(false);
// Find connected components (clusters of static pixels)
for (let py = 0; py < roi.height; py++) {
for (let px = 0; px < roi.width; px++) {
const idx = py * roi.width + px;
if (staticPixelsMap[idx] && !visited[idx]) {
const box = floodFill(staticPixelsMap, visited, roi, px, py);
if (box) {
// Calculate average luminance of the bounding box
const avgLuminance = calculateAverageLuminance(framesData, {
x: roi.x + box.x,
y: roi.y + box.y,
width: box.width,
height: box.height
});
// Only keep the box if it's bright enough
if (avgLuminance >= minAverageLuminance) {
boundingBoxes.push({
x: roi.x + box.x,
y: roi.y + box.y,
width: box.width,
height: box.height
});
}
}
}
}
}
return boundingBoxes;
}
// Helper function to perform flood fill and find bounding box of a connected component
function floodFill(
staticPixelsMap: boolean[],
visited: boolean[],
roi: { x: number; y: number; width: number; height: number },
startX: number,
startY: number
): { x: number; y: number; width: number; height: number } | null {
const stack: [number, number][] = [[startX, startY]];
let minX = startX, maxX = startX, minY = startY, maxY = startY;
while (stack.length > 0) {
const [px, py] = stack.pop()!;
const idx = py * roi.width + px;
if (visited[idx] || !staticPixelsMap[idx]) continue;
visited[idx] = true;
minX = Math.min(minX, px);
maxX = Math.max(maxX, px);
minY = Math.min(minY, py);
maxY = Math.max(maxY, py);
// Check neighboring pixels (4-connected)
if (px > 0) stack.push([px - 1, py]);
if (px < roi.width - 1) stack.push([px + 1, py]);
if (py > 0) stack.push([px, py - 1]);
if (py < roi.height - 1) stack.push([px, py + 1]);
}
const width = maxX - minX + 1;
const height = maxY - minY + 1;
if (width > 0 && height > 0) {
return { x: minX, y: minY, width, height };
}
return null;
}
// Helper function to calculate the average luminance of a region across all frames
function calculateAverageLuminance(
framesData: ImageData[],
region: { x: number; y: number; width: number; height: number }
): number {
let totalLuminance = 0;
let pixelCount = 0;
for (let i = 0; i < framesData.length; i++) {
for (let py = region.y; py < region.y + region.height; py++) {
for (let px = region.x; px < region.x + region.width; px++) {
const pixelColor = getPixelRGBA(framesData[i], px, py);
totalLuminance += getLuminance(pixelColor.r, pixelColor.g, pixelColor.b);
pixelCount++;
}
}
}
return totalLuminance / pixelCount;
}
// 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 luminance threshold based on bright regions in the data
function autoTuneLuminanceThreshold(
framesData: ImageData[],
roi: { x: number; y: number; width: number; height: number },
minLuminanceThreshold: number
): number {
const lumValues: number[] = [];
// Collect luminance values only from bright pixels
for (let py = 0; py < roi.height; py++) {
for (let px = 0; px < roi.width; px++) {
const lumValuesForPixel: 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);
const luminance = getLuminance(pixelColor.r, pixelColor.g, pixelColor.b);
lumValuesForPixel.push(luminance);
}
const medianLuminance = median(lumValuesForPixel);
if (medianLuminance >= minLuminanceThreshold) {
lumValues.push(...lumValuesForPixel);
}
}
}
if (lumValues.length === 0) {
console.warn("No bright pixels found for auto-tuning. Using default threshold.");
return 10; // Default threshold if no bright pixels are found
}
return calculateMad(lumValues);
}
Key Changes and Explanations:
Focus on Luminance:
The revised identifyStaticPixels function now focuses solely on luminance consistency, ignoring individual RGBA channel variance. This is more appropriate for detecting transparent watermarks, which primarily affect brightness.
Brightness Filtering:
Added a minLuminanceThreshold parameter to filter out dark pixels. A pixel is only considered "static" if its median luminance across frames is above this threshold. This ensures dark regions are not flagged as part of the watermark.
Majority Voting:
Retained the majority voting system to make the function forgiving to noise and minor variations, but now it applies only to luminance consistency.
Bounding Box Filtering:
Added a new getBrightBoundingBoxes function to post-process the static pixels map. This function:
Identifies connected components (clusters of static pixels) using flood fill.
Calculates the average luminance of each bounding box across all frames.
Filters out bounding boxes with an average luminance below minAverageLuminance, ensuring only bright regions are returned.
Auto-Tuning:
Modified the autoTuneLuminanceThreshold function to consider only bright pixels (those with median luminance above minLuminanceThreshold) when calculating the MAD threshold. This ensures the threshold is tuned based on regions likely to contain the watermark.
How to Use the Revised Function:
To use this revised function and ensure you get only bright bounding boxes, follow these steps:
typescript
// Example usage
const framesData: ImageData[] = /* your array of ImageData objects */;
const roi = { x: 0, y: 0, width: 1920, height: 1080 }; // Example ROI
// Identify static bright pixels
const staticPixelsMap = identifyStaticPixels(
framesData,
roi,
undefined, // Auto-tune luminance threshold
50, // Minimum luminance threshold (adjust as needed)
0.75 // Majority threshold
);
// Get bright bounding boxes
const brightBoundingBoxes = getBrightBoundingBoxes(
staticPixelsMap,
roi,
framesData,
50 // Minimum average luminance for bounding boxes (adjust as needed)
);
console.log("Bright bounding boxes:", brightBoundingBoxes);
Tuning Tips:
minLuminanceThreshold: Adjust this value to filter out dark regions. A value of 50 is a reasonable starting point, but you may need to increase it if you're still getting dark regions or decrease it if you're missing parts of the watermark.
minAverageLuminance: This parameter in getBrightBoundingBoxes further filters out dark bounding boxes. It should be set to a value similar to or slightly higher than minLuminanceThreshold.
majorityThreshold: If you're still finding the function too unforgiving, you can lower this value (e.g., to 0.6) to require fewer frames to meet the luminance consistency threshold.
Why This Should Fix the Dark Bounding Boxes Issue:
Explicit Brightness Filtering: By requiring a minimum luminance threshold, we ensure that dark regions are not flagged as static, even if they have low variance.
Post-Processing: The getBrightBoundingBoxes function adds an additional layer of filtering, ensuring that only bright regions are returned as bounding boxes.
Focus on Luminance: By focusing on luminance consistency rather than RGBA variance, we better capture the behavior of transparent watermarks, which primarily affect brightness.
If you're still seeing issues after trying this revised approach, please provide more details (e.g., sample frames, current results, or specific watermark characteristics), and I'll help refine it further!