Khunndev commited on
Commit
2eba938
·
1 Parent(s): 0e0cc3e

Support image enhancement, outlier filtering, and adaptive multi-tile detection

Browse files

- Add UI controls for image enhancement (contrast + sharpen) and outlier filtering
- Replace fixed 4-tile logic with dynamic grid sizing based on image megapixels
- Update model selection to prefer 1024px for production photos, 640px only for small previews
- Sync Python test script with frontend preprocessing and tiling behavior

frontend/package-lock.json.committed ADDED
The diff for this file is too large to render. See raw diff
 
frontend/src/App.tsx CHANGED
@@ -20,6 +20,8 @@ export default function App() {
20
  const [busy, setBusy] = useState(false)
21
  const [modelReady, setModelReady] = useState(false)
22
  const [useTiling, setUseTiling] = useState(false)
 
 
23
  const [exportCanvas, setExportCanvas] = useState<HTMLCanvasElement | null>(null)
24
  const fileRef = useRef<HTMLInputElement>(null)
25
  const cameraRef = useRef<HTMLInputElement>(null)
@@ -51,7 +53,13 @@ export default function App() {
51
  setBusy(true)
52
  setStatus(t(lang, 'processing'))
53
  try {
54
- const dets = await runDetection(image, { useTiling, onProgress: setStatus })
 
 
 
 
 
 
55
  const clustered = assignDiameterGroups(dets, groupCount, lang)
56
  setDetections(clustered.detections)
57
  setGroups(clustered.groups)
@@ -193,10 +201,18 @@ export default function App() {
193
  Apply
194
  </button>
195
  </div>
 
 
 
 
196
  <label className="flex items-center gap-2 text-sm text-slate-300">
197
  <input type="checkbox" checked={useTiling} onChange={(e) => setUseTiling(e.target.checked)} />
198
  {t(lang, 'highAccuracy')}
199
  </label>
 
 
 
 
200
  </div>
201
 
202
  {groups.length > 0 && (
 
20
  const [busy, setBusy] = useState(false)
21
  const [modelReady, setModelReady] = useState(false)
22
  const [useTiling, setUseTiling] = useState(false)
23
+ const [enhanceImage, setEnhanceImage] = useState(true)
24
+ const [filterOutliers, setFilterOutliers] = useState(false)
25
  const [exportCanvas, setExportCanvas] = useState<HTMLCanvasElement | null>(null)
26
  const fileRef = useRef<HTMLInputElement>(null)
27
  const cameraRef = useRef<HTMLInputElement>(null)
 
53
  setBusy(true)
54
  setStatus(t(lang, 'processing'))
55
  try {
56
+ const dets = await runDetection(image, {
57
+ useTiling,
58
+ enhanceImage,
59
+ filterOutliers,
60
+ autoTile: !useTiling,
61
+ onProgress: setStatus,
62
+ })
63
  const clustered = assignDiameterGroups(dets, groupCount, lang)
64
  setDetections(clustered.detections)
65
  setGroups(clustered.groups)
 
201
  Apply
202
  </button>
203
  </div>
204
+ <label className="flex items-center gap-2 text-sm text-slate-300">
205
+ <input type="checkbox" checked={enhanceImage} onChange={(e) => setEnhanceImage(e.target.checked)} />
206
+ {t(lang, 'enhanceImage')}
207
+ </label>
208
  <label className="flex items-center gap-2 text-sm text-slate-300">
209
  <input type="checkbox" checked={useTiling} onChange={(e) => setUseTiling(e.target.checked)} />
210
  {t(lang, 'highAccuracy')}
211
  </label>
212
+ <label className="flex items-center gap-2 text-sm text-slate-300">
213
+ <input type="checkbox" checked={filterOutliers} onChange={(e) => setFilterOutliers(e.target.checked)} />
214
+ {t(lang, 'filterOutliers')}
215
+ </label>
216
  </div>
217
 
218
  {groups.length > 0 && (
frontend/src/lib/i18n.ts CHANGED
@@ -22,7 +22,8 @@ const messages = {
22
  exportPng: 'Export PNG',
23
  exportJson: 'Export JSON',
24
  exportCsv: 'Export CSV',
25
- highAccuracy: 'High accuracy (4-tile)',
 
26
  filterOutliers: 'Filter outliers',
27
  mismatch: 'Mismatch',
28
  selectGroup: 'Select target group',
@@ -50,7 +51,8 @@ const messages = {
50
  exportPng: 'ส่งออก PNG',
51
  exportJson: 'ส่งออก JSON',
52
  exportCsv: 'ส่งออก CSV',
53
- highAccuracy: 'ความแม่นยำสูง (4 ส่วน)',
 
54
  filterOutliers: 'กรองค่าผิดปกติ',
55
  mismatch: 'ไม่ตรง',
56
  selectGroup: 'เลือกกลุ่มเป้าหมาย',
 
22
  exportPng: 'Export PNG',
23
  exportJson: 'Export JSON',
24
  exportCsv: 'Export CSV',
25
+ highAccuracy: 'High accuracy (multi-tile)',
26
+ enhanceImage: 'Enhance image (contrast + sharpen)',
27
  filterOutliers: 'Filter outliers',
28
  mismatch: 'Mismatch',
29
  selectGroup: 'Select target group',
 
51
  exportPng: 'ส่งออก PNG',
52
  exportJson: 'ส่งออก JSON',
53
  exportCsv: 'ส่งออก CSV',
54
+ highAccuracy: 'ความแม่นยำสูง (หลายส่วน)',
55
+ enhanceImage: 'ปรับภาพ (คอนทราสต์ + ความคม)',
56
  filterOutliers: 'กรองค่าผิดปกติ',
57
  mismatch: 'ไม่ตรง',
58
  selectGroup: 'เลือกกลุ่มเป้าหมาย',
frontend/src/lib/imageEnhance.ts ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface EnhanceOptions {
2
+ contrastStretch?: boolean
3
+ localContrast?: boolean
4
+ exposureNormalize?: boolean
5
+ sharpen?: boolean
6
+ }
7
+
8
+ const DEFAULT_OPTIONS: Required<EnhanceOptions> = {
9
+ contrastStretch: true,
10
+ localContrast: true,
11
+ exposureNormalize: true,
12
+ sharpen: true,
13
+ }
14
+
15
+ function luminance(r: number, g: number, b: number): number {
16
+ return 0.299 * r + 0.587 * g + 0.114 * b
17
+ }
18
+
19
+ function clamp(v: number): number {
20
+ return Math.max(0, Math.min(255, v))
21
+ }
22
+
23
+ function percentile(sorted: number[], p: number): number {
24
+ const idx = Math.floor((sorted.length - 1) * p)
25
+ return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]
26
+ }
27
+
28
+ function contrastStretchLuma(data: Uint8ClampedArray): void {
29
+ const lumas: number[] = []
30
+ for (let i = 0; i < data.length; i += 4) {
31
+ lumas.push(luminance(data[i], data[i + 1], data[i + 2]))
32
+ }
33
+ const sorted = [...lumas].sort((a, b) => a - b)
34
+ const lo = percentile(sorted, 0.02)
35
+ const hi = percentile(sorted, 0.98)
36
+ const span = Math.max(hi - lo, 1)
37
+
38
+ for (let i = 0; i < data.length; i += 4) {
39
+ const l = luminance(data[i], data[i + 1], data[i + 2])
40
+ const factor = clamp(((l - lo) / span) * 255) / Math.max(l, 1)
41
+ data[i] = clamp(data[i] * factor)
42
+ data[i + 1] = clamp(data[i + 1] * factor)
43
+ data[i + 2] = clamp(data[i + 2] * factor)
44
+ }
45
+ }
46
+
47
+ function exposureNormalize(data: Uint8ClampedArray): void {
48
+ let sum = 0
49
+ const n = data.length / 4
50
+ for (let i = 0; i < data.length; i += 4) {
51
+ sum += luminance(data[i], data[i + 1], data[i + 2])
52
+ }
53
+ const gain = Math.max(0.7, Math.min(1.4, (sum / n > 1 ? 128 / (sum / n) : 1)))
54
+ for (let i = 0; i < data.length; i += 4) {
55
+ data[i] = clamp(data[i] * gain)
56
+ data[i + 1] = clamp(data[i + 1] * gain)
57
+ data[i + 2] = clamp(data[i + 2] * gain)
58
+ }
59
+ }
60
+
61
+ function localContrast(data: Uint8ClampedArray, width: number, height: number): void {
62
+ const tilesX = 8
63
+ const tilesY = 8
64
+ const tileW = Math.ceil(width / tilesX)
65
+ const tileH = Math.ceil(height / tilesY)
66
+
67
+ for (let ty = 0; ty < tilesY; ty++) {
68
+ for (let tx = 0; tx < tilesX; tx++) {
69
+ const x0 = tx * tileW
70
+ const y0 = ty * tileH
71
+ const x1 = Math.min(width, x0 + tileW)
72
+ const y1 = Math.min(height, y0 + tileH)
73
+ const hist = new Array(256).fill(0)
74
+ let count = 0
75
+
76
+ for (let y = y0; y < y1; y++) {
77
+ for (let x = x0; x < x1; x++) {
78
+ const i = (y * width + x) * 4
79
+ hist[Math.round(luminance(data[i], data[i + 1], data[i + 2]))]++
80
+ count++
81
+ }
82
+ }
83
+
84
+ const clip = Math.max(1, Math.floor((count / 256) * 2))
85
+ let excess = 0
86
+ for (let b = 0; b < 256; b++) {
87
+ if (hist[b] > clip) {
88
+ excess += hist[b] - clip
89
+ hist[b] = clip
90
+ }
91
+ }
92
+ const redist = Math.floor(excess / 256)
93
+ for (let b = 0; b < 256; b++) {
94
+ hist[b] += redist
95
+ }
96
+
97
+ const cdf = new Array(256).fill(0)
98
+ cdf[0] = hist[0]
99
+ for (let b = 1; b < 256; b++) {
100
+ cdf[b] = cdf[b - 1] + hist[b]
101
+ }
102
+ const cdfMin = cdf.find((v) => v > 0) ?? 0
103
+ const denom = Math.max(count - cdfMin, 1)
104
+ const lut = cdf.map((v) => clamp(((v - cdfMin) / denom) * 255))
105
+
106
+ for (let y = y0; y < y1; y++) {
107
+ for (let x = x0; x < x1; x++) {
108
+ const i = (y * width + x) * 4
109
+ const l = Math.round(luminance(data[i], data[i + 1], data[i + 2]))
110
+ const factor = l > 0 ? lut[l] / l : 1
111
+ data[i] = clamp(data[i] * factor)
112
+ data[i + 1] = clamp(data[i + 1] * factor)
113
+ data[i + 2] = clamp(data[i + 2] * factor)
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ function unsharpMask(data: Uint8ClampedArray, width: number, height: number): void {
121
+ for (let c = 0; c < 3; c++) {
122
+ const src = new Float32Array(width * height)
123
+ for (let i = 0, p = 0; i < data.length; i += 4, p++) {
124
+ src[p] = data[i + c]
125
+ }
126
+ const blur = new Float32Array(src.length)
127
+ for (let y = 0; y < height; y++) {
128
+ for (let x = 0; x < width; x++) {
129
+ let sum = 0
130
+ let n = 0
131
+ for (let dy = -1; dy <= 1; dy++) {
132
+ for (let dx = -1; dx <= 1; dx++) {
133
+ const nx = x + dx
134
+ const ny = y + dy
135
+ if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
136
+ sum += src[ny * width + nx]
137
+ n++
138
+ }
139
+ }
140
+ }
141
+ blur[y * width + x] = sum / n
142
+ }
143
+ }
144
+ for (let i = 0, p = 0; i < data.length; i += 4, p++) {
145
+ data[i + c] = clamp(src[p] + 0.35 * (src[p] - blur[p]))
146
+ }
147
+ }
148
+ }
149
+
150
+ export function enhanceImageData(imageData: ImageData, options: EnhanceOptions = {}): ImageData {
151
+ const opts = { ...DEFAULT_OPTIONS, ...options }
152
+ const out = new ImageData(
153
+ new Uint8ClampedArray(imageData.data),
154
+ imageData.width,
155
+ imageData.height,
156
+ )
157
+
158
+ if (opts.exposureNormalize) {
159
+ exposureNormalize(out.data)
160
+ }
161
+ if (opts.contrastStretch) {
162
+ contrastStretchLuma(out.data)
163
+ }
164
+ if (opts.localContrast) {
165
+ localContrast(out.data, out.width, out.height)
166
+ }
167
+ if (opts.sharpen) {
168
+ unsharpMask(out.data, out.width, out.height)
169
+ }
170
+ return out
171
+ }
172
+
173
+ export function enhanceImageElement(
174
+ image: HTMLImageElement | HTMLCanvasElement,
175
+ options?: EnhanceOptions,
176
+ ): HTMLCanvasElement {
177
+ const srcW = 'naturalWidth' in image ? image.naturalWidth : image.width
178
+ const srcH = 'naturalHeight' in image ? image.naturalHeight : image.height
179
+ const canvas = document.createElement('canvas')
180
+ canvas.width = srcW
181
+ canvas.height = srcH
182
+ const ctx = canvas.getContext('2d')
183
+ if (!ctx) {
184
+ throw new Error('Canvas 2D not available')
185
+ }
186
+ ctx.drawImage(image, 0, 0)
187
+ const enhanced = enhanceImageData(ctx.getImageData(0, 0, srcW, srcH), options)
188
+ ctx.putImageData(enhanced, 0, 0)
189
+ return canvas
190
+ }
191
+
192
+ export function megapixels(width: number, height: number): number {
193
+ return (width * height) / 1_000_000
194
+ }
195
+
196
+ export function suggestTileGrid(width: number, height: number): number {
197
+ const mp = megapixels(width, height)
198
+ if (mp >= 8) {
199
+ return 5
200
+ }
201
+ if (mp >= 4) {
202
+ return 4
203
+ }
204
+ if (mp >= 2) {
205
+ return 3
206
+ }
207
+ return 2
208
+ }
209
+
210
+ export function shouldAutoTile(width: number, height: number): boolean {
211
+ return megapixels(width, height) >= 2 || Math.max(width, height) > 2000
212
+ }
frontend/src/lib/inference.ts CHANGED
@@ -1,5 +1,11 @@
1
  import * as ort from 'onnxruntime-web'
2
  import { CONFIDENCE_THRESHOLD, IOU_THRESHOLD, MAX_DETECTIONS, MODEL_640_URL, MODEL_URL } from './constants'
 
 
 
 
 
 
3
  import { selectModelForImage } from './modelSelect'
4
  import { filterOutliers, nonMaxSuppression } from './nms'
5
  import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess'
@@ -50,6 +56,49 @@ export async function loadModel(onProgress?: (msg: string) => void): Promise<voi
50
  onProgress?.(`Models ready (${activeBackend})`)
51
  }
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  export function decodeOutput(
54
  output: Float32Array,
55
  meta: LetterboxMeta,
@@ -98,97 +147,104 @@ export function decodeOutput(
98
 
99
  export async function runDetection(
100
  image: HTMLImageElement,
101
- options?: { useTiling?: boolean; filterOutliers?: boolean; onProgress?: (msg: string) => void },
 
 
 
 
 
 
 
102
  ): Promise<Detection[]> {
103
  await loadModel(options?.onProgress)
104
- const { modelUrl, inferenceSize } = selectModelForImage(
105
- image.naturalWidth,
106
- image.naturalHeight,
107
- )
108
  const session = await getSession(modelUrl)
109
  const start = performance.now()
110
 
111
- if (options?.useTiling) {
112
- return runTiledDetection(image, session, inferenceSize, options)
 
 
 
 
 
 
 
113
  }
114
 
115
- const { canvas, meta } = letterboxCanvas(image, inferenceSize)
116
- const tensor = canvasToTensor(canvas, inferenceSize)
117
- const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize])
118
- const results = await session.run({ images: input })
119
- const output = results.output.data as Float32Array
120
- const detections = decodeOutput(
121
- output,
122
- meta,
123
- image.naturalWidth,
124
- image.naturalHeight,
125
- CONFIDENCE_THRESHOLD,
126
  options?.filterOutliers ?? false,
127
  )
128
- options?.onProgress?.(`Detected ${detections.length} pipes in ${Math.round(performance.now() - start)}ms`)
129
- return detections
130
  }
131
 
132
  async function runTiledDetection(
133
  image: HTMLImageElement,
134
  session: ort.InferenceSession,
135
  inferenceSize: number,
136
- options?: { filterOutliers?: boolean; onProgress?: (msg: string) => void },
 
 
 
 
 
137
  ): Promise<Detection[]> {
138
  const onProgress = options?.onProgress
139
  const w = image.naturalWidth
140
  const h = image.naturalHeight
141
- const midX = w / 2
142
- const midY = h / 2
143
- const overlap = 0.1
144
- const dx = midX * overlap
145
- const dy = midY * overlap
146
- const tiles = [
147
- { x: 0, y: 0, w: midX + dx, h: midY + dy },
148
- { x: midX - dx, y: 0, w: w - midX + dx, h: midY + dy },
149
- { x: 0, y: midY - dy, w: midX + dx, h: h - midY + dy },
150
- { x: midX - dx, y: midY - dy, w: w - midX + dx, h: h - midY + dy },
151
- ]
152
-
153
  const all: Detection[] = []
154
- for (let i = 0; i < tiles.length; i++) {
155
- onProgress?.(`Tiling ${i + 1}/4...`)
156
- const tile = tiles[i]
157
- const tileCanvas = document.createElement('canvas')
158
- tileCanvas.width = tile.w
159
- tileCanvas.height = tile.h
160
- const ctx = tileCanvas.getContext('2d')!
161
- ctx.drawImage(image, tile.x, tile.y, tile.w, tile.h, 0, 0, tile.w, tile.h)
162
-
163
- const img = new Image()
164
- img.src = tileCanvas.toDataURL()
165
- await new Promise<void>((resolve) => {
166
- img.onload = () => resolve()
167
- })
168
 
169
- const { canvas, meta } = letterboxCanvas(img, inferenceSize)
170
- const tensor = canvasToTensor(canvas, inferenceSize)
171
- const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize])
172
- const results = await session.run({ images: input })
173
- const output = results.output.data as Float32Array
174
- const dets = decodeOutput(
175
- output,
176
- meta,
177
- tile.w,
178
- tile.h,
179
- CONFIDENCE_THRESHOLD,
180
- options?.filterOutliers ?? false,
181
- )
182
- for (const d of dets) {
183
- all.push({
184
- ...d,
185
- xmin: d.xmin + tile.x,
186
- ymin: d.ymin + tile.y,
187
- xmax: d.xmax + tile.x,
188
- ymax: d.ymax + tile.y,
189
- id: `tile-${i}-${d.id}`,
190
- groupId: 0,
191
- })
 
 
 
 
 
 
 
 
 
 
 
 
192
  }
193
  }
194
 
 
1
  import * as ort from 'onnxruntime-web'
2
  import { CONFIDENCE_THRESHOLD, IOU_THRESHOLD, MAX_DETECTIONS, MODEL_640_URL, MODEL_URL } from './constants'
3
+ import {
4
+ enhanceImageElement,
5
+ shouldAutoTile,
6
+ suggestTileGrid,
7
+ type EnhanceOptions,
8
+ } from './imageEnhance'
9
  import { selectModelForImage } from './modelSelect'
10
  import { filterOutliers, nonMaxSuppression } from './nms'
11
  import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess'
 
56
  onProgress?.(`Models ready (${activeBackend})`)
57
  }
58
 
59
+ function prepareSource(
60
+ image: HTMLImageElement,
61
+ enhance: boolean,
62
+ enhanceOptions?: EnhanceOptions,
63
+ ): HTMLCanvasElement | HTMLImageElement {
64
+ if (!enhance) {
65
+ return image
66
+ }
67
+ return enhanceImageElement(image, enhanceOptions)
68
+ }
69
+
70
+ async function inferCanvas(
71
+ source: HTMLCanvasElement | HTMLImageElement,
72
+ session: ort.InferenceSession,
73
+ inferenceSize: number,
74
+ offsetX: number,
75
+ offsetY: number,
76
+ regionW: number,
77
+ regionH: number,
78
+ filterOutliersFlag: boolean,
79
+ ): Promise<Detection[]> {
80
+ const { canvas, meta } = letterboxCanvas(source, inferenceSize)
81
+ const tensor = canvasToTensor(canvas, inferenceSize)
82
+ const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize])
83
+ const results = await session.run({ images: input })
84
+ const output = results.output.data as Float32Array
85
+ const dets = decodeOutput(
86
+ output,
87
+ meta,
88
+ regionW,
89
+ regionH,
90
+ CONFIDENCE_THRESHOLD,
91
+ filterOutliersFlag,
92
+ )
93
+ return dets.map((d) => ({
94
+ ...d,
95
+ xmin: d.xmin + offsetX,
96
+ ymin: d.ymin + offsetY,
97
+ xmax: d.xmax + offsetX,
98
+ ymax: d.ymax + offsetY,
99
+ }))
100
+ }
101
+
102
  export function decodeOutput(
103
  output: Float32Array,
104
  meta: LetterboxMeta,
 
147
 
148
  export async function runDetection(
149
  image: HTMLImageElement,
150
+ options?: {
151
+ useTiling?: boolean
152
+ autoTile?: boolean
153
+ enhanceImage?: boolean
154
+ enhanceOptions?: EnhanceOptions
155
+ filterOutliers?: boolean
156
+ onProgress?: (msg: string) => void
157
+ },
158
  ): Promise<Detection[]> {
159
  await loadModel(options?.onProgress)
160
+ const w = image.naturalWidth
161
+ const h = image.naturalHeight
162
+ const { modelUrl, inferenceSize } = selectModelForImage(w, h)
 
163
  const session = await getSession(modelUrl)
164
  const start = performance.now()
165
 
166
+ const enhance = options?.enhanceImage ?? true
167
+ const useTiling =
168
+ options?.useTiling ?? (options?.autoTile !== false && shouldAutoTile(w, h))
169
+
170
+ if (useTiling) {
171
+ return runTiledDetection(image, session, inferenceSize, {
172
+ ...options,
173
+ enhanceImage: enhance,
174
+ })
175
  }
176
 
177
+ options?.onProgress?.(enhance ? 'Enhancing image...' : 'Preparing image...')
178
+ const source = prepareSource(image, enhance, options?.enhanceOptions)
179
+ const dets = await inferCanvas(
180
+ source,
181
+ session,
182
+ inferenceSize,
183
+ 0,
184
+ 0,
185
+ w,
186
+ h,
 
187
  options?.filterOutliers ?? false,
188
  )
189
+ options?.onProgress?.(`Detected ${dets.length} pipes in ${Math.round(performance.now() - start)}ms`)
190
+ return dets
191
  }
192
 
193
  async function runTiledDetection(
194
  image: HTMLImageElement,
195
  session: ort.InferenceSession,
196
  inferenceSize: number,
197
+ options?: {
198
+ enhanceImage?: boolean
199
+ enhanceOptions?: EnhanceOptions
200
+ filterOutliers?: boolean
201
+ onProgress?: (msg: string) => void
202
+ },
203
  ): Promise<Detection[]> {
204
  const onProgress = options?.onProgress
205
  const w = image.naturalWidth
206
  const h = image.naturalHeight
207
+ const grid = suggestTileGrid(w, h)
208
+ const overlap = 0.2
209
+ const tileW = w / grid
210
+ const tileH = h / grid
 
 
 
 
 
 
 
 
211
  const all: Detection[] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ onProgress?.(`Enhancing + tiling ${grid}x${grid}...`)
214
+ const enhanced = (options?.enhanceImage ?? true)
215
+ ? enhanceImageElement(image, options?.enhanceOptions)
216
+ : image
217
+
218
+ let tileIndex = 0
219
+ const totalTiles = grid * grid
220
+ for (let gy = 0; gy < grid; gy++) {
221
+ for (let gx = 0; gx < grid; gx++) {
222
+ tileIndex++
223
+ onProgress?.(`Tile ${tileIndex}/${totalTiles}...`)
224
+ const x1 = Math.max(0, gx * tileW - (tileW * overlap * (gx > 0 ? 1 : 0)))
225
+ const y1 = Math.max(0, gy * tileH - (tileH * overlap * (gy > 0 ? 1 : 0)))
226
+ const x2 = Math.min(w, (gx + 1) * tileW + (tileW * overlap * (gx < grid - 1 ? 1 : 0)))
227
+ const y2 = Math.min(h, (gy + 1) * tileH + (tileH * overlap * (gy < grid - 1 ? 1 : 0)))
228
+ const cropW = x2 - x1
229
+ const cropH = y2 - y1
230
+
231
+ const tileCanvas = document.createElement('canvas')
232
+ tileCanvas.width = cropW
233
+ tileCanvas.height = cropH
234
+ const ctx = tileCanvas.getContext('2d')!
235
+ ctx.drawImage(enhanced, x1, y1, cropW, cropH, 0, 0, cropW, cropH)
236
+
237
+ const dets = await inferCanvas(
238
+ tileCanvas,
239
+ session,
240
+ inferenceSize,
241
+ x1,
242
+ y1,
243
+ cropW,
244
+ cropH,
245
+ options?.filterOutliers ?? false,
246
+ )
247
+ all.push(...dets)
248
  }
249
  }
250
 
frontend/src/lib/modelSelect.ts CHANGED
@@ -9,9 +9,9 @@ export function selectModelForImage(width: number, height: number): {
9
  modelUrl: string
10
  inferenceSize: number
11
  } {
12
- // Large portrait images over-detect at 1024; use 640 instead.
13
- const isLargePortrait = height > width * 1.3 || Math.max(width, height) > 2400
14
- if (isLargePortrait) {
15
  return { modelUrl: MODEL_640_URL, inferenceSize: INFERENCE_SIZE_SMALL }
16
  }
17
  return { modelUrl: MODEL_URL, inferenceSize: INFERENCE_SIZE }
 
9
  modelUrl: string
10
  inferenceSize: number
11
  } {
12
+ const maxDim = Math.max(width, height)
13
+ // Use 1024 for most production photos; 640 only for small previews.
14
+ if (maxDim <= 1200) {
15
  return { modelUrl: MODEL_640_URL, inferenceSize: INFERENCE_SIZE_SMALL }
16
  }
17
  return { modelUrl: MODEL_URL, inferenceSize: INFERENCE_SIZE }
scripts/image_enhance.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenCV image enhancement matching the browser pipeline."""
2
+ from __future__ import annotations
3
+
4
+ import cv2
5
+ import numpy as np
6
+
7
+
8
+ def enhance_bgr(image: np.ndarray) -> np.ndarray:
9
+ """Apply exposure normalize, CLAHE on L channel, and mild sharpen."""
10
+ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
11
+ l, a, b = cv2.split(lab)
12
+
13
+ mean_l = float(np.mean(l))
14
+ if mean_l > 1:
15
+ gain = np.clip(128.0 / mean_l, 0.7, 1.4)
16
+ l = np.clip(l.astype(np.float32) * gain, 0, 255).astype(np.uint8)
17
+
18
+ lo, hi = np.percentile(l, (2, 98))
19
+ if hi > lo:
20
+ l = np.clip((l.astype(np.float32) - lo) * (255.0 / (hi - lo)), 0, 255).astype(np.uint8)
21
+
22
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
23
+ l = clahe.apply(l)
24
+
25
+ enhanced = cv2.cvtColor(cv2.merge([l, a, b]), cv2.COLOR_LAB2BGR)
26
+ blurred = cv2.GaussianBlur(enhanced, (0, 0), 1.0)
27
+ sharpened = cv2.addWeighted(enhanced, 1.35, blurred, -0.35, 0)
28
+ return sharpened
scripts/test_samples.py CHANGED
@@ -9,15 +9,46 @@ import cv2
9
  import numpy as np
10
  import onnxruntime as ort
11
 
 
 
12
  ROOT = Path(__file__).resolve().parents[1]
13
- MODEL_PATH = ROOT / "static" / "models" / "countmodel.onnx"
14
  INFERENCE_SIZE = 1024
 
15
  CONF_THRESHOLD = 0.6
16
  IOU_THRESHOLD = 0.45
17
  MAX_DET = 4000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
 
20
- def letterbox(img: np.ndarray, size: int = INFERENCE_SIZE):
21
  h, w = img.shape[:2]
22
  scale = min(size / w, size / h)
23
  new_w, new_h = int(round(w * scale)), int(round(h * scale))
@@ -26,7 +57,7 @@ def letterbox(img: np.ndarray, size: int = INFERENCE_SIZE):
26
  out = np.full((size, size, 3), 114, dtype=np.uint8)
27
  resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
28
  out[pad_y : pad_y + new_h, pad_x : pad_x + new_w] = resized
29
- tensor = out[:, :, ::-1].astype(np.float32) / 255.0 # BGR->RGB
30
  chw = np.transpose(tensor, (2, 0, 1))[None, ...]
31
  meta = {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}
32
  return chw, meta
@@ -65,17 +96,17 @@ def filter_outliers(boxes):
65
  return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
66
 
67
 
68
- def decode(output: np.ndarray, meta: dict, img_w: int, img_h: int, use_outliers: bool = False):
69
  boxes, scores = [], []
70
  for row in output.reshape(-1, 6):
71
  cx, cy, w, h, obj, cls = row
72
  conf = float(obj * cls)
73
  if conf < CONF_THRESHOLD:
74
  continue
75
- x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"]
76
- y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"]
77
- x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"]
78
- y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"]
79
  x1, y1 = max(0, x1), max(0, y1)
80
  x2, y2 = min(img_w, x2), min(img_h, y2)
81
  if x2 <= x1 or y2 <= y1:
@@ -94,43 +125,75 @@ def decode(output: np.ndarray, meta: dict, img_w: int, img_h: int, use_outliers:
94
  return boxes, scores
95
 
96
 
97
- def select_inference_size(w: int, h: int) -> int:
98
- if h > w * 1.3 or max(w, h) > 2400:
99
- return 640
100
- return 1024
101
-
102
-
103
- def model_path_for_size(size: int) -> Path:
104
- if size == 640:
105
- p = ROOT / "static" / "models" / "countmodel-640.onnx"
106
- if p.is_file():
107
- return p
108
- return ROOT / "static" / "models" / "countmodel.onnx"
109
 
110
 
111
- def run_on_image(image_path: Path, out_path: Path):
 
 
 
 
 
 
112
  img = cv2.imread(str(image_path))
113
  if img is None:
114
  raise FileNotFoundError(image_path)
 
 
 
115
  h, w = img.shape[:2]
116
- size = select_inference_size(w, h)
117
- model_path = model_path_for_size(size)
118
  session = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])
119
- tensor, meta = letterbox(img, size)
 
120
  t0 = time.perf_counter()
121
- out = session.run(None, {"images": tensor})[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  ms = (time.perf_counter() - t0) * 1000
123
- boxes, scores = decode(out, meta, w, h)
124
  vis = img.copy()
125
  for i, (box, _sc) in enumerate(zip(boxes, scores), 1):
126
  x1, y1, x2, y2 = map(int, box)
127
  cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
128
  r = max(10, min(x2 - x1, y2 - y1) // 2)
129
  cv2.circle(vis, (cx, cy), r, (0, 0, 255), 2)
130
- cv2.putText(vis, str(i), (cx - 8, cy + 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
 
131
  cv2.putText(vis, f"Count: {len(boxes)}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3)
132
  cv2.imwrite(str(out_path), vis)
133
- return len(boxes), ms, (w, h), size, model_path.name
134
 
135
 
136
  def main():
@@ -141,16 +204,16 @@ def main():
141
  out_dir = ROOT / "test-output"
142
  out_dir.mkdir(exist_ok=True)
143
 
144
- print("Adaptive ONNX inference (640 for large portrait, 1024 otherwise)")
145
  print("-" * 60)
146
  for img_path in images:
147
  if not img_path.is_file():
148
  print(f"SKIP (not found): {img_path}")
149
  continue
150
  out_path = out_dir / f"{img_path.stem}-result.jpg"
151
- count, ms, size, infer_size, model_name = run_on_image(img_path, out_path)
152
  print(f"{img_path.name}")
153
- print(f" Size: {size[0]}x{size[1]} px | model: {model_name} @ {infer_size}")
154
  print(f" Pipes detected: {count}")
155
  print(f" Inference: {ms:.0f} ms")
156
  print(f" Annotated: {out_path}")
 
9
  import numpy as np
10
  import onnxruntime as ort
11
 
12
+ from scripts.image_enhance import enhance_bgr
13
+
14
  ROOT = Path(__file__).resolve().parents[1]
15
+ MODEL_DIR = ROOT / "frontend" / "public" / "models"
16
  INFERENCE_SIZE = 1024
17
+ INFERENCE_SIZE_SMALL = 640
18
  CONF_THRESHOLD = 0.6
19
  IOU_THRESHOLD = 0.45
20
  MAX_DET = 4000
21
+ TILE_OVERLAP = 0.2
22
+
23
+
24
+ def megapixels(w: int, h: int) -> float:
25
+ return (w * h) / 1_000_000
26
+
27
+
28
+ def suggest_tile_grid(w: int, h: int) -> int:
29
+ mp = megapixels(w, h)
30
+ if mp >= 8:
31
+ return 5
32
+ if mp >= 4:
33
+ return 4
34
+ if mp >= 2:
35
+ return 3
36
+ return 2
37
+
38
+
39
+ def should_auto_tile(w: int, h: int) -> bool:
40
+ return megapixels(w, h) >= 2 or max(w, h) > 2000
41
+
42
+
43
+ def select_model(w: int, h: int) -> tuple[Path, int]:
44
+ if max(w, h) <= 1200:
45
+ p = MODEL_DIR / "countmodel-640.onnx"
46
+ if p.is_file():
47
+ return p, INFERENCE_SIZE_SMALL
48
+ return MODEL_DIR / "countmodel.onnx", INFERENCE_SIZE
49
 
50
 
51
+ def letterbox(img: np.ndarray, size: int):
52
  h, w = img.shape[:2]
53
  scale = min(size / w, size / h)
54
  new_w, new_h = int(round(w * scale)), int(round(h * scale))
 
57
  out = np.full((size, size, 3), 114, dtype=np.uint8)
58
  resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
59
  out[pad_y : pad_y + new_h, pad_x : pad_x + new_w] = resized
60
+ tensor = out[:, :, ::-1].astype(np.float32) / 255.0
61
  chw = np.transpose(tensor, (2, 0, 1))[None, ...]
62
  meta = {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}
63
  return chw, meta
 
96
  return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
97
 
98
 
99
+ def decode(output: np.ndarray, meta: dict, img_w: int, img_h: int, offset_x=0, offset_y=0, use_outliers=False):
100
  boxes, scores = [], []
101
  for row in output.reshape(-1, 6):
102
  cx, cy, w, h, obj, cls = row
103
  conf = float(obj * cls)
104
  if conf < CONF_THRESHOLD:
105
  continue
106
+ x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
107
+ y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
108
+ x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
109
+ y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
110
  x1, y1 = max(0, x1), max(0, y1)
111
  x2, y2 = min(img_w, x2), min(img_h, y2)
112
  if x2 <= x1 or y2 <= y1:
 
125
  return boxes, scores
126
 
127
 
128
+ def infer_tile(session, tile: np.ndarray, size: int, offset_x: int, offset_y: int, img_w: int, img_h: int, use_outliers: bool):
129
+ tensor, meta = letterbox(tile, size)
130
+ out = session.run(None, {"images": tensor})[0]
131
+ return decode(out, meta, img_w, img_h, offset_x, offset_y, use_outliers)
 
 
 
 
 
 
 
 
132
 
133
 
134
+ def run_on_image(
135
+ image_path: Path,
136
+ out_path: Path,
137
+ enhance: bool = True,
138
+ use_tiling: bool | None = None,
139
+ use_outliers: bool = False,
140
+ ):
141
  img = cv2.imread(str(image_path))
142
  if img is None:
143
  raise FileNotFoundError(image_path)
144
+ if enhance:
145
+ img = enhance_bgr(img)
146
+
147
  h, w = img.shape[:2]
148
+ model_path, infer_size = select_model(w, h)
 
149
  session = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])
150
+
151
+ tile = use_tiling if use_tiling is not None else should_auto_tile(w, h)
152
  t0 = time.perf_counter()
153
+
154
+ if tile:
155
+ grid = suggest_tile_grid(w, h)
156
+ tile_w = w / grid
157
+ tile_h = h / grid
158
+ all_boxes: list = []
159
+ all_scores: list = []
160
+ for gy in range(grid):
161
+ for gx in range(grid):
162
+ x1 = max(0, gx * tile_w - (tile_w * TILE_OVERLAP * (gx > 0)))
163
+ y1 = max(0, gy * tile_h - (tile_h * TILE_OVERLAP * (gy > 0)))
164
+ x2 = min(w, (gx + 1) * tile_w + (tile_w * TILE_OVERLAP * (gx < grid - 1)))
165
+ y2 = min(h, (gy + 1) * tile_h + (tile_h * TILE_OVERLAP * (gy < grid - 1)))
166
+ crop = img[int(y1) : int(y2), int(x1) : int(x2)]
167
+ boxes, scores = infer_tile(
168
+ session, crop, infer_size, int(x1), int(y1), w, h, use_outliers
169
+ )
170
+ all_boxes.extend(boxes)
171
+ all_scores.extend(scores)
172
+ if all_boxes:
173
+ idx = nms(all_boxes, all_scores)
174
+ boxes = [all_boxes[i] for i in idx]
175
+ scores = [all_scores[i] for i in idx]
176
+ else:
177
+ boxes, scores = [], []
178
+ mode = f"tiling {grid}x{grid}"
179
+ else:
180
+ tensor, meta = letterbox(img, infer_size)
181
+ out = session.run(None, {"images": tensor})[0]
182
+ boxes, scores = decode(out, meta, w, h, use_outliers=use_outliers)
183
+ mode = "single frame"
184
+
185
  ms = (time.perf_counter() - t0) * 1000
 
186
  vis = img.copy()
187
  for i, (box, _sc) in enumerate(zip(boxes, scores), 1):
188
  x1, y1, x2, y2 = map(int, box)
189
  cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
190
  r = max(10, min(x2 - x1, y2 - y1) // 2)
191
  cv2.circle(vis, (cx, cy), r, (0, 0, 255), 2)
192
+ if len(boxes) <= 500:
193
+ cv2.putText(vis, str(i), (cx - 8, cy + 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
194
  cv2.putText(vis, f"Count: {len(boxes)}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3)
195
  cv2.imwrite(str(out_path), vis)
196
+ return len(boxes), ms, (w, h), infer_size, model_path.name, mode
197
 
198
 
199
  def main():
 
204
  out_dir = ROOT / "test-output"
205
  out_dir.mkdir(exist_ok=True)
206
 
207
+ print("ONNX inference with enhance + auto-tiling (matches browser)")
208
  print("-" * 60)
209
  for img_path in images:
210
  if not img_path.is_file():
211
  print(f"SKIP (not found): {img_path}")
212
  continue
213
  out_path = out_dir / f"{img_path.stem}-result.jpg"
214
+ count, ms, size, infer_size, model_name, mode = run_on_image(img_path, out_path)
215
  print(f"{img_path.name}")
216
+ print(f" Size: {size[0]}x{size[1]} px | model: {model_name} @ {infer_size} | {mode}")
217
  print(f" Pipes detected: {count}")
218
  print(f" Inference: {ms:.0f} ms")
219
  print(f" Annotated: {out_path}")