pipecountapp-dev / frontend /src /lib /preprocess.ts
Khunndev
Deploy offline-first PWA with in-browser ONNX inference
0e0cc3e
Raw History Blame
2.16 kB
import type { LetterboxMeta } from './types'
import { INFERENCE_SIZE } from './constants'
export function letterboxCanvas(
image: HTMLImageElement | HTMLCanvasElement,
size = INFERENCE_SIZE,
): { canvas: HTMLCanvasElement; meta: LetterboxMeta } {
const canvas = document.createElement('canvas')
canvas.width = size
canvas.height = size
const ctx = canvas.getContext('2d')
if (!ctx) {
throw new Error('Canvas 2D not available')
}
const srcW = 'naturalWidth' in image ? image.naturalWidth : image.width
const srcH = 'naturalHeight' in image ? image.naturalHeight : image.height
const scale = Math.min(size / srcW, size / srcH)
const newW = Math.round(srcW * scale)
const newH = Math.round(srcH * scale)
const padX = Math.floor((size - newW) / 2)
const padY = Math.floor((size - newH) / 2)
ctx.fillStyle = '#727272'
ctx.fillRect(0, 0, size, size)
ctx.drawImage(image, padX, padY, newW, newH)
return {
canvas,
meta: { scale, padX, padY, inputSize: size },
}
}
export function canvasToTensor(canvas: HTMLCanvasElement, size = INFERENCE_SIZE): Float32Array {
const ctx = canvas.getContext('2d')
if (!ctx) {
throw new Error('Canvas 2D not available')
}
const { data } = ctx.getImageData(0, 0, size, size)
const tensor = new Float32Array(3 * size * size)
let p = 0
for (let i = 0; i < data.length; i += 4) {
tensor[p++] = data[i] / 255
tensor[p++] = data[i + 1] / 255
tensor[p++] = data[i + 2] / 255
}
const chw = new Float32Array(3 * size * size)
const plane = size * size
for (let i = 0; i < plane; i++) {
chw[i] = tensor[i * 3]
chw[plane + i] = tensor[i * 3 + 1]
chw[2 * plane + i] = tensor[i * 3 + 2]
}
return chw
}
export function mapBoxToOriginal(
cx: number,
cy: number,
w: number,
h: number,
meta: LetterboxMeta,
): { xmin: number; ymin: number; xmax: number; ymax: number } {
const x1 = (cx - w / 2 - meta.padX) / meta.scale
const y1 = (cy - h / 2 - meta.padY) / meta.scale
const x2 = (cx + w / 2 - meta.padX) / meta.scale
const y2 = (cy + h / 2 - meta.padY) / meta.scale
return { xmin: x1, ymin: y1, xmax: x2, ymax: y2 }
}