rn-opencv-doc-perspective-correction 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/index.ts +288 -203
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rn-opencv-doc-perspective-correction",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "A React Native library for document corner detection and perspective correction using react-native-fast-opencv",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -1,203 +1,288 @@
1
- // @ts-nocheck
2
- import { OpenCV, OpenCVMat, ObjectType, DataTypes, ColorConversionCodes } from 'react-native-fast-opencv';
3
-
4
- export type Point = { x: number; y: number };
5
-
6
- export class DocumentScanner {
7
- private static getDistance(p1: Point, p2: Point) {
8
- return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
9
- }
10
-
11
- private static sortCorners(corners: Point[]): Point[] {
12
- if (corners.length !== 4) return corners;
13
-
14
- const center = corners.reduce(
15
- (acc, cur) => ({ x: acc.x + cur.x / 4, y: acc.y + cur.y / 4 }),
16
- { x: 0, y: 0 }
17
- );
18
-
19
- return corners.sort((a, b) => {
20
- const angleA = Math.atan2(a.y - center.y, a.x - center.x);
21
- const angleB = Math.atan2(b.y - center.y, b.x - center.x);
22
- return angleA - angleB;
23
- });
24
- }
25
-
26
- public static detectPageCorners(imageBase64: string): Point[] | undefined {
27
- let src: OpenCVMat | null = null;
28
- let gray: OpenCVMat | null = null;
29
- let blurred: OpenCVMat | null = null;
30
- let edges: OpenCVMat | null = null;
31
- let contoursObj: any = null;
32
- let hierarchyObj: any = null;
33
-
34
- try {
35
- src = OpenCV.base64ToMat(imageBase64);
36
- gray = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
37
- blurred = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
38
- edges = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U); // This will hold the threshold output
39
-
40
- OpenCV.invoke('cvtColor', src, gray, ColorConversionCodes.COLOR_BGR2GRAY);
41
-
42
- const ksize = OpenCV.createObject(ObjectType.Size, 5, 5);
43
- OpenCV.invoke('GaussianBlur', gray, blurred, ksize, 0);
44
-
45
- // Python uses: cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
46
- // THRESH_BINARY = 0
47
- // THRESH_OTSU = 8
48
- // THRESH_BINARY + THRESH_OTSU = 8
49
- OpenCV.invoke('threshold', blurred, edges, 0, 255, 8);
50
-
51
- contoursObj = OpenCV.createObject(ObjectType.MatVector);
52
- hierarchyObj = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
53
-
54
- // Using RETR_EXTERNAL similar to the Python script for outer contours
55
- OpenCV.invoke('findContoursWithHierarchy', edges, contoursObj, hierarchyObj, 0 /* RETR_EXTERNAL */, 2 /* CHAIN_APPROX_SIMPLE */);
56
-
57
- const contoursJS = OpenCV.toJSValue(contoursObj);
58
- const contoursArray = contoursJS?.array || [];
59
- const contoursSize = contoursArray.length;
60
-
61
- if (contoursSize === 0) {
62
- return undefined;
63
- }
64
-
65
- // First pass: extract all areas to sort them and minimize JSI calls
66
- let contourMetrics = [];
67
- for (let i = 0; i < contoursSize; i++) {
68
- const contour = OpenCV.copyObjectFromVector(contoursObj, i);
69
- const areaObj = OpenCV.invoke('contourArea', contour);
70
- const area = areaObj ? areaObj.value : 0;
71
- if (area > 5000) { // filter very small artifacts
72
- contourMetrics.push({ index: i, area, contour });
73
- }
74
- }
75
-
76
- // Sort contours by area in descending order
77
- contourMetrics.sort((a, b) => b.area - a.area);
78
-
79
- let largestPoly: Point[] | undefined = undefined;
80
-
81
- // Second pass: only check approxPolyDP for the largest ones
82
- for (let i = 0; i < contourMetrics.length; i++) {
83
- const metric = contourMetrics[i];
84
- const contour = metric.contour;
85
-
86
- const periObj = OpenCV.invoke('arcLength', contour, true);
87
- const peri = periObj ? periObj.value : 0;
88
- const approx = OpenCV.createObject(ObjectType.PointVector);
89
- OpenCV.invoke('approxPolyDP', contour, approx, 0.02 * peri, true);
90
-
91
- const approxJS = OpenCV.toJSValue(approx);
92
- if (approxJS && approxJS.array && approxJS.array.length === 4) {
93
- largestPoly = approxJS.array as Point[];
94
- break; // Stop at the first 4-point polygon like python script
95
- }
96
- }
97
-
98
-
99
-
100
- if (largestPoly && largestPoly.length === 4) {
101
- return this.sortCorners(largestPoly);
102
- }
103
- return undefined;
104
- } catch (e: any) {
105
- console.error('Lỗi khi dò tìm góc tài liệu (OpenCV):', e);
106
- throw new Error(`[OpenCV Corner Detection Error]: ${e.message}`);
107
- } finally {
108
- OpenCV.clearBuffers();
109
- }
110
- }
111
-
112
- public static applyPerspectiveCorrection(imageBase64: string, corners: Point[]): string | undefined {
113
- let src: OpenCVMat | null = null;
114
- let dst: OpenCVMat | null = null;
115
-
116
- try {
117
- if (!corners || corners.length !== 4) throw new Error("Cần truyền vào đúng 4 điểm góc.");
118
-
119
- const sortedCorners = this.sortCorners([...corners]);
120
- const [tl, tr, br, bl] = sortedCorners;
121
-
122
- const widthA = this.getDistance(br, bl);
123
- const widthB = this.getDistance(tr, tl);
124
- const maxWidth = Math.max(Math.round(widthA), Math.round(widthB));
125
-
126
- const heightA = this.getDistance(tr, br);
127
- const heightB = this.getDistance(tl, bl);
128
- const maxHeight = Math.max(Math.round(heightA), Math.round(heightB));
129
-
130
- if (maxWidth === 0 || maxHeight === 0) return undefined;
131
-
132
- src = OpenCV.base64ToMat(imageBase64);
133
- dst = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8UC3);
134
-
135
- const srcPoints = OpenCV.createObject(ObjectType.Point2fVector,
136
- [
137
- OpenCV.createObject(ObjectType.Point2f, tl.x, tl.y),
138
- OpenCV.createObject(ObjectType.Point2f, tr.x, tr.y),
139
- OpenCV.createObject(ObjectType.Point2f, br.x, br.y),
140
- OpenCV.createObject(ObjectType.Point2f, bl.x, bl.y)
141
- ]
142
- );
143
- const dstPoints = OpenCV.createObject(ObjectType.Point2fVector,
144
- [
145
- OpenCV.createObject(ObjectType.Point2f, 0, 0),
146
- OpenCV.createObject(ObjectType.Point2f, maxWidth - 1, 0),
147
- OpenCV.createObject(ObjectType.Point2f, maxWidth - 1, maxHeight - 1),
148
- OpenCV.createObject(ObjectType.Point2f, 0, maxHeight - 1)
149
- ]
150
- );
151
-
152
- const perspectiveMatrix = OpenCV.invoke('getPerspectiveTransform', srcPoints, dstPoints, 0);
153
-
154
- const size = OpenCV.createObject(ObjectType.Size, maxWidth, maxHeight);
155
- const borderValue = OpenCV.createObject(ObjectType.Scalar, 0);
156
-
157
- OpenCV.invoke('warpPerspective', src, dst, perspectiveMatrix, size, 1 /* INTER_LINEAR */, 0 /* BORDER_CONSTANT */, borderValue);
158
-
159
- const dstValue = OpenCV.toJSValue(dst);
160
-
161
- // Fix "writeFile got an object" by guaranteeing string type
162
- if (dstValue && dstValue.base64) {
163
- return typeof dstValue.base64 === 'string' ? dstValue.base64 : String(dstValue.base64);
164
- }
165
- return undefined;
166
- } catch (e) {
167
- console.error('Lỗi khi bóp phối cảnh tài liệu (OpenCV):', e);
168
- return undefined;
169
- } finally {
170
- OpenCV.clearBuffers();
171
- }
172
- }
173
-
174
- /**
175
- * Xoay ảnh 90, -90 hoặc 180 độ
176
- */
177
- public static rotateImage(imageBase64: string, angle: 90 | -90 | 180): string | undefined {
178
- let src: OpenCVMat | null = null;
179
- let dst: OpenCVMat | null = null;
180
- try {
181
- src = OpenCV.base64ToMat(imageBase64);
182
- dst = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
183
-
184
- let rotateCode = 0; // ROTATE_90_CLOCKWISE
185
- if (angle === -90) rotateCode = 2; // ROTATE_90_COUNTERCLOCKWISE
186
- else if (angle === 180) rotateCode = 1; // ROTATE_180
187
-
188
- OpenCV.invoke('rotate', src, dst, rotateCode);
189
-
190
- const dstValue = OpenCV.toJSValue(dst);
191
- if (dstValue && dstValue.base64) {
192
- return typeof dstValue.base64 === 'string' ? dstValue.base64 : String(dstValue.base64);
193
- }
194
- return undefined;
195
- } catch (e: any) {
196
- console.error('Lỗi khi xoay ảnh (OpenCV):', e);
197
- return undefined;
198
- } finally {
199
- OpenCV.clearBuffers();
200
- }
201
- }
202
- }
203
-
1
+ // @ts-nocheck
2
+ import { OpenCV, OpenCVMat, ObjectType, DataTypes, ColorConversionCodes } from 'react-native-fast-opencv';
3
+
4
+ export type Point = { x: number; y: number };
5
+
6
+ /**
7
+ * Gợi ý phương thức OCR nên dùng dựa trên phân tích màu sắc.
8
+ * 'G' = ML Kit (nhiều màu, ảnh thẻ, màu sắc phong phú)
9
+ * 'S' = Tesseract (ít màu, bản scan, giấy trắng)
10
+ */
11
+ export type OcrMethodHint = 'G' | 'S';
12
+
13
+ export class DocumentScanner {
14
+ private static getDistance(p1: Point, p2: Point) {
15
+ return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
16
+ }
17
+
18
+ private static sortCorners(corners: Point[]): Point[] {
19
+ if (corners.length !== 4) return corners;
20
+
21
+ const center = corners.reduce(
22
+ (acc, cur) => ({ x: acc.x + cur.x / 4, y: acc.y + cur.y / 4 }),
23
+ { x: 0, y: 0 }
24
+ );
25
+
26
+ return corners.sort((a, b) => {
27
+ const angleA = Math.atan2(a.y - center.y, a.x - center.x);
28
+ const angleB = Math.atan2(b.y - center.y, b.x - center.x);
29
+ return angleA - angleB;
30
+ });
31
+ }
32
+
33
+ public static detectPageCorners(imageBase64: string): Point[] | undefined {
34
+ let src: OpenCVMat | null = null;
35
+ let gray: OpenCVMat | null = null;
36
+ let blurred: OpenCVMat | null = null;
37
+ let edges: OpenCVMat | null = null;
38
+ let contoursObj: any = null;
39
+ let hierarchyObj: any = null;
40
+
41
+ try {
42
+ src = OpenCV.base64ToMat(imageBase64);
43
+ gray = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
44
+ blurred = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
45
+ edges = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
46
+
47
+ OpenCV.invoke('cvtColor', src, gray, ColorConversionCodes.COLOR_BGR2GRAY);
48
+
49
+ const ksize = OpenCV.createObject(ObjectType.Size, 5, 5);
50
+ OpenCV.invoke('GaussianBlur', gray, blurred, ksize, 0);
51
+
52
+ // THRESH_BINARY + THRESH_OTSU = 8
53
+ OpenCV.invoke('threshold', blurred, edges, 0, 255, 8);
54
+
55
+ contoursObj = OpenCV.createObject(ObjectType.MatVector);
56
+ hierarchyObj = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
57
+
58
+ OpenCV.invoke('findContoursWithHierarchy', edges, contoursObj, hierarchyObj, 0 /* RETR_EXTERNAL */, 2 /* CHAIN_APPROX_SIMPLE */);
59
+
60
+ const contoursJS = OpenCV.toJSValue(contoursObj);
61
+ const contoursArray = contoursJS?.array || [];
62
+ const contoursSize = contoursArray.length;
63
+
64
+ if (contoursSize === 0) {
65
+ return undefined;
66
+ }
67
+
68
+ let contourMetrics = [];
69
+ for (let i = 0; i < contoursSize; i++) {
70
+ const contour = OpenCV.copyObjectFromVector(contoursObj, i);
71
+ const areaObj = OpenCV.invoke('contourArea', contour);
72
+ const area = areaObj ? areaObj.value : 0;
73
+ if (area > 5000) {
74
+ contourMetrics.push({ index: i, area, contour });
75
+ }
76
+ }
77
+
78
+ contourMetrics.sort((a, b) => b.area - a.area);
79
+
80
+ let largestPoly: Point[] | undefined = undefined;
81
+
82
+ for (let i = 0; i < contourMetrics.length; i++) {
83
+ const metric = contourMetrics[i];
84
+ const contour = metric.contour;
85
+
86
+ const periObj = OpenCV.invoke('arcLength', contour, true);
87
+ const peri = periObj ? periObj.value : 0;
88
+ const approx = OpenCV.createObject(ObjectType.PointVector);
89
+ OpenCV.invoke('approxPolyDP', contour, approx, 0.02 * peri, true);
90
+
91
+ const approxJS = OpenCV.toJSValue(approx);
92
+ if (approxJS && approxJS.array && approxJS.array.length === 4) {
93
+ largestPoly = approxJS.array as Point[];
94
+ break;
95
+ }
96
+ }
97
+
98
+ if (largestPoly && largestPoly.length === 4) {
99
+ return this.sortCorners(largestPoly);
100
+ }
101
+ return undefined;
102
+ } catch (e: any) {
103
+ console.error('Lỗi khi dò tìm góc tài liệu (OpenCV):', e);
104
+ throw new Error(`[OpenCV Corner Detection Error]: ${e.message}`);
105
+ } finally {
106
+ OpenCV.clearBuffers();
107
+ }
108
+ }
109
+
110
+ public static applyPerspectiveCorrection(imageBase64: string, corners: Point[]): string | undefined {
111
+ let src: OpenCVMat | null = null;
112
+ let dst: OpenCVMat | null = null;
113
+
114
+ try {
115
+ if (!corners || corners.length !== 4) throw new Error("Cần truyền vào đúng 4 điểm góc.");
116
+
117
+ const sortedCorners = this.sortCorners([...corners]);
118
+ const [tl, tr, br, bl] = sortedCorners;
119
+
120
+ const widthA = this.getDistance(br, bl);
121
+ const widthB = this.getDistance(tr, tl);
122
+ const maxWidth = Math.max(Math.round(widthA), Math.round(widthB));
123
+
124
+ const heightA = this.getDistance(tr, br);
125
+ const heightB = this.getDistance(tl, bl);
126
+ const maxHeight = Math.max(Math.round(heightA), Math.round(heightB));
127
+
128
+ if (maxWidth === 0 || maxHeight === 0) return undefined;
129
+
130
+ src = OpenCV.base64ToMat(imageBase64);
131
+ dst = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8UC3);
132
+
133
+ const srcPoints = OpenCV.createObject(ObjectType.Point2fVector,
134
+ [
135
+ OpenCV.createObject(ObjectType.Point2f, tl.x, tl.y),
136
+ OpenCV.createObject(ObjectType.Point2f, tr.x, tr.y),
137
+ OpenCV.createObject(ObjectType.Point2f, br.x, br.y),
138
+ OpenCV.createObject(ObjectType.Point2f, bl.x, bl.y)
139
+ ]
140
+ );
141
+ const dstPoints = OpenCV.createObject(ObjectType.Point2fVector,
142
+ [
143
+ OpenCV.createObject(ObjectType.Point2f, 0, 0),
144
+ OpenCV.createObject(ObjectType.Point2f, maxWidth - 1, 0),
145
+ OpenCV.createObject(ObjectType.Point2f, maxWidth - 1, maxHeight - 1),
146
+ OpenCV.createObject(ObjectType.Point2f, 0, maxHeight - 1)
147
+ ]
148
+ );
149
+
150
+ const perspectiveMatrix = OpenCV.invoke('getPerspectiveTransform', srcPoints, dstPoints, 0);
151
+
152
+ const size = OpenCV.createObject(ObjectType.Size, maxWidth, maxHeight);
153
+ const borderValue = OpenCV.createObject(ObjectType.Scalar, 0);
154
+
155
+ OpenCV.invoke('warpPerspective', src, dst, perspectiveMatrix, size, 1 /* INTER_LINEAR */, 0 /* BORDER_CONSTANT */, borderValue);
156
+
157
+ const dstValue = OpenCV.toJSValue(dst);
158
+
159
+ if (dstValue && dstValue.base64) {
160
+ return typeof dstValue.base64 === 'string' ? dstValue.base64 : String(dstValue.base64);
161
+ }
162
+ return undefined;
163
+ } catch (e) {
164
+ console.error('Lỗi khi bóp phối cảnh tài liệu (OpenCV):', e);
165
+ return undefined;
166
+ } finally {
167
+ OpenCV.clearBuffers();
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Xoay ảnh 90, -90 hoặc 180 độ
173
+ */
174
+ public static rotateImage(imageBase64: string, angle: 90 | -90 | 180): string | undefined {
175
+ let src: OpenCVMat | null = null;
176
+ let dst: OpenCVMat | null = null;
177
+ try {
178
+ src = OpenCV.base64ToMat(imageBase64);
179
+ dst = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8U);
180
+
181
+ let rotateCode = 0; // ROTATE_90_CLOCKWISE
182
+ if (angle === -90) rotateCode = 2; // ROTATE_90_COUNTERCLOCKWISE
183
+ else if (angle === 180) rotateCode = 1; // ROTATE_180
184
+
185
+ OpenCV.invoke('rotate', src, dst, rotateCode);
186
+
187
+ const dstValue = OpenCV.toJSValue(dst);
188
+ if (dstValue && dstValue.base64) {
189
+ return typeof dstValue.base64 === 'string' ? dstValue.base64 : String(dstValue.base64);
190
+ }
191
+ return undefined;
192
+ } catch (e: any) {
193
+ console.error('Lỗi khi xoay ảnh (OpenCV):', e);
194
+ return undefined;
195
+ } finally {
196
+ OpenCV.clearBuffers();
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Phân tích độ phức tạp màu sắc để gợi ý phương thức OCR phù hợp.
202
+ *
203
+ * - Nếu corners phát hiện thành công → crop vùng tài liệu và phân tích vùng đó
204
+ * - Nếu không có corners (phát hiện thất bại) → phân tích toàn bộ ảnh
205
+ * - Dùng không gian màu Lab, đo độ lệch chuẩn kênh a* (xanh↔đỏ) và b* (lam↔vàng)
206
+ * - stdA + stdB > threshold → nhiều màu sắc → 'G' (ML Kit, phù hợp thẻ, ảnh màu)
207
+ * - stdA + stdB ≤ threshold → ít màu sắc → 'S' (Tesseract, phù hợp giấy trắng, bản scan)
208
+ *
209
+ * @param imageBase64 Ảnh gốc base64 JPEG
210
+ * @param corners 4 góc tài liệu đã phát hiện (tuỳ chọn)
211
+ * @param colorThreshold Ngưỡng phân biệt (mặc định 18.0, điều chỉnh nếu cần tinh chỉnh)
212
+ */
213
+ public static analyzeColorComplexity(
214
+ imageBase64: string,
215
+ corners?: Point[],
216
+ colorThreshold: number = 18.0
217
+ ): OcrMethodHint {
218
+ let src: OpenCVMat | null = null;
219
+ let roi: OpenCVMat | null = null;
220
+ let lab: OpenCVMat | null = null;
221
+
222
+ try {
223
+ src = OpenCV.base64ToMat(imageBase64);
224
+
225
+ // Nếu có corners hợp lệ → crop vùng tài liệu để phân tích chính xác hơn
226
+ if (corners && corners.length === 4) {
227
+ try {
228
+ const sortedCorners = this.sortCorners([...corners]);
229
+ const [tl, tr, br, bl] = sortedCorners;
230
+ const widthA = this.getDistance(br, bl);
231
+ const widthB = this.getDistance(tr, tl);
232
+ const maxWidth = Math.max(Math.round(widthA), Math.round(widthB));
233
+ const heightA = this.getDistance(tr, br);
234
+ const heightB = this.getDistance(tl, bl);
235
+ const maxHeight = Math.max(Math.round(heightA), Math.round(heightB));
236
+
237
+ if (maxWidth > 0 && maxHeight > 0) {
238
+ const srcPts = OpenCV.createObject(ObjectType.Point2fVector, [
239
+ OpenCV.createObject(ObjectType.Point2f, tl.x, tl.y),
240
+ OpenCV.createObject(ObjectType.Point2f, tr.x, tr.y),
241
+ OpenCV.createObject(ObjectType.Point2f, br.x, br.y),
242
+ OpenCV.createObject(ObjectType.Point2f, bl.x, bl.y),
243
+ ]);
244
+ const dstPts = OpenCV.createObject(ObjectType.Point2fVector, [
245
+ OpenCV.createObject(ObjectType.Point2f, 0, 0),
246
+ OpenCV.createObject(ObjectType.Point2f, maxWidth - 1, 0),
247
+ OpenCV.createObject(ObjectType.Point2f, maxWidth - 1, maxHeight - 1),
248
+ OpenCV.createObject(ObjectType.Point2f, 0, maxHeight - 1),
249
+ ]);
250
+ const perspM = OpenCV.invoke('getPerspectiveTransform', srcPts, dstPts, 0);
251
+ const sz = OpenCV.createObject(ObjectType.Size, maxWidth, maxHeight);
252
+ const borderVal = OpenCV.createObject(ObjectType.Scalar, 0);
253
+ roi = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8UC3);
254
+ OpenCV.invoke('warpPerspective', src, roi, perspM, sz, 1, 0, borderVal);
255
+ }
256
+ } catch (_) {
257
+ roi = null; // Crop lỗi → dùng toàn ảnh
258
+ }
259
+ }
260
+
261
+ const target = roi ?? src; // Dùng vùng crop nếu có, ngược lại toàn ảnh
262
+
263
+ // Chuyển sang Lab (L=sáng/tối, a*=màu xanh↔đỏ, b*=màu lam↔vàng)
264
+ lab = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_8UC3);
265
+ OpenCV.invoke('cvtColor', target, lab, ColorConversionCodes.COLOR_BGR2Lab);
266
+
267
+ // Đo mean và stddev từng kênh
268
+ const meanMat = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_64F);
269
+ const stdMat = OpenCV.createObject(ObjectType.Mat, 0, 0, DataTypes.CV_64F);
270
+ OpenCV.invoke('meanStdDev', lab, meanMat, stdMat);
271
+
272
+ const stdJS = OpenCV.toJSValue(stdMat);
273
+ const stdArray: number[] = stdJS?.array ?? [];
274
+ const stdA = stdArray[1] ?? 0; // a*: xanh lá ↔ đỏ
275
+ const stdB = stdArray[2] ?? 0; // b*: lam ↔ vàng
276
+
277
+ const colorScore = stdA + stdB;
278
+ console.log(`[OCR Auto] colorScore=${colorScore.toFixed(2)} threshold=${colorThreshold} => ${colorScore > colorThreshold ? 'G (ML Kit)' : 'S (Tesseract)'}`);
279
+
280
+ return colorScore > colorThreshold ? 'G' : 'S';
281
+ } catch (e: any) {
282
+ console.warn('[OpenCV] analyzeColorComplexity lỗi, fallback G:', e?.message);
283
+ return 'G'; // Fallback an toàn về ML Kit
284
+ } finally {
285
+ OpenCV.clearBuffers();
286
+ }
287
+ }
288
+ }