From 0eba9068d79ff0bfe5c933bf3b10d0a6dafcc6ed Mon Sep 17 00:00:00 2001 From: Kvan7 <71402892+Kvan7@users.noreply.github.com> Date: Tue, 7 Jul 2026 12:49:28 -0500 Subject: [PATCH] Create scale.ts --- main/src/vision/opencv/cpp/scale.ts | 77 +++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 main/src/vision/opencv/cpp/scale.ts diff --git a/main/src/vision/opencv/cpp/scale.ts b/main/src/vision/opencv/cpp/scale.ts new file mode 100644 index 00000000..733a3c69 --- /dev/null +++ b/main/src/vision/opencv/cpp/scale.ts @@ -0,0 +1,77 @@ +import type * as cv from "@u4/opencv4nodejs"; +import { + createBgMask, + filterMultiple, + getTomeBg, + getTomePxSize, +} from "./utils"; +import { + FINE_TUNE_SCALES, + ULTRA_FINE_TUNE_SCALES, + USUAL_SCALES, +} from "../constants"; + +function bestScale( + img: cv.Mat, + needle: cv.Mat, + originalH: number, + scales: number[], + threshold: number, + startingScale = 1, +) { + let bestScale = startingScale; + let bestFound: cv.Rect[] = []; + for (const testScale of scales) { + const size = getTomePxSize(testScale, originalH); + + const scaledNeedle = needle.resize(size, size); + const mask = createBgMask(size); + const found = filterMultiple( + img, + scaledNeedle, + threshold, + size, + size, + mask, + ); + if (found.length > bestFound.length) { + bestScale = testScale; + bestFound = found; + } + } + return { scale: bestScale, rects: bestFound }; +} + +export function getImageScale(img: cv.Mat, original: { w: number; h: number }) { + const needle = getTomeBg(); + const { scale: firstScale, rects: firstRects } = bestScale( + img, + needle, + original.h, + USUAL_SCALES, + 0.65, + ); + console.log(`First scale guess: ${firstScale} [${firstRects.length}]`); + + const { scale: secondScale, rects: secondRects } = bestScale( + img, + needle, + original.h, + FINE_TUNE_SCALES.map((s) => firstScale + s / 100), + 0.75, + firstScale, + ); + console.log(`Second scale guess: ${secondScale} [${secondRects.length}]`); + + const { scale: thirdScale, rects: thirdRects } = bestScale( + img, + needle, + original.h, + ULTRA_FINE_TUNE_SCALES.map((s) => secondScale + s / 100), + 0.8, + secondScale, + ); + console.log(`Third scale guess: ${thirdScale} [${thirdRects.length}]`); + + return thirdScale; +}