Skip to content

Commit d5bd9a4

Browse files
committed
Improve image loading
1 parent 1a1f20b commit d5bd9a4

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

src/utils/imagePreprocess.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export async function preprocessImage(file: File): Promise<HTMLCanvasElement> {
5454
img.onload = () => resolve(img);
5555
img.onerror = reject;
5656
img.src = blobUrl;
57-
});
57+
}).finally(() => URL.revokeObjectURL(blobUrl));
5858

5959
const src = cv.imread(imageEl);
6060

@@ -99,7 +99,6 @@ export async function preprocessImage(file: File): Promise<HTMLCanvasElement> {
9999
src.delete();
100100
scaled.delete();
101101
bin.delete();
102-
URL.revokeObjectURL(blobUrl);
103102

104103
return outCanvas;
105104
}

src/utils/opencvLoader.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
let cachedCv: any = null;
2+
let inFlight: Promise<any> | null = null;
23

34
function isPromiseInstance(obj: any): obj is Promise<any> {
45
return obj instanceof Promise;
56
}
67

7-
export async function loadOpenCV(): Promise<any> {
8-
if (cachedCv) return cachedCv;
9-
8+
async function importOpenCV(): Promise<any> {
109
const mod: any = await import('@techstark/opencv-js');
1110
const cvCandidate: any = mod?.default ?? mod;
1211

@@ -34,4 +33,17 @@ export async function loadOpenCV(): Promise<any> {
3433
cachedCv = cv;
3534

3635
return cachedCv;
36+
}
37+
38+
export async function loadOpenCV(): Promise<any> {
39+
if (cachedCv) return cachedCv;
40+
if (inFlight) return inFlight;
41+
42+
inFlight = importOpenCV();
43+
44+
try {
45+
return await inFlight;
46+
} finally {
47+
inFlight = null;
48+
}
3749
}

0 commit comments

Comments
 (0)