id-scanner-lib 1.0.0 → 1.2.0
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.
- package/README.md +173 -0
- package/dist/core.d.ts +77 -0
- package/dist/id-recognition/data-extractor.d.ts +31 -0
- package/dist/id-recognition/id-detector.d.ts +25 -1
- package/dist/id-scanner-core.esm.js +10870 -0
- package/dist/id-scanner-core.esm.js.map +1 -0
- package/dist/id-scanner-core.js +10882 -0
- package/dist/id-scanner-core.js.map +1 -0
- package/dist/id-scanner-core.min.js +9 -0
- package/dist/id-scanner-core.min.js.map +1 -0
- package/dist/id-scanner-ocr.esm.js +1625 -0
- package/dist/id-scanner-ocr.esm.js.map +1 -0
- package/dist/id-scanner-ocr.js +1634 -0
- package/dist/id-scanner-ocr.js.map +1 -0
- package/dist/id-scanner-ocr.min.js +9 -0
- package/dist/id-scanner-ocr.min.js.map +1 -0
- package/dist/id-scanner-qr.esm.js +773 -0
- package/dist/id-scanner-qr.esm.js.map +1 -0
- package/dist/id-scanner-qr.js +782 -0
- package/dist/id-scanner-qr.js.map +1 -0
- package/dist/id-scanner-qr.min.js +9 -0
- package/dist/id-scanner-qr.min.js.map +1 -0
- package/dist/id-scanner.js +1954 -94656
- package/dist/id-scanner.js.map +1 -1
- package/dist/id-scanner.min.js +7 -7
- package/dist/id-scanner.min.js.map +1 -1
- package/dist/index-umd.d.ts +96 -0
- package/dist/index.d.ts +23 -88
- package/dist/ocr-module.d.ts +67 -0
- package/dist/qr-module.d.ts +68 -0
- package/dist/types/core.d.ts +77 -0
- package/dist/types/demo/demo.d.ts +14 -0
- package/dist/types/id-recognition/data-extractor.d.ts +105 -0
- package/dist/types/id-recognition/id-detector.d.ts +100 -0
- package/dist/types/id-recognition/ocr-processor.d.ts +64 -0
- package/dist/types/index-umd.d.ts +96 -0
- package/dist/types/index.d.ts +78 -0
- package/dist/types/ocr-module.d.ts +67 -0
- package/dist/types/qr-module.d.ts +68 -0
- package/dist/types/scanner/barcode-scanner.d.ts +90 -0
- package/dist/types/scanner/qr-scanner.d.ts +80 -0
- package/dist/types/utils/camera.d.ts +81 -0
- package/dist/types/utils/image-processing.d.ts +75 -0
- package/dist/types/utils/types.d.ts +65 -0
- package/dist/utils/camera.d.ts +18 -13
- package/dist/utils/types.d.ts +6 -6
- package/package.json +25 -4
- package/src/core.ts +138 -0
- package/src/id-recognition/data-extractor.ts +97 -0
- package/src/id-recognition/id-detector.ts +230 -67
- package/src/id-recognition/ocr-processor.ts +145 -27
- package/src/id-recognition/ocr-worker.ts +146 -0
- package/src/index-umd.ts +240 -0
- package/src/index.ts +125 -139
- package/src/ocr-module.ts +139 -0
- package/src/qr-module.ts +129 -0
- package/src/utils/camera.ts +61 -36
- package/src/utils/image-processing.ts +204 -0
- package/src/utils/performance.ts +208 -0
- package/src/utils/resource-manager.ts +198 -0
- package/src/utils/types.ts +23 -6
- package/src/utils/worker.ts +173 -0
|
@@ -0,0 +1,1634 @@
|
|
|
1
|
+
(function (global, factory) {
|
|
2
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tesseract.js')) :
|
|
3
|
+
typeof define === 'function' && define.amd ? define(['exports', 'tesseract.js'], factory) :
|
|
4
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.IDScannerOCR = {}, global.Tesseract));
|
|
5
|
+
})(this, (function (exports, tesseract_js) { 'use strict';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @file 相机工具类
|
|
9
|
+
* @description 提供访问和控制设备摄像头的功能
|
|
10
|
+
* @module Camera
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* 相机工具类
|
|
14
|
+
*
|
|
15
|
+
* 提供访问设备摄像头、获取视频流以及捕获图像帧的功能
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* // 创建相机实例
|
|
20
|
+
* const camera = new Camera({
|
|
21
|
+
* width: 1280,
|
|
22
|
+
* height: 720,
|
|
23
|
+
* facingMode: 'environment' // 使用后置摄像头
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // 初始化相机
|
|
27
|
+
* const videoElement = document.getElementById('video') as HTMLVideoElement;
|
|
28
|
+
* await camera.start(videoElement);
|
|
29
|
+
*
|
|
30
|
+
* // 捕获当前视频帧
|
|
31
|
+
* const imageData = camera.captureFrame();
|
|
32
|
+
*
|
|
33
|
+
* // 使用结束后释放资源
|
|
34
|
+
* camera.stop();
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
class Camera {
|
|
38
|
+
/**
|
|
39
|
+
* 创建相机实例
|
|
40
|
+
* @param {CameraOptions} [options] - 相机配置选项
|
|
41
|
+
*/
|
|
42
|
+
constructor(options = {}) {
|
|
43
|
+
this.options = options;
|
|
44
|
+
this.stream = null;
|
|
45
|
+
this.videoElement = null;
|
|
46
|
+
this.options = {
|
|
47
|
+
width: 640,
|
|
48
|
+
height: 480,
|
|
49
|
+
facingMode: 'environment',
|
|
50
|
+
...options
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* 启动摄像头并将视频流绑定到视频元素
|
|
55
|
+
* @param videoElement HTML视频元素
|
|
56
|
+
* @returns Promise<void>
|
|
57
|
+
*/
|
|
58
|
+
async start(videoElement) {
|
|
59
|
+
return this.initialize(videoElement);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 停止摄像头并释放资源
|
|
63
|
+
*/
|
|
64
|
+
stop() {
|
|
65
|
+
this.release();
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* 初始化相机,获取视频流并绑定到视频元素
|
|
69
|
+
*
|
|
70
|
+
* @param {HTMLVideoElement} videoElement - 用于显示视频流的视频元素
|
|
71
|
+
* @returns {Promise<void>} 初始化完成的Promise
|
|
72
|
+
* @throws 如果无法访问摄像头,将抛出错误
|
|
73
|
+
*/
|
|
74
|
+
async initialize(videoElement) {
|
|
75
|
+
this.videoElement = videoElement;
|
|
76
|
+
try {
|
|
77
|
+
// 构建媒体约束
|
|
78
|
+
const constraints = {
|
|
79
|
+
video: {
|
|
80
|
+
width: { ideal: this.options.width },
|
|
81
|
+
height: { ideal: this.options.height },
|
|
82
|
+
facingMode: this.options.facingMode
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
// 获取视频流
|
|
86
|
+
this.stream = await navigator.mediaDevices.getUserMedia(constraints);
|
|
87
|
+
// 绑定到视频元素
|
|
88
|
+
if (this.videoElement) {
|
|
89
|
+
this.videoElement.srcObject = this.stream;
|
|
90
|
+
await new Promise((resolve) => {
|
|
91
|
+
if (this.videoElement) {
|
|
92
|
+
this.videoElement.onloadedmetadata = () => {
|
|
93
|
+
if (this.videoElement) {
|
|
94
|
+
this.videoElement.play().then(() => resolve());
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
console.error('无法访问摄像头:', error);
|
|
103
|
+
throw new Error('无法访问摄像头。请确保已授予摄像头访问权限,并且摄像头未被其他应用程序占用。');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* 捕获当前视频帧
|
|
108
|
+
*
|
|
109
|
+
* @returns {ImageData|null} 视频帧的ImageData对象,如果未初始化则返回null
|
|
110
|
+
*/
|
|
111
|
+
captureFrame() {
|
|
112
|
+
if (!this.videoElement) {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
// 创建Canvas元素用于捕获视频帧
|
|
116
|
+
const canvas = document.createElement('canvas');
|
|
117
|
+
canvas.width = this.videoElement.videoWidth;
|
|
118
|
+
canvas.height = this.videoElement.videoHeight;
|
|
119
|
+
const context = canvas.getContext('2d');
|
|
120
|
+
if (!context) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
// 将视频内容绘制到Canvas中
|
|
124
|
+
context.drawImage(this.videoElement, 0, 0, canvas.width, canvas.height);
|
|
125
|
+
// 获取ImageData对象
|
|
126
|
+
return context.getImageData(0, 0, canvas.width, canvas.height);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* 释放摄像头资源
|
|
130
|
+
*/
|
|
131
|
+
release() {
|
|
132
|
+
// 停止视频流的所有轨道
|
|
133
|
+
if (this.stream) {
|
|
134
|
+
this.stream.getTracks().forEach(track => track.stop());
|
|
135
|
+
this.stream = null;
|
|
136
|
+
}
|
|
137
|
+
// 清除视频元素绑定
|
|
138
|
+
if (this.videoElement) {
|
|
139
|
+
this.videoElement.srcObject = null;
|
|
140
|
+
this.videoElement = null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* @file 图像处理工具类
|
|
147
|
+
* @description 提供图像处理相关的辅助功能
|
|
148
|
+
* @module ImageProcessor
|
|
149
|
+
*/
|
|
150
|
+
/**
|
|
151
|
+
* 图像处理工具类
|
|
152
|
+
*
|
|
153
|
+
* 提供常用的图像处理功能,如亮度和对比度调整、灰度转换、图像大小调整等。
|
|
154
|
+
* 这些功能可用于增强图像质量,提高OCR和扫描的识别率。
|
|
155
|
+
*
|
|
156
|
+
* @example
|
|
157
|
+
* ```typescript
|
|
158
|
+
* // 使用图像处理功能增强图像
|
|
159
|
+
* const enhancedImage = ImageProcessor.adjustBrightnessContrast(
|
|
160
|
+
* originalImageData,
|
|
161
|
+
* 15, // 增加亮度
|
|
162
|
+
* 25 // 增加对比度
|
|
163
|
+
* );
|
|
164
|
+
*
|
|
165
|
+
* // 转换为灰度图像
|
|
166
|
+
* const grayImage = ImageProcessor.toGrayscale(originalImageData);
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
class ImageProcessor {
|
|
170
|
+
/**
|
|
171
|
+
* 将ImageData转换为Canvas元素
|
|
172
|
+
*
|
|
173
|
+
* @param {ImageData} imageData - 要转换的图像数据
|
|
174
|
+
* @returns {HTMLCanvasElement} 包含图像的Canvas元素
|
|
175
|
+
*/
|
|
176
|
+
static imageDataToCanvas(imageData) {
|
|
177
|
+
const canvas = document.createElement('canvas');
|
|
178
|
+
canvas.width = imageData.width;
|
|
179
|
+
canvas.height = imageData.height;
|
|
180
|
+
const ctx = canvas.getContext('2d');
|
|
181
|
+
if (ctx) {
|
|
182
|
+
ctx.putImageData(imageData, 0, 0);
|
|
183
|
+
}
|
|
184
|
+
return canvas;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* 将Canvas转换为ImageData
|
|
188
|
+
*
|
|
189
|
+
* @param {HTMLCanvasElement} canvas - 要转换的Canvas元素
|
|
190
|
+
* @returns {ImageData|null} Canvas的图像数据,如果获取失败则返回null
|
|
191
|
+
*/
|
|
192
|
+
static canvasToImageData(canvas) {
|
|
193
|
+
const ctx = canvas.getContext('2d');
|
|
194
|
+
return ctx ? ctx.getImageData(0, 0, canvas.width, canvas.height) : null;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* 调整图像亮度和对比度
|
|
198
|
+
*
|
|
199
|
+
* @param {ImageData} imageData - 要处理的图像数据
|
|
200
|
+
* @param {number} [brightness=0] - 亮度调整值,正值增加亮度,负值降低亮度,范围建议为-100到100
|
|
201
|
+
* @param {number} [contrast=0] - 对比度调整值,正值增加对比度,负值降低对比度,范围建议为-100到100
|
|
202
|
+
* @returns {ImageData} 处理后的图像数据
|
|
203
|
+
*/
|
|
204
|
+
static adjustBrightnessContrast(imageData, brightness = 0, contrast = 0) {
|
|
205
|
+
const canvas = this.imageDataToCanvas(imageData);
|
|
206
|
+
const ctx = canvas.getContext('2d');
|
|
207
|
+
if (ctx) {
|
|
208
|
+
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
209
|
+
const data = imgData.data;
|
|
210
|
+
// 调整对比度算法
|
|
211
|
+
const factor = (259 * (contrast + 255)) / (255 * (259 - contrast));
|
|
212
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
213
|
+
// 红色
|
|
214
|
+
data[i] = this.truncate(factor * (data[i] - 128) + 128 + brightness);
|
|
215
|
+
// 绿色
|
|
216
|
+
data[i + 1] = this.truncate(factor * (data[i + 1] - 128) + 128 + brightness);
|
|
217
|
+
// 蓝色
|
|
218
|
+
data[i + 2] = this.truncate(factor * (data[i + 2] - 128) + 128 + brightness);
|
|
219
|
+
// Alpha不变
|
|
220
|
+
}
|
|
221
|
+
ctx.putImageData(imgData, 0, 0);
|
|
222
|
+
return imgData;
|
|
223
|
+
}
|
|
224
|
+
return imageData;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* 确保值在0-255范围内
|
|
228
|
+
*
|
|
229
|
+
* @private
|
|
230
|
+
* @param {number} value - 要截断的值
|
|
231
|
+
* @returns {number} 截断后的值,范围为0-255
|
|
232
|
+
*/
|
|
233
|
+
static truncate(value) {
|
|
234
|
+
return Math.min(255, Math.max(0, value));
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* 将彩色图像转换为灰度图像
|
|
238
|
+
*
|
|
239
|
+
* 灰度转换可以简化图像,提高OCR和条形码识别的准确率
|
|
240
|
+
*
|
|
241
|
+
* @param {ImageData} imageData - 要转换的彩色图像
|
|
242
|
+
* @returns {ImageData} 转换后的灰度图像
|
|
243
|
+
*/
|
|
244
|
+
static toGrayscale(imageData) {
|
|
245
|
+
const canvas = this.imageDataToCanvas(imageData);
|
|
246
|
+
const ctx = canvas.getContext('2d');
|
|
247
|
+
if (ctx) {
|
|
248
|
+
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
249
|
+
const data = imgData.data;
|
|
250
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
251
|
+
const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
|
|
252
|
+
data[i] = avg; // 红色
|
|
253
|
+
data[i + 1] = avg; // 绿色
|
|
254
|
+
data[i + 2] = avg; // 蓝色
|
|
255
|
+
// Alpha不变
|
|
256
|
+
}
|
|
257
|
+
ctx.putImageData(imgData, 0, 0);
|
|
258
|
+
return imgData;
|
|
259
|
+
}
|
|
260
|
+
return imageData;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* 调整图像大小
|
|
264
|
+
*
|
|
265
|
+
* @param {ImageData} imageData - 原图像数据
|
|
266
|
+
* @param {number} newWidth - 新宽度
|
|
267
|
+
* @param {number} newHeight - 新高度
|
|
268
|
+
* @returns {ImageData} 调整大小后的图像数据
|
|
269
|
+
*/
|
|
270
|
+
static resize(imageData, newWidth, newHeight) {
|
|
271
|
+
const canvas = document.createElement('canvas');
|
|
272
|
+
canvas.width = newWidth;
|
|
273
|
+
canvas.height = newHeight;
|
|
274
|
+
const ctx = canvas.getContext('2d');
|
|
275
|
+
if (ctx) {
|
|
276
|
+
const tempCanvas = this.imageDataToCanvas(imageData);
|
|
277
|
+
ctx.drawImage(tempCanvas, 0, 0, imageData.width, imageData.height, 0, 0, newWidth, newHeight);
|
|
278
|
+
return ctx.getImageData(0, 0, newWidth, newHeight);
|
|
279
|
+
}
|
|
280
|
+
return imageData;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* 降低图像分辨率以提高处理速度
|
|
284
|
+
*
|
|
285
|
+
* 对于OCR和图像分析,降低分辨率可以在保持识别率的同时大幅提升处理速度
|
|
286
|
+
*
|
|
287
|
+
* @param {ImageData} imageData - 原图像数据
|
|
288
|
+
* @param {number} [maxDimension=1000] - 目标最大尺寸(宽或高)
|
|
289
|
+
* @returns {ImageData} 处理后的图像数据
|
|
290
|
+
*/
|
|
291
|
+
static downsampleForProcessing(imageData, maxDimension = 1000) {
|
|
292
|
+
const { width, height } = imageData;
|
|
293
|
+
// 如果图像尺寸已经小于或等于目标尺寸,则无需处理
|
|
294
|
+
if (width <= maxDimension && height <= maxDimension) {
|
|
295
|
+
return imageData;
|
|
296
|
+
}
|
|
297
|
+
// 计算缩放比例,保持宽高比
|
|
298
|
+
const scale = maxDimension / Math.max(width, height);
|
|
299
|
+
const newWidth = Math.round(width * scale);
|
|
300
|
+
const newHeight = Math.round(height * scale);
|
|
301
|
+
// 调整图像大小
|
|
302
|
+
return this.resize(imageData, newWidth, newHeight);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* 转换图像为Base64格式,方便在Worker线程中传递
|
|
306
|
+
*
|
|
307
|
+
* @param {ImageData} imageData - 原图像数据
|
|
308
|
+
* @returns {string} base64编码的图像数据
|
|
309
|
+
*/
|
|
310
|
+
static imageDataToBase64(imageData) {
|
|
311
|
+
const canvas = this.imageDataToCanvas(imageData);
|
|
312
|
+
return canvas.toDataURL('image/jpeg', 0.7); // 使用较低质量的JPEG格式减少数据量
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* 从Base64字符串还原图像数据
|
|
316
|
+
*
|
|
317
|
+
* @param {string} base64 - base64编码的图像数据
|
|
318
|
+
* @returns {Promise<ImageData>} 还原的图像数据
|
|
319
|
+
*/
|
|
320
|
+
static async base64ToImageData(base64) {
|
|
321
|
+
return new Promise((resolve, reject) => {
|
|
322
|
+
const img = new Image();
|
|
323
|
+
img.onload = () => {
|
|
324
|
+
const canvas = document.createElement('canvas');
|
|
325
|
+
canvas.width = img.width;
|
|
326
|
+
canvas.height = img.height;
|
|
327
|
+
const ctx = canvas.getContext('2d');
|
|
328
|
+
if (!ctx) {
|
|
329
|
+
reject(new Error('无法创建Canvas上下文'));
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
ctx.drawImage(img, 0, 0);
|
|
333
|
+
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
334
|
+
resolve(imageData);
|
|
335
|
+
};
|
|
336
|
+
img.onerror = () => {
|
|
337
|
+
reject(new Error('图像加载失败'));
|
|
338
|
+
};
|
|
339
|
+
img.src = base64;
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* 使用Web Worker并行处理图像
|
|
344
|
+
* 此方法将图像分割为多个部分,并行处理以提高性能
|
|
345
|
+
*
|
|
346
|
+
* @param {ImageData} imageData - 原图像数据
|
|
347
|
+
* @param {Function} processingFunction - 处理函数,接收ImageData返回ImageData
|
|
348
|
+
* @param {number} [chunks=4] - 分割的块数
|
|
349
|
+
* @returns {Promise<ImageData>} 处理后的图像数据
|
|
350
|
+
*/
|
|
351
|
+
static async processImageInParallel(imageData, processingFunction, chunks = 4) {
|
|
352
|
+
// 如果不支持Worker或图像太小,直接处理
|
|
353
|
+
if (typeof Worker === 'undefined' || imageData.width * imageData.height < 100000) {
|
|
354
|
+
return processingFunction(imageData);
|
|
355
|
+
}
|
|
356
|
+
// 创建结果canvas
|
|
357
|
+
const resultCanvas = document.createElement('canvas');
|
|
358
|
+
resultCanvas.width = imageData.width;
|
|
359
|
+
resultCanvas.height = imageData.height;
|
|
360
|
+
const resultCtx = resultCanvas.getContext('2d');
|
|
361
|
+
if (!resultCtx) {
|
|
362
|
+
throw new Error('无法创建Canvas上下文');
|
|
363
|
+
}
|
|
364
|
+
// 根据图像特性确定分割方向和每块大小
|
|
365
|
+
const isWide = imageData.width > imageData.height;
|
|
366
|
+
const chunkSize = Math.floor((isWide ? imageData.width : imageData.height) / chunks);
|
|
367
|
+
// 创建Worker处理每个块
|
|
368
|
+
const promises = [];
|
|
369
|
+
for (let i = 0; i < chunks; i++) {
|
|
370
|
+
const chunkCanvas = document.createElement('canvas');
|
|
371
|
+
const chunkCtx = chunkCanvas.getContext('2d');
|
|
372
|
+
if (!chunkCtx)
|
|
373
|
+
continue;
|
|
374
|
+
let chunkImageData;
|
|
375
|
+
if (isWide) {
|
|
376
|
+
// 水平分割
|
|
377
|
+
const startX = i * chunkSize;
|
|
378
|
+
const width = (i === chunks - 1) ? imageData.width - startX : chunkSize;
|
|
379
|
+
chunkCanvas.width = width;
|
|
380
|
+
chunkCanvas.height = imageData.height;
|
|
381
|
+
// 复制原图像数据到分块
|
|
382
|
+
const tempCanvas = this.imageDataToCanvas(imageData);
|
|
383
|
+
chunkCtx.drawImage(tempCanvas, startX, 0, width, imageData.height, 0, 0, width, imageData.height);
|
|
384
|
+
chunkImageData = chunkCtx.getImageData(0, 0, width, imageData.height);
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
// 垂直分割
|
|
388
|
+
const startY = i * chunkSize;
|
|
389
|
+
const height = (i === chunks - 1) ? imageData.height - startY : chunkSize;
|
|
390
|
+
chunkCanvas.width = imageData.width;
|
|
391
|
+
chunkCanvas.height = height;
|
|
392
|
+
// 复制原图像数据到分块
|
|
393
|
+
const tempCanvas = this.imageDataToCanvas(imageData);
|
|
394
|
+
chunkCtx.drawImage(tempCanvas, 0, startY, imageData.width, height, 0, 0, imageData.width, height);
|
|
395
|
+
chunkImageData = chunkCtx.getImageData(0, 0, imageData.width, height);
|
|
396
|
+
}
|
|
397
|
+
// 使用Worker处理
|
|
398
|
+
const workerCode = `
|
|
399
|
+
self.onmessage = function(e) {
|
|
400
|
+
const imageData = e.data.imageData;
|
|
401
|
+
const processingFunction = ${processingFunction.toString()};
|
|
402
|
+
const result = processingFunction(imageData);
|
|
403
|
+
self.postMessage({ result, index: e.data.index }, [result.data.buffer]);
|
|
404
|
+
}
|
|
405
|
+
`;
|
|
406
|
+
const blob = new Blob([workerCode], { type: 'application/javascript' });
|
|
407
|
+
const workerUrl = URL.createObjectURL(blob);
|
|
408
|
+
const worker = new Worker(workerUrl);
|
|
409
|
+
const promise = new Promise((resolve) => {
|
|
410
|
+
worker.onmessage = function (e) {
|
|
411
|
+
resolve(e.data);
|
|
412
|
+
worker.terminate();
|
|
413
|
+
URL.revokeObjectURL(workerUrl);
|
|
414
|
+
};
|
|
415
|
+
// 传输数据
|
|
416
|
+
worker.postMessage({
|
|
417
|
+
imageData: chunkImageData,
|
|
418
|
+
index: i
|
|
419
|
+
}, [chunkImageData.data.buffer]);
|
|
420
|
+
});
|
|
421
|
+
promises.push(promise);
|
|
422
|
+
}
|
|
423
|
+
// 等待所有Worker完成并组合结果
|
|
424
|
+
const results = await Promise.all(promises);
|
|
425
|
+
// 按索引排序结果
|
|
426
|
+
results.sort((a, b) => a.index - b.index);
|
|
427
|
+
// 将处理后的块绘制到结果canvas
|
|
428
|
+
for (let i = 0; i < results.length; i++) {
|
|
429
|
+
const { result } = results[i];
|
|
430
|
+
const tempCanvas = this.imageDataToCanvas(result);
|
|
431
|
+
if (isWide) {
|
|
432
|
+
const startX = i * chunkSize;
|
|
433
|
+
resultCtx.drawImage(tempCanvas, startX, 0);
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
const startY = i * chunkSize;
|
|
437
|
+
resultCtx.drawImage(tempCanvas, 0, startY);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return resultCtx.getImageData(0, 0, imageData.width, imageData.height);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* @file 性能优化工具类
|
|
446
|
+
* @description 提供节流、防抖、缓存等性能优化功能
|
|
447
|
+
* @module PerformanceUtils
|
|
448
|
+
*/
|
|
449
|
+
/**
|
|
450
|
+
* 节流函数:限制函数在一定时间内只能执行一次
|
|
451
|
+
*
|
|
452
|
+
* @param fn 需要节流的函数
|
|
453
|
+
* @param delay 延迟时间(毫秒)
|
|
454
|
+
* @returns 节流处理后的函数
|
|
455
|
+
*/
|
|
456
|
+
function throttle(fn, delay) {
|
|
457
|
+
let lastCall = 0;
|
|
458
|
+
let timeoutId = null;
|
|
459
|
+
return function (...args) {
|
|
460
|
+
const now = Date.now();
|
|
461
|
+
const remaining = delay - (now - lastCall);
|
|
462
|
+
if (remaining <= 0) {
|
|
463
|
+
if (timeoutId) {
|
|
464
|
+
clearTimeout(timeoutId);
|
|
465
|
+
timeoutId = null;
|
|
466
|
+
}
|
|
467
|
+
lastCall = now;
|
|
468
|
+
fn.apply(this, args);
|
|
469
|
+
}
|
|
470
|
+
else if (!timeoutId) {
|
|
471
|
+
timeoutId = window.setTimeout(() => {
|
|
472
|
+
lastCall = Date.now();
|
|
473
|
+
timeoutId = null;
|
|
474
|
+
fn.apply(this, args);
|
|
475
|
+
}, remaining);
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* LRU缓存类 - 使用最近最少使用策略的缓存实现
|
|
481
|
+
*/
|
|
482
|
+
class LRUCache {
|
|
483
|
+
/**
|
|
484
|
+
* 构造LRU缓存
|
|
485
|
+
* @param maxSize 缓存最大容量
|
|
486
|
+
*/
|
|
487
|
+
constructor(maxSize = 100) {
|
|
488
|
+
this.maxSize = maxSize;
|
|
489
|
+
this.cache = new Map();
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* 获取缓存项
|
|
493
|
+
* @param key 缓存键
|
|
494
|
+
* @returns 缓存值或undefined
|
|
495
|
+
*/
|
|
496
|
+
get(key) {
|
|
497
|
+
if (!this.cache.has(key)) {
|
|
498
|
+
return undefined;
|
|
499
|
+
}
|
|
500
|
+
// 获取值
|
|
501
|
+
const value = this.cache.get(key);
|
|
502
|
+
// 将项移至最新位置(删除后重新添加)
|
|
503
|
+
this.cache.delete(key);
|
|
504
|
+
this.cache.set(key, value);
|
|
505
|
+
return value;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* 设置缓存项
|
|
509
|
+
* @param key 缓存键
|
|
510
|
+
* @param value 缓存值
|
|
511
|
+
*/
|
|
512
|
+
set(key, value) {
|
|
513
|
+
// 如果键已存在,需要先删除
|
|
514
|
+
if (this.cache.has(key)) {
|
|
515
|
+
this.cache.delete(key);
|
|
516
|
+
}
|
|
517
|
+
// 如果缓存已满,移除最老的项
|
|
518
|
+
if (this.cache.size >= this.maxSize) {
|
|
519
|
+
const oldestKey = this.cache.keys().next().value;
|
|
520
|
+
this.cache.delete(oldestKey);
|
|
521
|
+
}
|
|
522
|
+
// 添加新项
|
|
523
|
+
this.cache.set(key, value);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* 删除缓存项
|
|
527
|
+
* @param key 缓存键
|
|
528
|
+
* @returns 是否成功删除
|
|
529
|
+
*/
|
|
530
|
+
delete(key) {
|
|
531
|
+
return this.cache.delete(key);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* 清空缓存
|
|
535
|
+
*/
|
|
536
|
+
clear() {
|
|
537
|
+
this.cache.clear();
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* 获取当前缓存大小
|
|
541
|
+
*/
|
|
542
|
+
get size() {
|
|
543
|
+
return this.cache.size;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* 检查键是否存在
|
|
547
|
+
* @param key 缓存键
|
|
548
|
+
*/
|
|
549
|
+
has(key) {
|
|
550
|
+
return this.cache.has(key);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* 图像指纹计算函数 - 用于检测相同或相似图像
|
|
555
|
+
*
|
|
556
|
+
* @param imageData 图像数据
|
|
557
|
+
* @param size 指纹尺寸(默认8x8)
|
|
558
|
+
* @returns 图像指纹字符串
|
|
559
|
+
*/
|
|
560
|
+
function calculateImageFingerprint(imageData, size = 8) {
|
|
561
|
+
// 1. 缩小图像到指定尺寸
|
|
562
|
+
const canvas = document.createElement('canvas');
|
|
563
|
+
canvas.width = size;
|
|
564
|
+
canvas.height = size;
|
|
565
|
+
const ctx = canvas.getContext('2d');
|
|
566
|
+
if (!ctx) {
|
|
567
|
+
return '';
|
|
568
|
+
}
|
|
569
|
+
// 创建一个临时canvas来绘制原始imageData
|
|
570
|
+
const tempCanvas = document.createElement('canvas');
|
|
571
|
+
tempCanvas.width = imageData.width;
|
|
572
|
+
tempCanvas.height = imageData.height;
|
|
573
|
+
const tempCtx = tempCanvas.getContext('2d');
|
|
574
|
+
if (!tempCtx) {
|
|
575
|
+
return '';
|
|
576
|
+
}
|
|
577
|
+
tempCtx.putImageData(imageData, 0, 0);
|
|
578
|
+
// 缩小到目标尺寸
|
|
579
|
+
ctx.drawImage(tempCanvas, 0, 0, imageData.width, imageData.height, 0, 0, size, size);
|
|
580
|
+
// 2. 转换为灰度
|
|
581
|
+
const smallImgData = ctx.getImageData(0, 0, size, size);
|
|
582
|
+
const grayValues = [];
|
|
583
|
+
for (let i = 0; i < smallImgData.data.length; i += 4) {
|
|
584
|
+
const r = smallImgData.data[i];
|
|
585
|
+
const g = smallImgData.data[i + 1];
|
|
586
|
+
const b = smallImgData.data[i + 2];
|
|
587
|
+
// 转为灰度: 0.299r + 0.587g + 0.114b
|
|
588
|
+
const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
|
|
589
|
+
grayValues.push(gray);
|
|
590
|
+
}
|
|
591
|
+
// 3. 计算平均值
|
|
592
|
+
const avg = grayValues.reduce((sum, val) => sum + val, 0) / grayValues.length;
|
|
593
|
+
// 4. 比较每个像素与平均值,生成二进制指纹
|
|
594
|
+
let fingerprint = '';
|
|
595
|
+
for (const gray of grayValues) {
|
|
596
|
+
fingerprint += gray >= avg ? '1' : '0';
|
|
597
|
+
}
|
|
598
|
+
return fingerprint;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* @file 身份证检测模块
|
|
603
|
+
* @description 提供自动检测和定位图像中的身份证功能
|
|
604
|
+
* @module IDCardDetector
|
|
605
|
+
*/
|
|
606
|
+
/**
|
|
607
|
+
* 身份证检测器类
|
|
608
|
+
*
|
|
609
|
+
* 通过图像处理和计算机视觉技术,实时检测视频流中的身份证,并提取身份证区域
|
|
610
|
+
* 注意:当前实现是简化版,实际项目中建议使用OpenCV.js进行更精确的检测
|
|
611
|
+
*
|
|
612
|
+
* @example
|
|
613
|
+
* ```typescript
|
|
614
|
+
* // 创建身份证检测器
|
|
615
|
+
* const detector = new IDCardDetector((result) => {
|
|
616
|
+
* if (result.success && result.croppedImage) {
|
|
617
|
+
* console.log('检测到身份证!');
|
|
618
|
+
* // 对裁剪出的身份证图像进行处理
|
|
619
|
+
* processIDCardImage(result.croppedImage);
|
|
620
|
+
* }
|
|
621
|
+
* });
|
|
622
|
+
*
|
|
623
|
+
* // 启动检测
|
|
624
|
+
* const videoElement = document.getElementById('video') as HTMLVideoElement;
|
|
625
|
+
* await detector.start(videoElement);
|
|
626
|
+
*
|
|
627
|
+
* // 停止检测
|
|
628
|
+
* detector.stop();
|
|
629
|
+
* ```
|
|
630
|
+
*/
|
|
631
|
+
class IDCardDetector {
|
|
632
|
+
/**
|
|
633
|
+
* 创建身份证检测器实例
|
|
634
|
+
*
|
|
635
|
+
* @param options 身份证检测器配置选项,或者检测回调函数
|
|
636
|
+
*/
|
|
637
|
+
constructor(options) {
|
|
638
|
+
this.detecting = false;
|
|
639
|
+
this.detectTimer = null;
|
|
640
|
+
this.frameCount = 0;
|
|
641
|
+
this.lastDetectionTime = 0;
|
|
642
|
+
this.camera = new Camera();
|
|
643
|
+
if (typeof options === 'function') {
|
|
644
|
+
// 兼容旧的构造函数方式
|
|
645
|
+
this.onDetected = options;
|
|
646
|
+
this.options = {
|
|
647
|
+
detectionInterval: 200,
|
|
648
|
+
maxImageDimension: 800,
|
|
649
|
+
enableCache: true,
|
|
650
|
+
cacheSize: 20,
|
|
651
|
+
logger: console.log
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
else if (options) {
|
|
655
|
+
// 使用新的选项对象方式
|
|
656
|
+
this.options = {
|
|
657
|
+
detectionInterval: 200,
|
|
658
|
+
maxImageDimension: 800,
|
|
659
|
+
enableCache: true,
|
|
660
|
+
cacheSize: 20,
|
|
661
|
+
logger: console.log,
|
|
662
|
+
...options
|
|
663
|
+
};
|
|
664
|
+
this.onDetected = options.onDetection;
|
|
665
|
+
this.onError = options.onError;
|
|
666
|
+
}
|
|
667
|
+
else {
|
|
668
|
+
this.options = {
|
|
669
|
+
detectionInterval: 200,
|
|
670
|
+
maxImageDimension: 800,
|
|
671
|
+
enableCache: true,
|
|
672
|
+
cacheSize: 20,
|
|
673
|
+
logger: console.log
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
this.detectionInterval = this.options.detectionInterval;
|
|
677
|
+
this.maxImageDimension = this.options.maxImageDimension;
|
|
678
|
+
// 初始化结果缓存
|
|
679
|
+
this.resultCache = new LRUCache(this.options.cacheSize);
|
|
680
|
+
// 创建节流版本的检测函数
|
|
681
|
+
this.throttledDetect = throttle(this.performDetection.bind(this), this.detectionInterval);
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* 启动身份证检测
|
|
685
|
+
*
|
|
686
|
+
* 初始化相机并开始连续检测视频帧中的身份证
|
|
687
|
+
*
|
|
688
|
+
* @param {HTMLVideoElement} videoElement - 用于显示相机画面的video元素
|
|
689
|
+
* @returns {Promise<void>} 启动完成的Promise
|
|
690
|
+
*/
|
|
691
|
+
async start(videoElement) {
|
|
692
|
+
await this.camera.initialize(videoElement);
|
|
693
|
+
this.detecting = true;
|
|
694
|
+
this.frameCount = 0;
|
|
695
|
+
this.lastDetectionTime = 0;
|
|
696
|
+
this.detect();
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* 停止身份证检测
|
|
700
|
+
*/
|
|
701
|
+
stop() {
|
|
702
|
+
this.detecting = false;
|
|
703
|
+
if (this.detectTimer !== null) {
|
|
704
|
+
cancelAnimationFrame(this.detectTimer);
|
|
705
|
+
this.detectTimer = null;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* 持续检测视频帧
|
|
710
|
+
*
|
|
711
|
+
* @private
|
|
712
|
+
*/
|
|
713
|
+
detect() {
|
|
714
|
+
if (!this.detecting)
|
|
715
|
+
return;
|
|
716
|
+
this.detectTimer = requestAnimationFrame(() => {
|
|
717
|
+
try {
|
|
718
|
+
this.frameCount++;
|
|
719
|
+
const now = performance.now();
|
|
720
|
+
// 帧率控制 - 只有满足时间间隔的帧才进行检测
|
|
721
|
+
// 这样可以显著减少CPU使用率,同时保持良好的用户体验
|
|
722
|
+
if (this.frameCount % 3 === 0 || now - this.lastDetectionTime >= this.detectionInterval) {
|
|
723
|
+
this.throttledDetect();
|
|
724
|
+
this.lastDetectionTime = now;
|
|
725
|
+
}
|
|
726
|
+
// 继续下一帧检测
|
|
727
|
+
this.detect();
|
|
728
|
+
}
|
|
729
|
+
catch (error) {
|
|
730
|
+
if (this.onError) {
|
|
731
|
+
this.onError(error);
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
console.error('身份证检测错误:', error);
|
|
735
|
+
}
|
|
736
|
+
// 出错后延迟重试
|
|
737
|
+
setTimeout(() => {
|
|
738
|
+
if (this.detecting) {
|
|
739
|
+
this.detect();
|
|
740
|
+
}
|
|
741
|
+
}, 1000);
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* 执行单帧检测
|
|
747
|
+
*
|
|
748
|
+
* @private
|
|
749
|
+
*/
|
|
750
|
+
async performDetection() {
|
|
751
|
+
if (!this.detecting || !this.camera)
|
|
752
|
+
return;
|
|
753
|
+
// 获取当前视频帧
|
|
754
|
+
const frame = this.camera.captureFrame();
|
|
755
|
+
if (!frame)
|
|
756
|
+
return;
|
|
757
|
+
// 检查缓存
|
|
758
|
+
if (this.options.enableCache) {
|
|
759
|
+
const fingerprint = calculateImageFingerprint(frame, 16); // 使用更大的尺寸提高特征区分度
|
|
760
|
+
const cachedResult = this.resultCache.get(fingerprint);
|
|
761
|
+
if (cachedResult) {
|
|
762
|
+
this.options.logger?.('使用缓存的检测结果');
|
|
763
|
+
// 使用缓存结果,但更新图像数据以确保最新
|
|
764
|
+
const updatedResult = {
|
|
765
|
+
...cachedResult,
|
|
766
|
+
imageData: frame
|
|
767
|
+
};
|
|
768
|
+
if (this.onDetected) {
|
|
769
|
+
this.onDetected(updatedResult);
|
|
770
|
+
}
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
// 降低分辨率以提高性能
|
|
775
|
+
const downsampledFrame = ImageProcessor.downsampleForProcessing(frame, this.maxImageDimension);
|
|
776
|
+
try {
|
|
777
|
+
// 检测身份证
|
|
778
|
+
const result = await this.detectIDCard(downsampledFrame);
|
|
779
|
+
// 如果检测成功,将原始图像添加到结果中
|
|
780
|
+
if (result.success) {
|
|
781
|
+
result.imageData = frame;
|
|
782
|
+
// 缓存结果
|
|
783
|
+
if (this.options.enableCache) {
|
|
784
|
+
const fingerprint = calculateImageFingerprint(frame, 16);
|
|
785
|
+
this.resultCache.set(fingerprint, result);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
// 处理检测结果
|
|
789
|
+
if (this.onDetected) {
|
|
790
|
+
this.onDetected(result);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
catch (error) {
|
|
794
|
+
if (this.onError) {
|
|
795
|
+
this.onError(error);
|
|
796
|
+
}
|
|
797
|
+
else {
|
|
798
|
+
console.error('身份证检测错误:', error);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* 检测图像中的身份证
|
|
804
|
+
*
|
|
805
|
+
* @private
|
|
806
|
+
* @param {ImageData} imageData - 要分析的图像数据
|
|
807
|
+
* @returns {Promise<DetectionResult>} 检测结果
|
|
808
|
+
*/
|
|
809
|
+
async detectIDCard(imageData) {
|
|
810
|
+
// 1. 图像预处理
|
|
811
|
+
ImageProcessor.toGrayscale(imageData);
|
|
812
|
+
// 2. 检测矩形和边缘(简化版实现)
|
|
813
|
+
// 注意:实际应用中应使用OpenCV.js或其他计算机视觉库进行更精确的检测
|
|
814
|
+
// 此处仅作为概念性实现,使用基本矩形检测逻辑
|
|
815
|
+
// 模拟检测过程,随机判断是否找到身份证
|
|
816
|
+
// 在实际应用中,此处应当实现实际的计算机视觉算法
|
|
817
|
+
const detectionResult = {
|
|
818
|
+
success: Math.random() > 0.3, // 70%的概率成功检测到
|
|
819
|
+
message: '身份证检测完成'
|
|
820
|
+
};
|
|
821
|
+
if (detectionResult.success) {
|
|
822
|
+
// 模拟一个身份证矩形区域
|
|
823
|
+
const width = imageData.width;
|
|
824
|
+
const height = imageData.height;
|
|
825
|
+
// 大致的身份证区域(按比例)
|
|
826
|
+
const rectWidth = Math.round(width * 0.7);
|
|
827
|
+
const rectHeight = Math.round(rectWidth * 0.618); // 身份证是黄金比例
|
|
828
|
+
const rectX = Math.round((width - rectWidth) / 2);
|
|
829
|
+
const rectY = Math.round((height - rectHeight) / 2);
|
|
830
|
+
// 添加四个角点
|
|
831
|
+
detectionResult.corners = [
|
|
832
|
+
{ x: rectX, y: rectY },
|
|
833
|
+
{ x: rectX + rectWidth, y: rectY },
|
|
834
|
+
{ x: rectX + rectWidth, y: rectY + rectHeight },
|
|
835
|
+
{ x: rectX, y: rectY + rectHeight }
|
|
836
|
+
];
|
|
837
|
+
// 添加边界框
|
|
838
|
+
detectionResult.boundingBox = {
|
|
839
|
+
x: rectX,
|
|
840
|
+
y: rectY,
|
|
841
|
+
width: rectWidth,
|
|
842
|
+
height: rectHeight
|
|
843
|
+
};
|
|
844
|
+
// 裁剪身份证图像
|
|
845
|
+
const canvas = document.createElement('canvas');
|
|
846
|
+
canvas.width = rectWidth;
|
|
847
|
+
canvas.height = rectHeight;
|
|
848
|
+
const ctx = canvas.getContext('2d');
|
|
849
|
+
if (ctx) {
|
|
850
|
+
const tempCanvas = ImageProcessor.imageDataToCanvas(imageData);
|
|
851
|
+
ctx.drawImage(tempCanvas, rectX, rectY, rectWidth, rectHeight, 0, 0, rectWidth, rectHeight);
|
|
852
|
+
detectionResult.croppedImage = ctx.getImageData(0, 0, rectWidth, rectHeight);
|
|
853
|
+
}
|
|
854
|
+
// 设置置信度
|
|
855
|
+
detectionResult.confidence = 0.7 + Math.random() * 0.3;
|
|
856
|
+
}
|
|
857
|
+
return detectionResult;
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* 清除检测结果缓存
|
|
861
|
+
*/
|
|
862
|
+
clearCache() {
|
|
863
|
+
this.resultCache.clear();
|
|
864
|
+
this.options.logger?.('检测结果缓存已清除');
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* 释放资源
|
|
868
|
+
*/
|
|
869
|
+
dispose() {
|
|
870
|
+
this.stop();
|
|
871
|
+
this.camera.release();
|
|
872
|
+
this.resultCache.clear();
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* @file Web Worker辅助工具类
|
|
878
|
+
* @description 提供Worker线程管理功能,用于将计算密集型任务移至后台线程
|
|
879
|
+
* @module WorkerUtils
|
|
880
|
+
*/
|
|
881
|
+
/**
|
|
882
|
+
* 创建Worker线程并处理消息通信
|
|
883
|
+
*
|
|
884
|
+
* @param workerFunction 要在Worker中执行的函数
|
|
885
|
+
* @returns 返回包含发送消息方法的Worker控制对象
|
|
886
|
+
*/
|
|
887
|
+
function createWorker(workerFunction) {
|
|
888
|
+
// 将函数转换为字符串,然后创建一个Blob URL
|
|
889
|
+
const workerCode = `
|
|
890
|
+
self.onmessage = async function(e) {
|
|
891
|
+
try {
|
|
892
|
+
const result = await (${workerFunction.toString()})(e.data);
|
|
893
|
+
self.postMessage({ success: true, result });
|
|
894
|
+
} catch (error) {
|
|
895
|
+
self.postMessage({
|
|
896
|
+
success: false,
|
|
897
|
+
error: { message: error.message, stack: error.stack }
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
`;
|
|
902
|
+
const blob = new Blob([workerCode], { type: 'application/javascript' });
|
|
903
|
+
const workerUrl = URL.createObjectURL(blob);
|
|
904
|
+
const worker = new Worker(workerUrl);
|
|
905
|
+
// 创建一个映射来存储待解析的Promise
|
|
906
|
+
const promiseMap = new Map();
|
|
907
|
+
let messageCounter = 0;
|
|
908
|
+
worker.onmessage = (e) => {
|
|
909
|
+
// 释放Blob URL
|
|
910
|
+
if (promiseMap.size === 0) {
|
|
911
|
+
URL.revokeObjectURL(workerUrl);
|
|
912
|
+
}
|
|
913
|
+
const { id, success, result, error } = e.data;
|
|
914
|
+
const promiseHandlers = promiseMap.get(id);
|
|
915
|
+
if (promiseHandlers) {
|
|
916
|
+
promiseMap.delete(id);
|
|
917
|
+
if (success) {
|
|
918
|
+
promiseHandlers.resolve(result);
|
|
919
|
+
}
|
|
920
|
+
else {
|
|
921
|
+
const workerError = new Error(error.message);
|
|
922
|
+
workerError.stack = error.stack;
|
|
923
|
+
promiseHandlers.reject(workerError);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
return {
|
|
928
|
+
postMessage: (data) => {
|
|
929
|
+
return new Promise((resolve, reject) => {
|
|
930
|
+
const id = messageCounter++;
|
|
931
|
+
promiseMap.set(id, { resolve, reject });
|
|
932
|
+
worker.postMessage({ id, data });
|
|
933
|
+
});
|
|
934
|
+
},
|
|
935
|
+
terminate: () => {
|
|
936
|
+
worker.terminate();
|
|
937
|
+
promiseMap.clear();
|
|
938
|
+
URL.revokeObjectURL(workerUrl);
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* 判断浏览器是否支持Web Workers
|
|
944
|
+
*
|
|
945
|
+
* @returns 是否支持Web Workers
|
|
946
|
+
*/
|
|
947
|
+
function isWorkerSupported() {
|
|
948
|
+
return typeof Worker !== 'undefined';
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* @file OCR Worker处理模块
|
|
953
|
+
* @description 用于在Web Worker中执行OCR处理
|
|
954
|
+
* @module OCRWorker
|
|
955
|
+
*/
|
|
956
|
+
/**
|
|
957
|
+
* 在Web Worker中执行OCR处理的函数
|
|
958
|
+
*
|
|
959
|
+
* 该函数用于在使用 createWorker 创建的 Worker 中执行
|
|
960
|
+
*
|
|
961
|
+
* @param input OCR处理输入数据
|
|
962
|
+
* @returns OCR处理结果
|
|
963
|
+
*/
|
|
964
|
+
async function processOCRInWorker(input) {
|
|
965
|
+
// 计时开始
|
|
966
|
+
const startTime = performance.now();
|
|
967
|
+
// 加载Tesseract.js (Worker 环境下动态导入)
|
|
968
|
+
const { createWorker } = await import('tesseract.js');
|
|
969
|
+
// 创建OCR Worker
|
|
970
|
+
const worker = createWorker(input.tessWorkerOptions || {
|
|
971
|
+
logger: (m) => console.log(m)
|
|
972
|
+
});
|
|
973
|
+
try {
|
|
974
|
+
// 初始化OCR引擎
|
|
975
|
+
await worker.load();
|
|
976
|
+
await worker.loadLanguage('chi_sim');
|
|
977
|
+
await worker.initialize('chi_sim');
|
|
978
|
+
await worker.setParameters({
|
|
979
|
+
tessedit_char_whitelist: '0123456789X-年月日一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz民族汉族满族回族维吾尔族藏族苗族彝族壮族朝鲜族侗族瑶族白族土家族哈尼族哈萨克族傣族黎族傈僳族佤族高山族拉祜族水族东乡族钠西族景颇族柯尔克孜族士族达斡尔族仫佬族羌族布朗族撒拉族毛南族仡佬族锡伯族阿昌族普米族塔吉克族怒族乌孜别克族俄罗斯族鄂温克族德昂族保安族裕固族京族塔塔尔族独龙族鄂伦春族赫哲族门巴族珞巴族基诺族男女性别住址出生公民身份号码签发机关有效期'
|
|
980
|
+
});
|
|
981
|
+
// 识别图像
|
|
982
|
+
const { data } = await worker.recognize(input.imageBase64);
|
|
983
|
+
// 解析识别结果
|
|
984
|
+
const idCardInfo = parseIDCardText(data.text);
|
|
985
|
+
// 处理完成后终止worker
|
|
986
|
+
await worker.terminate();
|
|
987
|
+
// 计算处理时间
|
|
988
|
+
const processingTime = performance.now() - startTime;
|
|
989
|
+
// 返回处理结果
|
|
990
|
+
return {
|
|
991
|
+
idCardInfo,
|
|
992
|
+
processingTime
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
catch (error) {
|
|
996
|
+
// 确保资源被释放
|
|
997
|
+
await worker.terminate();
|
|
998
|
+
throw error;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* 解析身份证文本信息
|
|
1003
|
+
*
|
|
1004
|
+
* 从OCR识别到的文本中提取结构化的身份证信息
|
|
1005
|
+
*
|
|
1006
|
+
* @private
|
|
1007
|
+
* @param {string} text - OCR识别到的文本
|
|
1008
|
+
* @returns {IDCardInfo} 提取到的身份证信息对象
|
|
1009
|
+
*/
|
|
1010
|
+
function parseIDCardText(text) {
|
|
1011
|
+
const info = {};
|
|
1012
|
+
// 拆分为行
|
|
1013
|
+
const lines = text.split('\n').filter(line => line.trim());
|
|
1014
|
+
// 解析身份证号码(最容易识别的部分)
|
|
1015
|
+
const idNumberRegex = /(\d{17}[\dX])/;
|
|
1016
|
+
const idNumberMatch = text.match(idNumberRegex);
|
|
1017
|
+
if (idNumberMatch) {
|
|
1018
|
+
info.idNumber = idNumberMatch[1];
|
|
1019
|
+
}
|
|
1020
|
+
// 解析姓名
|
|
1021
|
+
for (const line of lines) {
|
|
1022
|
+
if (line.includes('姓名') || line.length < 10 && line.length > 1 && !/\d/.test(line)) {
|
|
1023
|
+
info.name = line.replace('姓名', '').trim();
|
|
1024
|
+
break;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
// 解析性别和民族
|
|
1028
|
+
const genderNationalityRegex = /(男|女).*(族)/;
|
|
1029
|
+
const genderMatch = text.match(genderNationalityRegex);
|
|
1030
|
+
if (genderMatch) {
|
|
1031
|
+
info.gender = genderMatch[1];
|
|
1032
|
+
const nationalityText = genderMatch[0];
|
|
1033
|
+
info.nationality = nationalityText.substring(nationalityText.indexOf(genderMatch[1]) + 1).trim();
|
|
1034
|
+
}
|
|
1035
|
+
// 解析出生日期
|
|
1036
|
+
const birthDateRegex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
|
|
1037
|
+
const birthDateMatch = text.match(birthDateRegex);
|
|
1038
|
+
if (birthDateMatch) {
|
|
1039
|
+
info.birthDate = `${birthDateMatch[1]}-${birthDateMatch[2]}-${birthDateMatch[3]}`;
|
|
1040
|
+
}
|
|
1041
|
+
// 解析地址
|
|
1042
|
+
const addressRegex = /住址([\s\S]*?)公民身份号码/;
|
|
1043
|
+
const addressMatch = text.match(addressRegex);
|
|
1044
|
+
if (addressMatch) {
|
|
1045
|
+
info.address = addressMatch[1].replace(/\n/g, '').trim();
|
|
1046
|
+
}
|
|
1047
|
+
// 解析签发机关
|
|
1048
|
+
const authorityRegex = /签发机关([\s\S]*?)有效期/;
|
|
1049
|
+
const authorityMatch = text.match(authorityRegex);
|
|
1050
|
+
if (authorityMatch) {
|
|
1051
|
+
info.issuingAuthority = authorityMatch[1].replace(/\n/g, '').trim();
|
|
1052
|
+
}
|
|
1053
|
+
// 解析有效期限
|
|
1054
|
+
const validPeriodRegex = /有效期限([\s\S]*?)(-|至)/;
|
|
1055
|
+
const validPeriodMatch = text.match(validPeriodRegex);
|
|
1056
|
+
if (validPeriodMatch) {
|
|
1057
|
+
info.validPeriod = validPeriodMatch[0].replace('有效期限', '').trim();
|
|
1058
|
+
}
|
|
1059
|
+
return info;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/**
|
|
1063
|
+
* @file OCR处理模块
|
|
1064
|
+
* @description 提供身份证文字识别和信息提取功能
|
|
1065
|
+
* @module OCRProcessor
|
|
1066
|
+
*/
|
|
1067
|
+
/**
|
|
1068
|
+
* OCR处理器类
|
|
1069
|
+
*
|
|
1070
|
+
* 使用Tesseract.js实现对身份证图像的OCR文字识别和信息提取功能
|
|
1071
|
+
*
|
|
1072
|
+
* @example
|
|
1073
|
+
* ```typescript
|
|
1074
|
+
* // 创建OCR处理器
|
|
1075
|
+
* const ocrProcessor = new OCRProcessor();
|
|
1076
|
+
*
|
|
1077
|
+
* // 初始化OCR引擎
|
|
1078
|
+
* await ocrProcessor.initialize();
|
|
1079
|
+
*
|
|
1080
|
+
* // 处理身份证图像
|
|
1081
|
+
* const idInfo = await ocrProcessor.processIDCard(idCardImageData);
|
|
1082
|
+
* console.log('识别到的身份证信息:', idInfo);
|
|
1083
|
+
*
|
|
1084
|
+
* // 使用结束后释放资源
|
|
1085
|
+
* await ocrProcessor.terminate();
|
|
1086
|
+
* ```
|
|
1087
|
+
*/
|
|
1088
|
+
class OCRProcessor {
|
|
1089
|
+
/**
|
|
1090
|
+
* 创建OCR处理器实例
|
|
1091
|
+
*
|
|
1092
|
+
* @param options OCR处理器选项
|
|
1093
|
+
*/
|
|
1094
|
+
constructor(options = {}) {
|
|
1095
|
+
this.worker = null;
|
|
1096
|
+
this.ocrWorker = null;
|
|
1097
|
+
this.initialized = false;
|
|
1098
|
+
this.options = {
|
|
1099
|
+
useWorker: isWorkerSupported(),
|
|
1100
|
+
enableCache: true,
|
|
1101
|
+
cacheSize: 50,
|
|
1102
|
+
maxImageDimension: 1000,
|
|
1103
|
+
logger: console.log,
|
|
1104
|
+
...options
|
|
1105
|
+
};
|
|
1106
|
+
// 初始化缓存
|
|
1107
|
+
this.resultCache = new LRUCache(this.options.cacheSize);
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* 初始化OCR引擎
|
|
1111
|
+
*
|
|
1112
|
+
* 加载Tesseract OCR引擎和中文简体语言包,并设置适合身份证识别的参数
|
|
1113
|
+
*
|
|
1114
|
+
* @returns {Promise<void>} 初始化完成的Promise
|
|
1115
|
+
*/
|
|
1116
|
+
async initialize() {
|
|
1117
|
+
if (this.initialized)
|
|
1118
|
+
return;
|
|
1119
|
+
if (this.options.useWorker) {
|
|
1120
|
+
// 使用自定义Worker线程处理OCR
|
|
1121
|
+
this.ocrWorker = createWorker(processOCRInWorker);
|
|
1122
|
+
this.initialized = true;
|
|
1123
|
+
this.options.logger?.('OCR Worker 初始化完成');
|
|
1124
|
+
}
|
|
1125
|
+
else {
|
|
1126
|
+
// 使用主线程处理OCR
|
|
1127
|
+
this.worker = tesseract_js.createWorker({
|
|
1128
|
+
logger: this.options.logger
|
|
1129
|
+
});
|
|
1130
|
+
await this.worker.load();
|
|
1131
|
+
await this.worker.loadLanguage('chi_sim');
|
|
1132
|
+
await this.worker.initialize('chi_sim');
|
|
1133
|
+
await this.worker.setParameters({
|
|
1134
|
+
tessedit_char_whitelist: '0123456789X-年月日一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz民族汉族满族回族维吾尔族藏族苗族彝族壮族朝鲜族侗族瑶族白族土家族哈尼族哈萨克族傣族黎族傈僳族佤族高山族拉祜族水族东乡族钠西族景颇族柯尔克孜族士族达斡尔族仫佬族羌族布朗族撒拉族毛南族仡佬族锡伯族阿昌族普米族塔吉克族怒族乌孜别克族俄罗斯族鄂温克族德昂族保安族裕固族京族塔塔尔族独龙族鄂伦春族赫哲族门巴族珞巴族基诺族男女性别住址出生公民身份号码签发机关有效期'
|
|
1135
|
+
});
|
|
1136
|
+
this.initialized = true;
|
|
1137
|
+
this.options.logger?.('OCR引擎初始化完成');
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* 处理身份证图像并提取信息
|
|
1142
|
+
* @param imageData 要处理的身份证图像数据
|
|
1143
|
+
* @returns 提取的身份证信息
|
|
1144
|
+
*/
|
|
1145
|
+
async processIDCard(imageData) {
|
|
1146
|
+
if (!this.initialized) {
|
|
1147
|
+
await this.initialize();
|
|
1148
|
+
}
|
|
1149
|
+
// 计算图像指纹,用于缓存查找
|
|
1150
|
+
if (this.options.enableCache) {
|
|
1151
|
+
const fingerprint = calculateImageFingerprint(imageData);
|
|
1152
|
+
// 检查缓存中是否有结果
|
|
1153
|
+
const cachedResult = this.resultCache.get(fingerprint);
|
|
1154
|
+
if (cachedResult) {
|
|
1155
|
+
this.options.logger?.('使用缓存的OCR结果');
|
|
1156
|
+
return cachedResult;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
// 图像预处理:降低分辨率和增强对比度
|
|
1160
|
+
const downsampledImage = ImageProcessor.downsampleForProcessing(imageData, this.options.maxImageDimension);
|
|
1161
|
+
const enhancedImage = ImageProcessor.adjustBrightnessContrast(downsampledImage, 15, 25);
|
|
1162
|
+
// OCR识别
|
|
1163
|
+
try {
|
|
1164
|
+
let idCardInfo;
|
|
1165
|
+
if (this.options.useWorker && this.ocrWorker) {
|
|
1166
|
+
// 使用Worker线程处理
|
|
1167
|
+
const base64Image = ImageProcessor.imageDataToBase64(enhancedImage);
|
|
1168
|
+
const result = await this.ocrWorker.postMessage({
|
|
1169
|
+
imageBase64: base64Image,
|
|
1170
|
+
tessWorkerOptions: {
|
|
1171
|
+
logger: this.options.logger
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
1174
|
+
idCardInfo = result.idCardInfo;
|
|
1175
|
+
this.options.logger?.(`OCR处理完成,用时: ${result.processingTime.toFixed(2)}ms`);
|
|
1176
|
+
}
|
|
1177
|
+
else {
|
|
1178
|
+
// 使用主线程处理
|
|
1179
|
+
const startTime = performance.now();
|
|
1180
|
+
// 转换ImageData为Canvas
|
|
1181
|
+
const canvas = ImageProcessor.imageDataToCanvas(enhancedImage);
|
|
1182
|
+
const { data } = await this.worker.recognize(canvas);
|
|
1183
|
+
// 解析身份证信息
|
|
1184
|
+
idCardInfo = this.parseIDCardText(data.text);
|
|
1185
|
+
const processingTime = performance.now() - startTime;
|
|
1186
|
+
this.options.logger?.(`OCR处理完成,用时: ${processingTime.toFixed(2)}ms`);
|
|
1187
|
+
}
|
|
1188
|
+
// 缓存结果
|
|
1189
|
+
if (this.options.enableCache) {
|
|
1190
|
+
const fingerprint = calculateImageFingerprint(imageData);
|
|
1191
|
+
this.resultCache.set(fingerprint, idCardInfo);
|
|
1192
|
+
}
|
|
1193
|
+
return idCardInfo;
|
|
1194
|
+
}
|
|
1195
|
+
catch (error) {
|
|
1196
|
+
this.options.logger?.(`OCR识别错误: ${error}`);
|
|
1197
|
+
return {};
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* 解析身份证文本信息
|
|
1202
|
+
*
|
|
1203
|
+
* 从OCR识别到的文本中提取结构化的身份证信息
|
|
1204
|
+
*
|
|
1205
|
+
* @private
|
|
1206
|
+
* @param {string} text - OCR识别到的文本
|
|
1207
|
+
* @returns {IDCardInfo} 提取到的身份证信息对象
|
|
1208
|
+
*/
|
|
1209
|
+
parseIDCardText(text) {
|
|
1210
|
+
const info = {};
|
|
1211
|
+
// 拆分为行
|
|
1212
|
+
const lines = text.split('\n').filter(line => line.trim());
|
|
1213
|
+
// 解析身份证号码(最容易识别的部分)
|
|
1214
|
+
const idNumberRegex = /(\d{17}[\dX])/;
|
|
1215
|
+
const idNumberMatch = text.match(idNumberRegex);
|
|
1216
|
+
if (idNumberMatch) {
|
|
1217
|
+
info.idNumber = idNumberMatch[1];
|
|
1218
|
+
}
|
|
1219
|
+
// 解析姓名
|
|
1220
|
+
for (const line of lines) {
|
|
1221
|
+
if (line.includes('姓名') || line.length < 10 && line.length > 1 && !/\d/.test(line)) {
|
|
1222
|
+
info.name = line.replace('姓名', '').trim();
|
|
1223
|
+
break;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
// 解析性别和民族
|
|
1227
|
+
const genderNationalityRegex = /(男|女).*(族)/;
|
|
1228
|
+
const genderMatch = text.match(genderNationalityRegex);
|
|
1229
|
+
if (genderMatch) {
|
|
1230
|
+
info.gender = genderMatch[1];
|
|
1231
|
+
const nationalityText = genderMatch[0];
|
|
1232
|
+
info.nationality = nationalityText.substring(nationalityText.indexOf(genderMatch[1]) + 1).trim();
|
|
1233
|
+
}
|
|
1234
|
+
// 解析出生日期
|
|
1235
|
+
const birthDateRegex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
|
|
1236
|
+
const birthDateMatch = text.match(birthDateRegex);
|
|
1237
|
+
if (birthDateMatch) {
|
|
1238
|
+
info.birthDate = `${birthDateMatch[1]}-${birthDateMatch[2]}-${birthDateMatch[3]}`;
|
|
1239
|
+
}
|
|
1240
|
+
// 解析地址
|
|
1241
|
+
const addressRegex = /住址([\s\S]*?)公民身份号码/;
|
|
1242
|
+
const addressMatch = text.match(addressRegex);
|
|
1243
|
+
if (addressMatch) {
|
|
1244
|
+
info.address = addressMatch[1].replace(/\n/g, '').trim();
|
|
1245
|
+
}
|
|
1246
|
+
// 解析签发机关
|
|
1247
|
+
const authorityRegex = /签发机关([\s\S]*?)有效期/;
|
|
1248
|
+
const authorityMatch = text.match(authorityRegex);
|
|
1249
|
+
if (authorityMatch) {
|
|
1250
|
+
info.issuingAuthority = authorityMatch[1].replace(/\n/g, '').trim();
|
|
1251
|
+
}
|
|
1252
|
+
// 解析有效期限
|
|
1253
|
+
const validPeriodRegex = /有效期限([\s\S]*?)(-|至)/;
|
|
1254
|
+
const validPeriodMatch = text.match(validPeriodRegex);
|
|
1255
|
+
if (validPeriodMatch) {
|
|
1256
|
+
info.validPeriod = validPeriodMatch[0].replace('有效期限', '').trim();
|
|
1257
|
+
}
|
|
1258
|
+
return info;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* 清除结果缓存
|
|
1262
|
+
*/
|
|
1263
|
+
clearCache() {
|
|
1264
|
+
this.resultCache.clear();
|
|
1265
|
+
this.options.logger?.('OCR结果缓存已清除');
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* 终止OCR引擎并释放资源
|
|
1269
|
+
*
|
|
1270
|
+
* @returns {Promise<void>} 终止完成的Promise
|
|
1271
|
+
*/
|
|
1272
|
+
async terminate() {
|
|
1273
|
+
if (this.worker) {
|
|
1274
|
+
await this.worker.terminate();
|
|
1275
|
+
this.worker = null;
|
|
1276
|
+
}
|
|
1277
|
+
if (this.ocrWorker) {
|
|
1278
|
+
this.ocrWorker.terminate();
|
|
1279
|
+
this.ocrWorker = null;
|
|
1280
|
+
}
|
|
1281
|
+
this.initialized = false;
|
|
1282
|
+
this.options.logger?.('OCR引擎已终止');
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* 释放资源
|
|
1286
|
+
*/
|
|
1287
|
+
dispose() {
|
|
1288
|
+
return this.terminate();
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/**
|
|
1293
|
+
* @file 数据提取工具类
|
|
1294
|
+
* @description 提供身份证信息的验证和格式化功能
|
|
1295
|
+
* @module DataExtractor
|
|
1296
|
+
*/
|
|
1297
|
+
/**
|
|
1298
|
+
* 数据提取工具类
|
|
1299
|
+
*
|
|
1300
|
+
* 提供身份证信息的验证、提取和增强功能,可以从身份证号码中提取出生日期、性别等信息,
|
|
1301
|
+
* 并对OCR识别结果进行补充和验证
|
|
1302
|
+
*
|
|
1303
|
+
* @example
|
|
1304
|
+
* ```typescript
|
|
1305
|
+
* // 验证身份证号码
|
|
1306
|
+
* const isValid = DataExtractor.validateIDNumber('110101199001011234');
|
|
1307
|
+
*
|
|
1308
|
+
* // 从身份证号码提取出生日期
|
|
1309
|
+
* const birthDate = DataExtractor.extractBirthDateFromID('110101199001011234');
|
|
1310
|
+
* // 结果: '1990-01-01'
|
|
1311
|
+
*
|
|
1312
|
+
* // 增强OCR识别结果
|
|
1313
|
+
* const enhancedInfo = DataExtractor.enhanceIDCardInfo({
|
|
1314
|
+
* name: '张三',
|
|
1315
|
+
* idNumber: '110101199001011234'
|
|
1316
|
+
* });
|
|
1317
|
+
* // 结果会自动补充性别和出生日期
|
|
1318
|
+
* ```
|
|
1319
|
+
*/
|
|
1320
|
+
class DataExtractor {
|
|
1321
|
+
/**
|
|
1322
|
+
* 验证身份证号码格式
|
|
1323
|
+
*
|
|
1324
|
+
* 检查身份证号码的长度、格式和出生日期部分是否有效
|
|
1325
|
+
*
|
|
1326
|
+
* @param {string} idNumber - 要验证的身份证号码
|
|
1327
|
+
* @returns {boolean} 是否是有效的身份证号码
|
|
1328
|
+
*/
|
|
1329
|
+
static validateIDNumber(idNumber) {
|
|
1330
|
+
// 简单校验长度
|
|
1331
|
+
if (!idNumber || idNumber.length !== 18) {
|
|
1332
|
+
return false;
|
|
1333
|
+
}
|
|
1334
|
+
// 校验格式 (前17位必须是数字,最后一位可以是数字或X)
|
|
1335
|
+
const pattern = /^\d{17}[\dX]$/;
|
|
1336
|
+
if (!pattern.test(idNumber)) {
|
|
1337
|
+
return false;
|
|
1338
|
+
}
|
|
1339
|
+
// 校验出生日期
|
|
1340
|
+
const year = parseInt(idNumber.substr(6, 4));
|
|
1341
|
+
const month = parseInt(idNumber.substr(10, 2));
|
|
1342
|
+
const day = parseInt(idNumber.substr(12, 2));
|
|
1343
|
+
const date = new Date(year, month - 1, day);
|
|
1344
|
+
if (date.getFullYear() !== year ||
|
|
1345
|
+
date.getMonth() + 1 !== month ||
|
|
1346
|
+
date.getDate() !== day) {
|
|
1347
|
+
return false;
|
|
1348
|
+
}
|
|
1349
|
+
// 简单的校验规则,实际项目中可以加入更完善的验证
|
|
1350
|
+
return true;
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* 从身份证号码提取出生日期
|
|
1354
|
+
*
|
|
1355
|
+
* @param {string} idNumber - 身份证号码
|
|
1356
|
+
* @returns {string|null} 格式化的出生日期(YYYY-MM-DD),如果身份证号码无效则返回null
|
|
1357
|
+
*/
|
|
1358
|
+
static extractBirthDateFromID(idNumber) {
|
|
1359
|
+
if (!this.validateIDNumber(idNumber)) {
|
|
1360
|
+
return null;
|
|
1361
|
+
}
|
|
1362
|
+
const year = idNumber.substr(6, 4);
|
|
1363
|
+
const month = idNumber.substr(10, 2);
|
|
1364
|
+
const day = idNumber.substr(12, 2);
|
|
1365
|
+
return `${year}-${month}-${day}`;
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* 从身份证号码提取性别
|
|
1369
|
+
*
|
|
1370
|
+
* 根据身份证号码第17位判断性别,奇数为男,偶数为女
|
|
1371
|
+
*
|
|
1372
|
+
* @param {string} idNumber - 身份证号码
|
|
1373
|
+
* @returns {string|null} '男'或'女',如果身份证号码无效则返回null
|
|
1374
|
+
*/
|
|
1375
|
+
static extractGenderFromID(idNumber) {
|
|
1376
|
+
if (!this.validateIDNumber(idNumber)) {
|
|
1377
|
+
return null;
|
|
1378
|
+
}
|
|
1379
|
+
// 第17位,奇数为男,偶数为女
|
|
1380
|
+
const genderCode = parseInt(idNumber.charAt(16));
|
|
1381
|
+
return genderCode % 2 === 1 ? '男' : '女';
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* 从身份证号码提取地区编码
|
|
1385
|
+
*
|
|
1386
|
+
* @param {string} idNumber - 身份证号码
|
|
1387
|
+
* @returns {string|null} 地区编码(前6位),如果身份证号码无效则返回null
|
|
1388
|
+
*/
|
|
1389
|
+
static extractRegionFromID(idNumber) {
|
|
1390
|
+
if (!this.validateIDNumber(idNumber)) {
|
|
1391
|
+
return null;
|
|
1392
|
+
}
|
|
1393
|
+
return idNumber.substr(0, 6);
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* 合并并优化身份证信息
|
|
1397
|
+
*
|
|
1398
|
+
* 使用多个来源的数据进行交叉验证和补充,如果OCR识别结果缺少某些信息,
|
|
1399
|
+
* 但有身份证号码,则可以从号码中提取出生日期和性别等信息
|
|
1400
|
+
*
|
|
1401
|
+
* @param {IDCardInfo} ocrInfo - OCR识别到的身份证信息
|
|
1402
|
+
* @param {string} [idNumber] - 可选的外部提供的身份证号码,优先级高于OCR识别结果
|
|
1403
|
+
* @returns {IDCardInfo} 增强后的身份证信息
|
|
1404
|
+
*/
|
|
1405
|
+
static enhanceIDCardInfo(ocrInfo, idNumber) {
|
|
1406
|
+
const result = { ...ocrInfo };
|
|
1407
|
+
// 如果OCR识别出身份证号,但没有识别出生日期或性别,则从身份证号码提取
|
|
1408
|
+
if (result.idNumber && this.validateIDNumber(result.idNumber)) {
|
|
1409
|
+
// 从身份证号提取出生日期
|
|
1410
|
+
if (!result.birthDate) {
|
|
1411
|
+
result.birthDate = this.extractBirthDateFromID(result.idNumber) || undefined;
|
|
1412
|
+
}
|
|
1413
|
+
// 从身份证号提取性别
|
|
1414
|
+
if (!result.gender) {
|
|
1415
|
+
result.gender = this.extractGenderFromID(result.idNumber) || undefined;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
// 如果外部传入了身份证号,则优先使用它并提取信息
|
|
1419
|
+
if (idNumber && this.validateIDNumber(idNumber)) {
|
|
1420
|
+
result.idNumber = idNumber;
|
|
1421
|
+
// 使用身份证号码再次验证或补充信息
|
|
1422
|
+
const birthDate = this.extractBirthDateFromID(idNumber);
|
|
1423
|
+
if (birthDate) {
|
|
1424
|
+
result.birthDate = birthDate;
|
|
1425
|
+
}
|
|
1426
|
+
const gender = this.extractGenderFromID(idNumber);
|
|
1427
|
+
if (gender) {
|
|
1428
|
+
result.gender = gender;
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
return result;
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* 提取并验证身份证信息
|
|
1435
|
+
*
|
|
1436
|
+
* @param idCardInfo 初步提取的身份证信息
|
|
1437
|
+
* @returns 验证和增强后的身份证信息
|
|
1438
|
+
*/
|
|
1439
|
+
extractAndValidate(idCardInfo) {
|
|
1440
|
+
const enhancedInfo = { ...idCardInfo };
|
|
1441
|
+
// 验证和规范化身份证号
|
|
1442
|
+
if (enhancedInfo.idNumber) {
|
|
1443
|
+
enhancedInfo.idNumber = this.normalizeIDNumber(enhancedInfo.idNumber);
|
|
1444
|
+
// 如果身份证号有效,推断出生日期
|
|
1445
|
+
if (this.validateIDNumber(enhancedInfo.idNumber)) {
|
|
1446
|
+
if (!enhancedInfo.birthDate) {
|
|
1447
|
+
enhancedInfo.birthDate = this.extractBirthDateFromID(enhancedInfo.idNumber);
|
|
1448
|
+
}
|
|
1449
|
+
// 推断性别
|
|
1450
|
+
if (!enhancedInfo.gender) {
|
|
1451
|
+
enhancedInfo.gender = this.extractGenderFromID(enhancedInfo.idNumber);
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
// 规范化日期格式
|
|
1456
|
+
if (enhancedInfo.birthDate) {
|
|
1457
|
+
enhancedInfo.birthDate = this.normalizeDate(enhancedInfo.birthDate);
|
|
1458
|
+
}
|
|
1459
|
+
// 规范化地址信息
|
|
1460
|
+
if (enhancedInfo.address) {
|
|
1461
|
+
enhancedInfo.address = this.normalizeAddress(enhancedInfo.address);
|
|
1462
|
+
}
|
|
1463
|
+
return enhancedInfo;
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* 规范化身份证号码
|
|
1467
|
+
*/
|
|
1468
|
+
normalizeIDNumber(idNumber) {
|
|
1469
|
+
// 移除空格和特殊字符
|
|
1470
|
+
return idNumber.replace(/[\s\-]/g, '').toUpperCase();
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* 验证身份证号码是否有效
|
|
1474
|
+
*/
|
|
1475
|
+
validateIDNumber(idNumber) {
|
|
1476
|
+
// 简单验证身份证号码长度和格式
|
|
1477
|
+
const idRegex = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
|
|
1478
|
+
return idRegex.test(idNumber);
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* 从身份证号中提取出生日期
|
|
1482
|
+
*/
|
|
1483
|
+
extractBirthDateFromID(idNumber) {
|
|
1484
|
+
if (idNumber.length === 18) {
|
|
1485
|
+
return `${idNumber.substring(6, 10)}-${idNumber.substring(10, 12)}-${idNumber.substring(12, 14)}`;
|
|
1486
|
+
}
|
|
1487
|
+
else if (idNumber.length === 15) {
|
|
1488
|
+
return `19${idNumber.substring(6, 8)}-${idNumber.substring(8, 10)}-${idNumber.substring(10, 12)}`;
|
|
1489
|
+
}
|
|
1490
|
+
return '';
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* 从身份证号中提取性别信息
|
|
1494
|
+
*/
|
|
1495
|
+
extractGenderFromID(idNumber) {
|
|
1496
|
+
let sexCode;
|
|
1497
|
+
if (idNumber.length === 18) {
|
|
1498
|
+
sexCode = parseInt(idNumber.charAt(16));
|
|
1499
|
+
}
|
|
1500
|
+
else {
|
|
1501
|
+
sexCode = parseInt(idNumber.charAt(14));
|
|
1502
|
+
}
|
|
1503
|
+
return sexCode % 2 === 1 ? '男' : '女';
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* 规范化日期格式
|
|
1507
|
+
*/
|
|
1508
|
+
normalizeDate(date) {
|
|
1509
|
+
// 简单的日期格式化逻辑
|
|
1510
|
+
return date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* 规范化地址信息
|
|
1514
|
+
*/
|
|
1515
|
+
normalizeAddress(address) {
|
|
1516
|
+
// 地址格式化逻辑
|
|
1517
|
+
return address.trim();
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/**
|
|
1522
|
+
* @file OCR模块入口文件
|
|
1523
|
+
* @description 包含身份证OCR识别相关功能
|
|
1524
|
+
* @module IDScannerOCR
|
|
1525
|
+
* @version 1.0.0
|
|
1526
|
+
* @license MIT
|
|
1527
|
+
*/
|
|
1528
|
+
/**
|
|
1529
|
+
* OCR模块类
|
|
1530
|
+
*
|
|
1531
|
+
* 提供身份证检测和OCR文字识别功能
|
|
1532
|
+
*/
|
|
1533
|
+
class OCRModule {
|
|
1534
|
+
/**
|
|
1535
|
+
* 构造函数
|
|
1536
|
+
* @param options 配置选项
|
|
1537
|
+
*/
|
|
1538
|
+
constructor(options = {}) {
|
|
1539
|
+
this.options = options;
|
|
1540
|
+
this.isRunning = false;
|
|
1541
|
+
this.videoElement = null;
|
|
1542
|
+
this.camera = new Camera(options.cameraOptions);
|
|
1543
|
+
this.idDetector = new IDCardDetector({
|
|
1544
|
+
onDetection: this.handleIDDetection.bind(this),
|
|
1545
|
+
onError: this.handleError.bind(this)
|
|
1546
|
+
});
|
|
1547
|
+
this.ocrProcessor = new OCRProcessor();
|
|
1548
|
+
this.dataExtractor = new DataExtractor();
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* 初始化OCR引擎
|
|
1552
|
+
*
|
|
1553
|
+
* @returns Promise<void>
|
|
1554
|
+
*/
|
|
1555
|
+
async initialize() {
|
|
1556
|
+
try {
|
|
1557
|
+
await this.ocrProcessor.initialize();
|
|
1558
|
+
console.log('OCR engine initialized');
|
|
1559
|
+
}
|
|
1560
|
+
catch (error) {
|
|
1561
|
+
this.handleError(error);
|
|
1562
|
+
throw error;
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* 启动身份证扫描
|
|
1567
|
+
* @param videoElement HTML视频元素
|
|
1568
|
+
*/
|
|
1569
|
+
async startIDCardScanner(videoElement) {
|
|
1570
|
+
if (!this.ocrProcessor) {
|
|
1571
|
+
throw new Error('OCR engine not initialized. Call initialize() first.');
|
|
1572
|
+
}
|
|
1573
|
+
this.videoElement = videoElement;
|
|
1574
|
+
this.isRunning = true;
|
|
1575
|
+
await this.camera.start(videoElement);
|
|
1576
|
+
this.idDetector.start(videoElement);
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* 停止扫描
|
|
1580
|
+
*/
|
|
1581
|
+
stop() {
|
|
1582
|
+
this.isRunning = false;
|
|
1583
|
+
this.idDetector.stop();
|
|
1584
|
+
this.camera.stop();
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* 处理身份证检测结果
|
|
1588
|
+
*/
|
|
1589
|
+
async handleIDDetection(result) {
|
|
1590
|
+
if (!this.isRunning)
|
|
1591
|
+
return;
|
|
1592
|
+
try {
|
|
1593
|
+
// 检查 imageData 是否存在
|
|
1594
|
+
if (!result.imageData) {
|
|
1595
|
+
this.handleError(new Error('无效的图像数据'));
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
const idCardInfo = await this.ocrProcessor.processIDCard(result.imageData);
|
|
1599
|
+
const extractedInfo = this.dataExtractor.extractAndValidate(idCardInfo);
|
|
1600
|
+
if (this.options.onIDCardScanned) {
|
|
1601
|
+
this.options.onIDCardScanned(extractedInfo);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
catch (error) {
|
|
1605
|
+
this.handleError(error);
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* 处理错误
|
|
1610
|
+
*/
|
|
1611
|
+
handleError(error) {
|
|
1612
|
+
if (this.options.onError) {
|
|
1613
|
+
this.options.onError(error);
|
|
1614
|
+
}
|
|
1615
|
+
else {
|
|
1616
|
+
console.error('OCRModule error:', error);
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* 释放资源
|
|
1621
|
+
*/
|
|
1622
|
+
async terminate() {
|
|
1623
|
+
this.stop();
|
|
1624
|
+
await this.ocrProcessor.terminate();
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
exports.DataExtractor = DataExtractor;
|
|
1629
|
+
exports.IDCardDetector = IDCardDetector;
|
|
1630
|
+
exports.OCRModule = OCRModule;
|
|
1631
|
+
exports.OCRProcessor = OCRProcessor;
|
|
1632
|
+
|
|
1633
|
+
}));
|
|
1634
|
+
//# sourceMappingURL=id-scanner-ocr.js.map
|