-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenCVCanvas.tsx
More file actions
152 lines (128 loc) · 4.09 KB
/
Copy pathOpenCVCanvas.tsx
File metadata and controls
152 lines (128 loc) · 4.09 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// This file is part of @robomous/opencv-react project from Robomous.
// It is subject to the license terms in the LICENSE file found in the top-level directory
import React, { useRef, useEffect, useCallback } from 'react';
import type { OpenCVCanvasProps } from '../types';
import { useOpenCV } from '../hooks/useOpenCV';
/**
* A React component that renders an internal canvas, loads a source image,
* draws it, and calls `onProcess` with the OpenCV instance once ready.
*
* The consumer is responsible for calling `mat.delete()` on all created Mats
* inside `onProcess` to prevent memory leaks.
*
* @example
* <OpenCVCanvas
* src="/image.jpg"
* outputCanvasRef={outputRef}
* onProcess={({ canvas, cv, outputCanvas }) => {
* let src = null;
* try {
* src = cv.imread(canvas);
* cv.imshow(outputCanvas || canvas, src);
* } finally {
* if (src) src.delete();
* }
* }}
* />
*/
export function OpenCVCanvas({
src,
outputCanvasRef,
autoProcess = true,
className,
crossOrigin,
onLoad,
onProcess,
onError,
}: OpenCVCanvasProps) {
const { cv, isReady } = useOpenCV();
const canvasRef = useRef<HTMLCanvasElement>(null);
const imageRef = useRef<HTMLImageElement | null>(null);
const isImageDrawnRef = useRef(false);
// Refs for stable access to latest callbacks and state in effects
const cvRef = useRef(cv);
cvRef.current = cv;
const isReadyRef = useRef(isReady);
isReadyRef.current = isReady;
const autoProcessRef = useRef(autoProcess);
autoProcessRef.current = autoProcess;
const onProcessRef = useRef(onProcess);
onProcessRef.current = onProcess;
const onErrorRef = useRef(onError);
onErrorRef.current = onError;
const outputCanvasRefRef = useRef(outputCanvasRef);
outputCanvasRefRef.current = outputCanvasRef;
const runProcessing = useCallback(() => {
if (!autoProcessRef.current || !onProcessRef.current) return;
if (!isReadyRef.current || !cvRef.current) return;
if (!isImageDrawnRef.current) return;
const canvas = canvasRef.current;
const image = imageRef.current;
if (!canvas || !image) return;
const context = canvas.getContext('2d');
if (!context) return;
const outputCanvas = outputCanvasRefRef.current?.current ?? undefined;
if (outputCanvas) {
outputCanvas.width = canvas.width;
outputCanvas.height = canvas.height;
}
const run = async () => {
try {
await onProcessRef.current!({
canvas,
context,
image,
cv: cvRef.current!,
outputCanvas,
});
} catch (err) {
onErrorRef.current?.(err instanceof Error ? err : new Error(String(err)));
}
};
run();
}, []);
// Load and draw the source image whenever `src` changes
useEffect(() => {
let stale = false;
isImageDrawnRef.current = false;
const canvas = canvasRef.current;
if (!canvas) return;
const img = new Image();
if (crossOrigin !== undefined) {
img.crossOrigin = crossOrigin;
}
img.onload = () => {
if (stale) return;
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const context = canvas.getContext('2d');
if (!context) {
onErrorRef.current?.(new Error('Failed to get 2D context from canvas'));
return;
}
context.drawImage(img, 0, 0);
imageRef.current = img;
isImageDrawnRef.current = true;
onLoad?.({ canvas, context, image: img });
// If cv is already ready, run processing immediately
runProcessing();
};
img.onerror = () => {
if (stale) return;
onErrorRef.current?.(new Error(`Failed to load image: ${src}`));
};
img.src = src;
return () => {
stale = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [src, crossOrigin]);
// Run processing when OpenCV becomes ready (image may already be drawn)
useEffect(() => {
if (isReady && cv) {
runProcessing();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isReady, cv]);
return <canvas ref={canvasRef} className={className} />;
}