Spaces:
Runtime error
Runtime error
File size: 2,181 Bytes
0e0cc3e 76b467a 0e0cc3e 76b467a 0e0cc3e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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)
// Write straight into CHW layout (R-plane | G-plane | B-plane) in a single
// pass. Previously this allocated a second 12.5MB Float32Array (at 1024) and
// transposed into it — pointless across 16-25 tiles per count.
const plane = size * size
const chw = new Float32Array(3 * plane)
for (let p = 0; p < plane; p++) {
const i = p * 4
chw[p] = data[i] / 255
chw[plane + p] = data[i + 1] / 255
chw[2 * plane + p] = data[i + 2] / 255
}
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 }
}
|