Initial orientator
This commit is contained in:
53
internal/detector/preprocess.go
Normal file
53
internal/detector/preprocess.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package detector
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
stddraw "image/draw"
|
||||
|
||||
xdraw "golang.org/x/image/draw"
|
||||
)
|
||||
|
||||
const ImgSize = 1200
|
||||
|
||||
// Preprocess implements the Python reference exactly:
|
||||
// 1. resize keeping aspect ratio to fit in 1200x1200 (Lanczos-equivalent CatmullRom)
|
||||
// 2. paste onto white 1200x1200 canvas at (0,0)
|
||||
// 3. normalize: (x/255 - 0.5) / 0.5
|
||||
// 4. HWC -> CHW with batch dim -> [1, 3, 1200, 1200]
|
||||
func Preprocess(img image.Image) []float32 {
|
||||
bounds := img.Bounds()
|
||||
w, h := bounds.Dx(), bounds.Dy()
|
||||
|
||||
scale := float64(ImgSize) / float64(w)
|
||||
if s := float64(ImgSize) / float64(h); s < scale {
|
||||
scale = s
|
||||
}
|
||||
newW := int(float64(w) * scale)
|
||||
newH := int(float64(h) * scale)
|
||||
if newW < 1 {
|
||||
newW = 1
|
||||
}
|
||||
if newH < 1 {
|
||||
newH = 1
|
||||
}
|
||||
|
||||
canvas := image.NewRGBA(image.Rect(0, 0, ImgSize, ImgSize))
|
||||
stddraw.Draw(canvas, canvas.Bounds(), &image.Uniform{C: color.RGBA{255, 255, 255, 255}}, image.Point{}, stddraw.Src)
|
||||
xdraw.CatmullRom.Scale(canvas, image.Rect(0, 0, newW, newH), img, bounds, xdraw.Over, nil)
|
||||
|
||||
out := make([]float32, 3*ImgSize*ImgSize)
|
||||
plane := ImgSize * ImgSize
|
||||
pix := canvas.Pix
|
||||
for y := 0; y < ImgSize; y++ {
|
||||
row := y * canvas.Stride
|
||||
base := y * ImgSize
|
||||
for x := 0; x < ImgSize; x++ {
|
||||
i := row + x*4
|
||||
out[base+x] = float32(pix[i+0])/127.5 - 1
|
||||
out[plane+base+x] = float32(pix[i+1])/127.5 - 1
|
||||
out[2*plane+base+x] = float32(pix[i+2])/127.5 - 1
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user