pipecountapp-dev / frontend /src /lib /imageEnhance.ts
Khunndev
Cursor
Improve detection accuracy with tiling defaults, 1024 model, and tuned thresholds.
2b21a73
Raw History Blame Contribute Delete
6.24 kB
export interface EnhanceOptions {
contrastStretch?: boolean
localContrast?: boolean
exposureNormalize?: boolean
sharpen?: boolean
}
const DEFAULT_OPTIONS: Required<EnhanceOptions> = {
contrastStretch: true,
localContrast: true,
exposureNormalize: true,
sharpen: true,
}
function luminance(r: number, g: number, b: number): number {
return 0.299 * r + 0.587 * g + 0.114 * b
}
function clamp(v: number): number {
return Math.max(0, Math.min(255, v))
}
function percentile(sorted: number[], p: number): number {
const idx = Math.floor((sorted.length - 1) * p)
return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]
}
function contrastStretchLuma(data: Uint8ClampedArray): void {
const lumas: number[] = []
for (let i = 0; i < data.length; i += 4) {
lumas.push(luminance(data[i], data[i + 1], data[i + 2]))
}
const sorted = [...lumas].sort((a, b) => a - b)
const lo = percentile(sorted, 0.02)
const hi = percentile(sorted, 0.98)
const span = Math.max(hi - lo, 1)
for (let i = 0; i < data.length; i += 4) {
const l = luminance(data[i], data[i + 1], data[i + 2])
const factor = clamp(((l - lo) / span) * 255) / Math.max(l, 1)
data[i] = clamp(data[i] * factor)
data[i + 1] = clamp(data[i + 1] * factor)
data[i + 2] = clamp(data[i + 2] * factor)
}
}
function exposureNormalize(data: Uint8ClampedArray): void {
let sum = 0
const n = data.length / 4
for (let i = 0; i < data.length; i += 4) {
sum += luminance(data[i], data[i + 1], data[i + 2])
}
const gain = Math.max(0.7, Math.min(1.4, (sum / n > 1 ? 128 / (sum / n) : 1)))
for (let i = 0; i < data.length; i += 4) {
data[i] = clamp(data[i] * gain)
data[i + 1] = clamp(data[i + 1] * gain)
data[i + 2] = clamp(data[i + 2] * gain)
}
}
function localContrast(data: Uint8ClampedArray, width: number, height: number): void {
const tilesX = 8
const tilesY = 8
const tileW = Math.ceil(width / tilesX)
const tileH = Math.ceil(height / tilesY)
for (let ty = 0; ty < tilesY; ty++) {
for (let tx = 0; tx < tilesX; tx++) {
const x0 = tx * tileW
const y0 = ty * tileH
const x1 = Math.min(width, x0 + tileW)
const y1 = Math.min(height, y0 + tileH)
const hist = new Array(256).fill(0)
let count = 0
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const i = (y * width + x) * 4
hist[Math.round(luminance(data[i], data[i + 1], data[i + 2]))]++
count++
}
}
const clip = Math.max(1, Math.floor((count / 256) * 2))
let excess = 0
for (let b = 0; b < 256; b++) {
if (hist[b] > clip) {
excess += hist[b] - clip
hist[b] = clip
}
}
const redist = Math.floor(excess / 256)
for (let b = 0; b < 256; b++) {
hist[b] += redist
}
const cdf = new Array(256).fill(0)
cdf[0] = hist[0]
for (let b = 1; b < 256; b++) {
cdf[b] = cdf[b - 1] + hist[b]
}
const cdfMin = cdf.find((v) => v > 0) ?? 0
const denom = Math.max(count - cdfMin, 1)
const lut = cdf.map((v) => clamp(((v - cdfMin) / denom) * 255))
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const i = (y * width + x) * 4
const l = Math.round(luminance(data[i], data[i + 1], data[i + 2]))
const factor = l > 0 ? lut[l] / l : 1
data[i] = clamp(data[i] * factor)
data[i + 1] = clamp(data[i + 1] * factor)
data[i + 2] = clamp(data[i + 2] * factor)
}
}
}
}
}
function unsharpMask(data: Uint8ClampedArray, width: number, height: number): void {
for (let c = 0; c < 3; c++) {
const src = new Float32Array(width * height)
for (let i = 0, p = 0; i < data.length; i += 4, p++) {
src[p] = data[i + c]
}
const blur = new Float32Array(src.length)
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let sum = 0
let n = 0
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
const nx = x + dx
const ny = y + dy
if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
sum += src[ny * width + nx]
n++
}
}
}
blur[y * width + x] = sum / n
}
}
for (let i = 0, p = 0; i < data.length; i += 4, p++) {
data[i + c] = clamp(src[p] + 0.35 * (src[p] - blur[p]))
}
}
}
export function enhanceImageData(imageData: ImageData, options: EnhanceOptions = {}): ImageData {
const opts = { ...DEFAULT_OPTIONS, ...options }
const out = new ImageData(
new Uint8ClampedArray(imageData.data),
imageData.width,
imageData.height,
)
if (opts.exposureNormalize) {
exposureNormalize(out.data)
}
if (opts.contrastStretch) {
contrastStretchLuma(out.data)
}
if (opts.localContrast) {
localContrast(out.data, out.width, out.height)
}
if (opts.sharpen) {
unsharpMask(out.data, out.width, out.height)
}
return out
}
export function enhanceImageElement(
image: HTMLImageElement | HTMLCanvasElement,
options?: EnhanceOptions,
): HTMLCanvasElement {
const srcW = 'naturalWidth' in image ? image.naturalWidth : image.width
const srcH = 'naturalHeight' in image ? image.naturalHeight : image.height
const canvas = document.createElement('canvas')
canvas.width = srcW
canvas.height = srcH
const ctx = canvas.getContext('2d')
if (!ctx) {
throw new Error('Canvas 2D not available')
}
ctx.drawImage(image, 0, 0)
const enhanced = enhanceImageData(ctx.getImageData(0, 0, srcW, srcH), options)
ctx.putImageData(enhanced, 0, 0)
return canvas
}
export function megapixels(width: number, height: number): number {
return (width * height) / 1_000_000
}
export function suggestTileGrid(width: number, height: number): number {
const mp = megapixels(width, height)
if (mp >= 6) {
return 5
}
if (mp >= 3) {
return 4
}
if (mp >= 1.2) {
return 3
}
return 2
}
export function shouldAutoTile(width: number, height: number): boolean {
return megapixels(width, height) >= 0.75 || Math.max(width, height) > 1400
}