id-scanner-lib 1.1.1 → 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 +77 -0
- package/dist/id-scanner-core.esm.js +160 -0
- package/dist/id-scanner-core.esm.js.map +1 -1
- package/dist/id-scanner-core.js +160 -0
- package/dist/id-scanner-core.js.map +1 -1
- package/dist/id-scanner-core.min.js +2 -2
- package/dist/id-scanner-core.min.js.map +1 -1
- package/dist/id-scanner-ocr.esm.js +789 -78
- package/dist/id-scanner-ocr.esm.js.map +1 -1
- package/dist/id-scanner-ocr.js +788 -77
- package/dist/id-scanner-ocr.js.map +1 -1
- package/dist/id-scanner-ocr.min.js +2 -2
- package/dist/id-scanner-ocr.min.js.map +1 -1
- package/dist/id-scanner-qr.esm.js +160 -0
- package/dist/id-scanner-qr.esm.js.map +1 -1
- package/dist/id-scanner-qr.js +160 -0
- package/dist/id-scanner-qr.js.map +1 -1
- package/dist/id-scanner-qr.min.js +2 -2
- package/dist/id-scanner-qr.min.js.map +1 -1
- package/dist/id-scanner.js +788 -77
- package/dist/id-scanner.js.map +1 -1
- package/dist/id-scanner.min.js +2 -2
- package/dist/id-scanner.min.js.map +1 -1
- package/package.json +1 -1
- package/src/id-recognition/id-detector.ts +210 -65
- package/src/id-recognition/ocr-processor.ts +142 -21
- package/src/id-recognition/ocr-worker.ts +146 -0
- 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/worker.ts +173 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createWorker } from 'tesseract.js';
|
|
1
|
+
import { createWorker as createWorker$1 } from 'tesseract.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @file 相机工具类
|
|
@@ -275,6 +275,323 @@ class ImageProcessor {
|
|
|
275
275
|
}
|
|
276
276
|
return imageData;
|
|
277
277
|
}
|
|
278
|
+
/**
|
|
279
|
+
* 降低图像分辨率以提高处理速度
|
|
280
|
+
*
|
|
281
|
+
* 对于OCR和图像分析,降低分辨率可以在保持识别率的同时大幅提升处理速度
|
|
282
|
+
*
|
|
283
|
+
* @param {ImageData} imageData - 原图像数据
|
|
284
|
+
* @param {number} [maxDimension=1000] - 目标最大尺寸(宽或高)
|
|
285
|
+
* @returns {ImageData} 处理后的图像数据
|
|
286
|
+
*/
|
|
287
|
+
static downsampleForProcessing(imageData, maxDimension = 1000) {
|
|
288
|
+
const { width, height } = imageData;
|
|
289
|
+
// 如果图像尺寸已经小于或等于目标尺寸,则无需处理
|
|
290
|
+
if (width <= maxDimension && height <= maxDimension) {
|
|
291
|
+
return imageData;
|
|
292
|
+
}
|
|
293
|
+
// 计算缩放比例,保持宽高比
|
|
294
|
+
const scale = maxDimension / Math.max(width, height);
|
|
295
|
+
const newWidth = Math.round(width * scale);
|
|
296
|
+
const newHeight = Math.round(height * scale);
|
|
297
|
+
// 调整图像大小
|
|
298
|
+
return this.resize(imageData, newWidth, newHeight);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* 转换图像为Base64格式,方便在Worker线程中传递
|
|
302
|
+
*
|
|
303
|
+
* @param {ImageData} imageData - 原图像数据
|
|
304
|
+
* @returns {string} base64编码的图像数据
|
|
305
|
+
*/
|
|
306
|
+
static imageDataToBase64(imageData) {
|
|
307
|
+
const canvas = this.imageDataToCanvas(imageData);
|
|
308
|
+
return canvas.toDataURL('image/jpeg', 0.7); // 使用较低质量的JPEG格式减少数据量
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* 从Base64字符串还原图像数据
|
|
312
|
+
*
|
|
313
|
+
* @param {string} base64 - base64编码的图像数据
|
|
314
|
+
* @returns {Promise<ImageData>} 还原的图像数据
|
|
315
|
+
*/
|
|
316
|
+
static async base64ToImageData(base64) {
|
|
317
|
+
return new Promise((resolve, reject) => {
|
|
318
|
+
const img = new Image();
|
|
319
|
+
img.onload = () => {
|
|
320
|
+
const canvas = document.createElement('canvas');
|
|
321
|
+
canvas.width = img.width;
|
|
322
|
+
canvas.height = img.height;
|
|
323
|
+
const ctx = canvas.getContext('2d');
|
|
324
|
+
if (!ctx) {
|
|
325
|
+
reject(new Error('无法创建Canvas上下文'));
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
ctx.drawImage(img, 0, 0);
|
|
329
|
+
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
330
|
+
resolve(imageData);
|
|
331
|
+
};
|
|
332
|
+
img.onerror = () => {
|
|
333
|
+
reject(new Error('图像加载失败'));
|
|
334
|
+
};
|
|
335
|
+
img.src = base64;
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* 使用Web Worker并行处理图像
|
|
340
|
+
* 此方法将图像分割为多个部分,并行处理以提高性能
|
|
341
|
+
*
|
|
342
|
+
* @param {ImageData} imageData - 原图像数据
|
|
343
|
+
* @param {Function} processingFunction - 处理函数,接收ImageData返回ImageData
|
|
344
|
+
* @param {number} [chunks=4] - 分割的块数
|
|
345
|
+
* @returns {Promise<ImageData>} 处理后的图像数据
|
|
346
|
+
*/
|
|
347
|
+
static async processImageInParallel(imageData, processingFunction, chunks = 4) {
|
|
348
|
+
// 如果不支持Worker或图像太小,直接处理
|
|
349
|
+
if (typeof Worker === 'undefined' || imageData.width * imageData.height < 100000) {
|
|
350
|
+
return processingFunction(imageData);
|
|
351
|
+
}
|
|
352
|
+
// 创建结果canvas
|
|
353
|
+
const resultCanvas = document.createElement('canvas');
|
|
354
|
+
resultCanvas.width = imageData.width;
|
|
355
|
+
resultCanvas.height = imageData.height;
|
|
356
|
+
const resultCtx = resultCanvas.getContext('2d');
|
|
357
|
+
if (!resultCtx) {
|
|
358
|
+
throw new Error('无法创建Canvas上下文');
|
|
359
|
+
}
|
|
360
|
+
// 根据图像特性确定分割方向和每块大小
|
|
361
|
+
const isWide = imageData.width > imageData.height;
|
|
362
|
+
const chunkSize = Math.floor((isWide ? imageData.width : imageData.height) / chunks);
|
|
363
|
+
// 创建Worker处理每个块
|
|
364
|
+
const promises = [];
|
|
365
|
+
for (let i = 0; i < chunks; i++) {
|
|
366
|
+
const chunkCanvas = document.createElement('canvas');
|
|
367
|
+
const chunkCtx = chunkCanvas.getContext('2d');
|
|
368
|
+
if (!chunkCtx)
|
|
369
|
+
continue;
|
|
370
|
+
let chunkImageData;
|
|
371
|
+
if (isWide) {
|
|
372
|
+
// 水平分割
|
|
373
|
+
const startX = i * chunkSize;
|
|
374
|
+
const width = (i === chunks - 1) ? imageData.width - startX : chunkSize;
|
|
375
|
+
chunkCanvas.width = width;
|
|
376
|
+
chunkCanvas.height = imageData.height;
|
|
377
|
+
// 复制原图像数据到分块
|
|
378
|
+
const tempCanvas = this.imageDataToCanvas(imageData);
|
|
379
|
+
chunkCtx.drawImage(tempCanvas, startX, 0, width, imageData.height, 0, 0, width, imageData.height);
|
|
380
|
+
chunkImageData = chunkCtx.getImageData(0, 0, width, imageData.height);
|
|
381
|
+
}
|
|
382
|
+
else {
|
|
383
|
+
// 垂直分割
|
|
384
|
+
const startY = i * chunkSize;
|
|
385
|
+
const height = (i === chunks - 1) ? imageData.height - startY : chunkSize;
|
|
386
|
+
chunkCanvas.width = imageData.width;
|
|
387
|
+
chunkCanvas.height = height;
|
|
388
|
+
// 复制原图像数据到分块
|
|
389
|
+
const tempCanvas = this.imageDataToCanvas(imageData);
|
|
390
|
+
chunkCtx.drawImage(tempCanvas, 0, startY, imageData.width, height, 0, 0, imageData.width, height);
|
|
391
|
+
chunkImageData = chunkCtx.getImageData(0, 0, imageData.width, height);
|
|
392
|
+
}
|
|
393
|
+
// 使用Worker处理
|
|
394
|
+
const workerCode = `
|
|
395
|
+
self.onmessage = function(e) {
|
|
396
|
+
const imageData = e.data.imageData;
|
|
397
|
+
const processingFunction = ${processingFunction.toString()};
|
|
398
|
+
const result = processingFunction(imageData);
|
|
399
|
+
self.postMessage({ result, index: e.data.index }, [result.data.buffer]);
|
|
400
|
+
}
|
|
401
|
+
`;
|
|
402
|
+
const blob = new Blob([workerCode], { type: 'application/javascript' });
|
|
403
|
+
const workerUrl = URL.createObjectURL(blob);
|
|
404
|
+
const worker = new Worker(workerUrl);
|
|
405
|
+
const promise = new Promise((resolve) => {
|
|
406
|
+
worker.onmessage = function (e) {
|
|
407
|
+
resolve(e.data);
|
|
408
|
+
worker.terminate();
|
|
409
|
+
URL.revokeObjectURL(workerUrl);
|
|
410
|
+
};
|
|
411
|
+
// 传输数据
|
|
412
|
+
worker.postMessage({
|
|
413
|
+
imageData: chunkImageData,
|
|
414
|
+
index: i
|
|
415
|
+
}, [chunkImageData.data.buffer]);
|
|
416
|
+
});
|
|
417
|
+
promises.push(promise);
|
|
418
|
+
}
|
|
419
|
+
// 等待所有Worker完成并组合结果
|
|
420
|
+
const results = await Promise.all(promises);
|
|
421
|
+
// 按索引排序结果
|
|
422
|
+
results.sort((a, b) => a.index - b.index);
|
|
423
|
+
// 将处理后的块绘制到结果canvas
|
|
424
|
+
for (let i = 0; i < results.length; i++) {
|
|
425
|
+
const { result } = results[i];
|
|
426
|
+
const tempCanvas = this.imageDataToCanvas(result);
|
|
427
|
+
if (isWide) {
|
|
428
|
+
const startX = i * chunkSize;
|
|
429
|
+
resultCtx.drawImage(tempCanvas, startX, 0);
|
|
430
|
+
}
|
|
431
|
+
else {
|
|
432
|
+
const startY = i * chunkSize;
|
|
433
|
+
resultCtx.drawImage(tempCanvas, 0, startY);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return resultCtx.getImageData(0, 0, imageData.width, imageData.height);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* @file 性能优化工具类
|
|
442
|
+
* @description 提供节流、防抖、缓存等性能优化功能
|
|
443
|
+
* @module PerformanceUtils
|
|
444
|
+
*/
|
|
445
|
+
/**
|
|
446
|
+
* 节流函数:限制函数在一定时间内只能执行一次
|
|
447
|
+
*
|
|
448
|
+
* @param fn 需要节流的函数
|
|
449
|
+
* @param delay 延迟时间(毫秒)
|
|
450
|
+
* @returns 节流处理后的函数
|
|
451
|
+
*/
|
|
452
|
+
function throttle(fn, delay) {
|
|
453
|
+
let lastCall = 0;
|
|
454
|
+
let timeoutId = null;
|
|
455
|
+
return function (...args) {
|
|
456
|
+
const now = Date.now();
|
|
457
|
+
const remaining = delay - (now - lastCall);
|
|
458
|
+
if (remaining <= 0) {
|
|
459
|
+
if (timeoutId) {
|
|
460
|
+
clearTimeout(timeoutId);
|
|
461
|
+
timeoutId = null;
|
|
462
|
+
}
|
|
463
|
+
lastCall = now;
|
|
464
|
+
fn.apply(this, args);
|
|
465
|
+
}
|
|
466
|
+
else if (!timeoutId) {
|
|
467
|
+
timeoutId = window.setTimeout(() => {
|
|
468
|
+
lastCall = Date.now();
|
|
469
|
+
timeoutId = null;
|
|
470
|
+
fn.apply(this, args);
|
|
471
|
+
}, remaining);
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* LRU缓存类 - 使用最近最少使用策略的缓存实现
|
|
477
|
+
*/
|
|
478
|
+
class LRUCache {
|
|
479
|
+
/**
|
|
480
|
+
* 构造LRU缓存
|
|
481
|
+
* @param maxSize 缓存最大容量
|
|
482
|
+
*/
|
|
483
|
+
constructor(maxSize = 100) {
|
|
484
|
+
this.maxSize = maxSize;
|
|
485
|
+
this.cache = new Map();
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* 获取缓存项
|
|
489
|
+
* @param key 缓存键
|
|
490
|
+
* @returns 缓存值或undefined
|
|
491
|
+
*/
|
|
492
|
+
get(key) {
|
|
493
|
+
if (!this.cache.has(key)) {
|
|
494
|
+
return undefined;
|
|
495
|
+
}
|
|
496
|
+
// 获取值
|
|
497
|
+
const value = this.cache.get(key);
|
|
498
|
+
// 将项移至最新位置(删除后重新添加)
|
|
499
|
+
this.cache.delete(key);
|
|
500
|
+
this.cache.set(key, value);
|
|
501
|
+
return value;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* 设置缓存项
|
|
505
|
+
* @param key 缓存键
|
|
506
|
+
* @param value 缓存值
|
|
507
|
+
*/
|
|
508
|
+
set(key, value) {
|
|
509
|
+
// 如果键已存在,需要先删除
|
|
510
|
+
if (this.cache.has(key)) {
|
|
511
|
+
this.cache.delete(key);
|
|
512
|
+
}
|
|
513
|
+
// 如果缓存已满,移除最老的项
|
|
514
|
+
if (this.cache.size >= this.maxSize) {
|
|
515
|
+
const oldestKey = this.cache.keys().next().value;
|
|
516
|
+
this.cache.delete(oldestKey);
|
|
517
|
+
}
|
|
518
|
+
// 添加新项
|
|
519
|
+
this.cache.set(key, value);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* 删除缓存项
|
|
523
|
+
* @param key 缓存键
|
|
524
|
+
* @returns 是否成功删除
|
|
525
|
+
*/
|
|
526
|
+
delete(key) {
|
|
527
|
+
return this.cache.delete(key);
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* 清空缓存
|
|
531
|
+
*/
|
|
532
|
+
clear() {
|
|
533
|
+
this.cache.clear();
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* 获取当前缓存大小
|
|
537
|
+
*/
|
|
538
|
+
get size() {
|
|
539
|
+
return this.cache.size;
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* 检查键是否存在
|
|
543
|
+
* @param key 缓存键
|
|
544
|
+
*/
|
|
545
|
+
has(key) {
|
|
546
|
+
return this.cache.has(key);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* 图像指纹计算函数 - 用于检测相同或相似图像
|
|
551
|
+
*
|
|
552
|
+
* @param imageData 图像数据
|
|
553
|
+
* @param size 指纹尺寸(默认8x8)
|
|
554
|
+
* @returns 图像指纹字符串
|
|
555
|
+
*/
|
|
556
|
+
function calculateImageFingerprint(imageData, size = 8) {
|
|
557
|
+
// 1. 缩小图像到指定尺寸
|
|
558
|
+
const canvas = document.createElement('canvas');
|
|
559
|
+
canvas.width = size;
|
|
560
|
+
canvas.height = size;
|
|
561
|
+
const ctx = canvas.getContext('2d');
|
|
562
|
+
if (!ctx) {
|
|
563
|
+
return '';
|
|
564
|
+
}
|
|
565
|
+
// 创建一个临时canvas来绘制原始imageData
|
|
566
|
+
const tempCanvas = document.createElement('canvas');
|
|
567
|
+
tempCanvas.width = imageData.width;
|
|
568
|
+
tempCanvas.height = imageData.height;
|
|
569
|
+
const tempCtx = tempCanvas.getContext('2d');
|
|
570
|
+
if (!tempCtx) {
|
|
571
|
+
return '';
|
|
572
|
+
}
|
|
573
|
+
tempCtx.putImageData(imageData, 0, 0);
|
|
574
|
+
// 缩小到目标尺寸
|
|
575
|
+
ctx.drawImage(tempCanvas, 0, 0, imageData.width, imageData.height, 0, 0, size, size);
|
|
576
|
+
// 2. 转换为灰度
|
|
577
|
+
const smallImgData = ctx.getImageData(0, 0, size, size);
|
|
578
|
+
const grayValues = [];
|
|
579
|
+
for (let i = 0; i < smallImgData.data.length; i += 4) {
|
|
580
|
+
const r = smallImgData.data[i];
|
|
581
|
+
const g = smallImgData.data[i + 1];
|
|
582
|
+
const b = smallImgData.data[i + 2];
|
|
583
|
+
// 转为灰度: 0.299r + 0.587g + 0.114b
|
|
584
|
+
const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
|
|
585
|
+
grayValues.push(gray);
|
|
586
|
+
}
|
|
587
|
+
// 3. 计算平均值
|
|
588
|
+
const avg = grayValues.reduce((sum, val) => sum + val, 0) / grayValues.length;
|
|
589
|
+
// 4. 比较每个像素与平均值,生成二进制指纹
|
|
590
|
+
let fingerprint = '';
|
|
591
|
+
for (const gray of grayValues) {
|
|
592
|
+
fingerprint += gray >= avg ? '1' : '0';
|
|
593
|
+
}
|
|
594
|
+
return fingerprint;
|
|
278
595
|
}
|
|
279
596
|
|
|
280
597
|
/**
|
|
@@ -316,15 +633,48 @@ class IDCardDetector {
|
|
|
316
633
|
constructor(options) {
|
|
317
634
|
this.detecting = false;
|
|
318
635
|
this.detectTimer = null;
|
|
636
|
+
this.frameCount = 0;
|
|
637
|
+
this.lastDetectionTime = 0;
|
|
319
638
|
this.camera = new Camera();
|
|
320
639
|
if (typeof options === 'function') {
|
|
321
640
|
// 兼容旧的构造函数方式
|
|
322
641
|
this.onDetected = options;
|
|
642
|
+
this.options = {
|
|
643
|
+
detectionInterval: 200,
|
|
644
|
+
maxImageDimension: 800,
|
|
645
|
+
enableCache: true,
|
|
646
|
+
cacheSize: 20,
|
|
647
|
+
logger: console.log
|
|
648
|
+
};
|
|
323
649
|
}
|
|
324
650
|
else if (options) {
|
|
325
651
|
// 使用新的选项对象方式
|
|
652
|
+
this.options = {
|
|
653
|
+
detectionInterval: 200,
|
|
654
|
+
maxImageDimension: 800,
|
|
655
|
+
enableCache: true,
|
|
656
|
+
cacheSize: 20,
|
|
657
|
+
logger: console.log,
|
|
658
|
+
...options
|
|
659
|
+
};
|
|
326
660
|
this.onDetected = options.onDetection;
|
|
661
|
+
this.onError = options.onError;
|
|
327
662
|
}
|
|
663
|
+
else {
|
|
664
|
+
this.options = {
|
|
665
|
+
detectionInterval: 200,
|
|
666
|
+
maxImageDimension: 800,
|
|
667
|
+
enableCache: true,
|
|
668
|
+
cacheSize: 20,
|
|
669
|
+
logger: console.log
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
this.detectionInterval = this.options.detectionInterval;
|
|
673
|
+
this.maxImageDimension = this.options.maxImageDimension;
|
|
674
|
+
// 初始化结果缓存
|
|
675
|
+
this.resultCache = new LRUCache(this.options.cacheSize);
|
|
676
|
+
// 创建节流版本的检测函数
|
|
677
|
+
this.throttledDetect = throttle(this.performDetection.bind(this), this.detectionInterval);
|
|
328
678
|
}
|
|
329
679
|
/**
|
|
330
680
|
* 启动身份证检测
|
|
@@ -337,97 +687,373 @@ class IDCardDetector {
|
|
|
337
687
|
async start(videoElement) {
|
|
338
688
|
await this.camera.initialize(videoElement);
|
|
339
689
|
this.detecting = true;
|
|
690
|
+
this.frameCount = 0;
|
|
691
|
+
this.lastDetectionTime = 0;
|
|
340
692
|
this.detect();
|
|
341
693
|
}
|
|
342
694
|
/**
|
|
343
|
-
*
|
|
344
|
-
|
|
345
|
-
|
|
695
|
+
* 停止身份证检测
|
|
696
|
+
*/
|
|
697
|
+
stop() {
|
|
698
|
+
this.detecting = false;
|
|
699
|
+
if (this.detectTimer !== null) {
|
|
700
|
+
cancelAnimationFrame(this.detectTimer);
|
|
701
|
+
this.detectTimer = null;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* 持续检测视频帧
|
|
346
706
|
*
|
|
347
707
|
* @private
|
|
348
708
|
*/
|
|
349
|
-
|
|
709
|
+
detect() {
|
|
350
710
|
if (!this.detecting)
|
|
351
711
|
return;
|
|
352
|
-
|
|
353
|
-
if (imageData) {
|
|
712
|
+
this.detectTimer = requestAnimationFrame(() => {
|
|
354
713
|
try {
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
714
|
+
this.frameCount++;
|
|
715
|
+
const now = performance.now();
|
|
716
|
+
// 帧率控制 - 只有满足时间间隔的帧才进行检测
|
|
717
|
+
// 这样可以显著减少CPU使用率,同时保持良好的用户体验
|
|
718
|
+
if (this.frameCount % 3 === 0 || now - this.lastDetectionTime >= this.detectionInterval) {
|
|
719
|
+
this.throttledDetect();
|
|
720
|
+
this.lastDetectionTime = now;
|
|
360
721
|
}
|
|
722
|
+
// 继续下一帧检测
|
|
723
|
+
this.detect();
|
|
361
724
|
}
|
|
362
725
|
catch (error) {
|
|
726
|
+
if (this.onError) {
|
|
727
|
+
this.onError(error);
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
console.error('身份证检测错误:', error);
|
|
731
|
+
}
|
|
732
|
+
// 出错后延迟重试
|
|
733
|
+
setTimeout(() => {
|
|
734
|
+
if (this.detecting) {
|
|
735
|
+
this.detect();
|
|
736
|
+
}
|
|
737
|
+
}, 1000);
|
|
738
|
+
}
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* 执行单帧检测
|
|
743
|
+
*
|
|
744
|
+
* @private
|
|
745
|
+
*/
|
|
746
|
+
async performDetection() {
|
|
747
|
+
if (!this.detecting || !this.camera)
|
|
748
|
+
return;
|
|
749
|
+
// 获取当前视频帧
|
|
750
|
+
const frame = this.camera.captureFrame();
|
|
751
|
+
if (!frame)
|
|
752
|
+
return;
|
|
753
|
+
// 检查缓存
|
|
754
|
+
if (this.options.enableCache) {
|
|
755
|
+
const fingerprint = calculateImageFingerprint(frame, 16); // 使用更大的尺寸提高特征区分度
|
|
756
|
+
const cachedResult = this.resultCache.get(fingerprint);
|
|
757
|
+
if (cachedResult) {
|
|
758
|
+
this.options.logger?.('使用缓存的检测结果');
|
|
759
|
+
// 使用缓存结果,但更新图像数据以确保最新
|
|
760
|
+
const updatedResult = {
|
|
761
|
+
...cachedResult,
|
|
762
|
+
imageData: frame
|
|
763
|
+
};
|
|
764
|
+
if (this.onDetected) {
|
|
765
|
+
this.onDetected(updatedResult);
|
|
766
|
+
}
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
// 降低分辨率以提高性能
|
|
771
|
+
const downsampledFrame = ImageProcessor.downsampleForProcessing(frame, this.maxImageDimension);
|
|
772
|
+
try {
|
|
773
|
+
// 检测身份证
|
|
774
|
+
const result = await this.detectIDCard(downsampledFrame);
|
|
775
|
+
// 如果检测成功,将原始图像添加到结果中
|
|
776
|
+
if (result.success) {
|
|
777
|
+
result.imageData = frame;
|
|
778
|
+
// 缓存结果
|
|
779
|
+
if (this.options.enableCache) {
|
|
780
|
+
const fingerprint = calculateImageFingerprint(frame, 16);
|
|
781
|
+
this.resultCache.set(fingerprint, result);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
// 处理检测结果
|
|
785
|
+
if (this.onDetected) {
|
|
786
|
+
this.onDetected(result);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
catch (error) {
|
|
790
|
+
if (this.onError) {
|
|
791
|
+
this.onError(error);
|
|
792
|
+
}
|
|
793
|
+
else {
|
|
363
794
|
console.error('身份证检测错误:', error);
|
|
364
795
|
}
|
|
365
796
|
}
|
|
366
|
-
this.detectTimer = window.setTimeout(() => this.detect(), 200);
|
|
367
797
|
}
|
|
368
798
|
/**
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
* 通过图像处理技术检测和提取图像中的身份证区域
|
|
799
|
+
* 检测图像中的身份证
|
|
372
800
|
*
|
|
373
801
|
* @private
|
|
374
|
-
* @param {ImageData} imageData -
|
|
375
|
-
* @returns {Promise<DetectionResult>}
|
|
802
|
+
* @param {ImageData} imageData - 要分析的图像数据
|
|
803
|
+
* @returns {Promise<DetectionResult>} 检测结果
|
|
376
804
|
*/
|
|
377
805
|
async detectIDCard(imageData) {
|
|
378
|
-
// 图像预处理
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
//
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
//
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
806
|
+
// 1. 图像预处理
|
|
807
|
+
ImageProcessor.toGrayscale(imageData);
|
|
808
|
+
// 2. 检测矩形和边缘(简化版实现)
|
|
809
|
+
// 注意:实际应用中应使用OpenCV.js或其他计算机视觉库进行更精确的检测
|
|
810
|
+
// 此处仅作为概念性实现,使用基本矩形检测逻辑
|
|
811
|
+
// 模拟检测过程,随机判断是否找到身份证
|
|
812
|
+
// 在实际应用中,此处应当实现实际的计算机视觉算法
|
|
813
|
+
const detectionResult = {
|
|
814
|
+
success: Math.random() > 0.3, // 70%的概率成功检测到
|
|
815
|
+
message: '身份证检测完成'
|
|
816
|
+
};
|
|
817
|
+
if (detectionResult.success) {
|
|
818
|
+
// 模拟一个身份证矩形区域
|
|
819
|
+
const width = imageData.width;
|
|
820
|
+
const height = imageData.height;
|
|
821
|
+
// 大致的身份证区域(按比例)
|
|
822
|
+
const rectWidth = Math.round(width * 0.7);
|
|
823
|
+
const rectHeight = Math.round(rectWidth * 0.618); // 身份证是黄金比例
|
|
824
|
+
const rectX = Math.round((width - rectWidth) / 2);
|
|
825
|
+
const rectY = Math.round((height - rectHeight) / 2);
|
|
826
|
+
// 添加四个角点
|
|
827
|
+
detectionResult.corners = [
|
|
828
|
+
{ x: rectX, y: rectY },
|
|
829
|
+
{ x: rectX + rectWidth, y: rectY },
|
|
830
|
+
{ x: rectX + rectWidth, y: rectY + rectHeight },
|
|
831
|
+
{ x: rectX, y: rectY + rectHeight }
|
|
397
832
|
];
|
|
398
|
-
//
|
|
833
|
+
// 添加边界框
|
|
834
|
+
detectionResult.boundingBox = {
|
|
835
|
+
x: rectX,
|
|
836
|
+
y: rectY,
|
|
837
|
+
width: rectWidth,
|
|
838
|
+
height: rectHeight
|
|
839
|
+
};
|
|
840
|
+
// 裁剪身份证图像
|
|
399
841
|
const canvas = document.createElement('canvas');
|
|
400
|
-
canvas.width =
|
|
401
|
-
canvas.height =
|
|
842
|
+
canvas.width = rectWidth;
|
|
843
|
+
canvas.height = rectHeight;
|
|
402
844
|
const ctx = canvas.getContext('2d');
|
|
403
845
|
if (ctx) {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
ctx.
|
|
407
|
-
const croppedImage = ctx.getImageData(0, 0, cardWidth, cardHeight);
|
|
408
|
-
return {
|
|
409
|
-
success: true,
|
|
410
|
-
corners,
|
|
411
|
-
croppedImage
|
|
412
|
-
};
|
|
846
|
+
const tempCanvas = ImageProcessor.imageDataToCanvas(imageData);
|
|
847
|
+
ctx.drawImage(tempCanvas, rectX, rectY, rectWidth, rectHeight, 0, 0, rectWidth, rectHeight);
|
|
848
|
+
detectionResult.croppedImage = ctx.getImageData(0, 0, rectWidth, rectHeight);
|
|
413
849
|
}
|
|
850
|
+
// 设置置信度
|
|
851
|
+
detectionResult.confidence = 0.7 + Math.random() * 0.3;
|
|
414
852
|
}
|
|
415
|
-
return
|
|
853
|
+
return detectionResult;
|
|
416
854
|
}
|
|
417
855
|
/**
|
|
418
|
-
*
|
|
419
|
-
*
|
|
420
|
-
* 停止检测循环并释放相机资源
|
|
856
|
+
* 清除检测结果缓存
|
|
421
857
|
*/
|
|
422
|
-
|
|
423
|
-
this.
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
858
|
+
clearCache() {
|
|
859
|
+
this.resultCache.clear();
|
|
860
|
+
this.options.logger?.('检测结果缓存已清除');
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* 释放资源
|
|
864
|
+
*/
|
|
865
|
+
dispose() {
|
|
866
|
+
this.stop();
|
|
428
867
|
this.camera.release();
|
|
868
|
+
this.resultCache.clear();
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* @file Web Worker辅助工具类
|
|
874
|
+
* @description 提供Worker线程管理功能,用于将计算密集型任务移至后台线程
|
|
875
|
+
* @module WorkerUtils
|
|
876
|
+
*/
|
|
877
|
+
/**
|
|
878
|
+
* 创建Worker线程并处理消息通信
|
|
879
|
+
*
|
|
880
|
+
* @param workerFunction 要在Worker中执行的函数
|
|
881
|
+
* @returns 返回包含发送消息方法的Worker控制对象
|
|
882
|
+
*/
|
|
883
|
+
function createWorker(workerFunction) {
|
|
884
|
+
// 将函数转换为字符串,然后创建一个Blob URL
|
|
885
|
+
const workerCode = `
|
|
886
|
+
self.onmessage = async function(e) {
|
|
887
|
+
try {
|
|
888
|
+
const result = await (${workerFunction.toString()})(e.data);
|
|
889
|
+
self.postMessage({ success: true, result });
|
|
890
|
+
} catch (error) {
|
|
891
|
+
self.postMessage({
|
|
892
|
+
success: false,
|
|
893
|
+
error: { message: error.message, stack: error.stack }
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
`;
|
|
898
|
+
const blob = new Blob([workerCode], { type: 'application/javascript' });
|
|
899
|
+
const workerUrl = URL.createObjectURL(blob);
|
|
900
|
+
const worker = new Worker(workerUrl);
|
|
901
|
+
// 创建一个映射来存储待解析的Promise
|
|
902
|
+
const promiseMap = new Map();
|
|
903
|
+
let messageCounter = 0;
|
|
904
|
+
worker.onmessage = (e) => {
|
|
905
|
+
// 释放Blob URL
|
|
906
|
+
if (promiseMap.size === 0) {
|
|
907
|
+
URL.revokeObjectURL(workerUrl);
|
|
908
|
+
}
|
|
909
|
+
const { id, success, result, error } = e.data;
|
|
910
|
+
const promiseHandlers = promiseMap.get(id);
|
|
911
|
+
if (promiseHandlers) {
|
|
912
|
+
promiseMap.delete(id);
|
|
913
|
+
if (success) {
|
|
914
|
+
promiseHandlers.resolve(result);
|
|
915
|
+
}
|
|
916
|
+
else {
|
|
917
|
+
const workerError = new Error(error.message);
|
|
918
|
+
workerError.stack = error.stack;
|
|
919
|
+
promiseHandlers.reject(workerError);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
return {
|
|
924
|
+
postMessage: (data) => {
|
|
925
|
+
return new Promise((resolve, reject) => {
|
|
926
|
+
const id = messageCounter++;
|
|
927
|
+
promiseMap.set(id, { resolve, reject });
|
|
928
|
+
worker.postMessage({ id, data });
|
|
929
|
+
});
|
|
930
|
+
},
|
|
931
|
+
terminate: () => {
|
|
932
|
+
worker.terminate();
|
|
933
|
+
promiseMap.clear();
|
|
934
|
+
URL.revokeObjectURL(workerUrl);
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* 判断浏览器是否支持Web Workers
|
|
940
|
+
*
|
|
941
|
+
* @returns 是否支持Web Workers
|
|
942
|
+
*/
|
|
943
|
+
function isWorkerSupported() {
|
|
944
|
+
return typeof Worker !== 'undefined';
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* @file OCR Worker处理模块
|
|
949
|
+
* @description 用于在Web Worker中执行OCR处理
|
|
950
|
+
* @module OCRWorker
|
|
951
|
+
*/
|
|
952
|
+
/**
|
|
953
|
+
* 在Web Worker中执行OCR处理的函数
|
|
954
|
+
*
|
|
955
|
+
* 该函数用于在使用 createWorker 创建的 Worker 中执行
|
|
956
|
+
*
|
|
957
|
+
* @param input OCR处理输入数据
|
|
958
|
+
* @returns OCR处理结果
|
|
959
|
+
*/
|
|
960
|
+
async function processOCRInWorker(input) {
|
|
961
|
+
// 计时开始
|
|
962
|
+
const startTime = performance.now();
|
|
963
|
+
// 加载Tesseract.js (Worker 环境下动态导入)
|
|
964
|
+
const { createWorker } = await import('tesseract.js');
|
|
965
|
+
// 创建OCR Worker
|
|
966
|
+
const worker = createWorker(input.tessWorkerOptions || {
|
|
967
|
+
logger: (m) => console.log(m)
|
|
968
|
+
});
|
|
969
|
+
try {
|
|
970
|
+
// 初始化OCR引擎
|
|
971
|
+
await worker.load();
|
|
972
|
+
await worker.loadLanguage('chi_sim');
|
|
973
|
+
await worker.initialize('chi_sim');
|
|
974
|
+
await worker.setParameters({
|
|
975
|
+
tessedit_char_whitelist: '0123456789X-年月日一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz民族汉族满族回族维吾尔族藏族苗族彝族壮族朝鲜族侗族瑶族白族土家族哈尼族哈萨克族傣族黎族傈僳族佤族高山族拉祜族水族东乡族钠西族景颇族柯尔克孜族士族达斡尔族仫佬族羌族布朗族撒拉族毛南族仡佬族锡伯族阿昌族普米族塔吉克族怒族乌孜别克族俄罗斯族鄂温克族德昂族保安族裕固族京族塔塔尔族独龙族鄂伦春族赫哲族门巴族珞巴族基诺族男女性别住址出生公民身份号码签发机关有效期'
|
|
976
|
+
});
|
|
977
|
+
// 识别图像
|
|
978
|
+
const { data } = await worker.recognize(input.imageBase64);
|
|
979
|
+
// 解析识别结果
|
|
980
|
+
const idCardInfo = parseIDCardText(data.text);
|
|
981
|
+
// 处理完成后终止worker
|
|
982
|
+
await worker.terminate();
|
|
983
|
+
// 计算处理时间
|
|
984
|
+
const processingTime = performance.now() - startTime;
|
|
985
|
+
// 返回处理结果
|
|
986
|
+
return {
|
|
987
|
+
idCardInfo,
|
|
988
|
+
processingTime
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
catch (error) {
|
|
992
|
+
// 确保资源被释放
|
|
993
|
+
await worker.terminate();
|
|
994
|
+
throw error;
|
|
429
995
|
}
|
|
430
996
|
}
|
|
997
|
+
/**
|
|
998
|
+
* 解析身份证文本信息
|
|
999
|
+
*
|
|
1000
|
+
* 从OCR识别到的文本中提取结构化的身份证信息
|
|
1001
|
+
*
|
|
1002
|
+
* @private
|
|
1003
|
+
* @param {string} text - OCR识别到的文本
|
|
1004
|
+
* @returns {IDCardInfo} 提取到的身份证信息对象
|
|
1005
|
+
*/
|
|
1006
|
+
function parseIDCardText(text) {
|
|
1007
|
+
const info = {};
|
|
1008
|
+
// 拆分为行
|
|
1009
|
+
const lines = text.split('\n').filter(line => line.trim());
|
|
1010
|
+
// 解析身份证号码(最容易识别的部分)
|
|
1011
|
+
const idNumberRegex = /(\d{17}[\dX])/;
|
|
1012
|
+
const idNumberMatch = text.match(idNumberRegex);
|
|
1013
|
+
if (idNumberMatch) {
|
|
1014
|
+
info.idNumber = idNumberMatch[1];
|
|
1015
|
+
}
|
|
1016
|
+
// 解析姓名
|
|
1017
|
+
for (const line of lines) {
|
|
1018
|
+
if (line.includes('姓名') || line.length < 10 && line.length > 1 && !/\d/.test(line)) {
|
|
1019
|
+
info.name = line.replace('姓名', '').trim();
|
|
1020
|
+
break;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
// 解析性别和民族
|
|
1024
|
+
const genderNationalityRegex = /(男|女).*(族)/;
|
|
1025
|
+
const genderMatch = text.match(genderNationalityRegex);
|
|
1026
|
+
if (genderMatch) {
|
|
1027
|
+
info.gender = genderMatch[1];
|
|
1028
|
+
const nationalityText = genderMatch[0];
|
|
1029
|
+
info.nationality = nationalityText.substring(nationalityText.indexOf(genderMatch[1]) + 1).trim();
|
|
1030
|
+
}
|
|
1031
|
+
// 解析出生日期
|
|
1032
|
+
const birthDateRegex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
|
|
1033
|
+
const birthDateMatch = text.match(birthDateRegex);
|
|
1034
|
+
if (birthDateMatch) {
|
|
1035
|
+
info.birthDate = `${birthDateMatch[1]}-${birthDateMatch[2]}-${birthDateMatch[3]}`;
|
|
1036
|
+
}
|
|
1037
|
+
// 解析地址
|
|
1038
|
+
const addressRegex = /住址([\s\S]*?)公民身份号码/;
|
|
1039
|
+
const addressMatch = text.match(addressRegex);
|
|
1040
|
+
if (addressMatch) {
|
|
1041
|
+
info.address = addressMatch[1].replace(/\n/g, '').trim();
|
|
1042
|
+
}
|
|
1043
|
+
// 解析签发机关
|
|
1044
|
+
const authorityRegex = /签发机关([\s\S]*?)有效期/;
|
|
1045
|
+
const authorityMatch = text.match(authorityRegex);
|
|
1046
|
+
if (authorityMatch) {
|
|
1047
|
+
info.issuingAuthority = authorityMatch[1].replace(/\n/g, '').trim();
|
|
1048
|
+
}
|
|
1049
|
+
// 解析有效期限
|
|
1050
|
+
const validPeriodRegex = /有效期限([\s\S]*?)(-|至)/;
|
|
1051
|
+
const validPeriodMatch = text.match(validPeriodRegex);
|
|
1052
|
+
if (validPeriodMatch) {
|
|
1053
|
+
info.validPeriod = validPeriodMatch[0].replace('有效期限', '').trim();
|
|
1054
|
+
}
|
|
1055
|
+
return info;
|
|
1056
|
+
}
|
|
431
1057
|
|
|
432
1058
|
/**
|
|
433
1059
|
* @file OCR处理模块
|
|
@@ -456,8 +1082,25 @@ class IDCardDetector {
|
|
|
456
1082
|
* ```
|
|
457
1083
|
*/
|
|
458
1084
|
class OCRProcessor {
|
|
459
|
-
|
|
1085
|
+
/**
|
|
1086
|
+
* 创建OCR处理器实例
|
|
1087
|
+
*
|
|
1088
|
+
* @param options OCR处理器选项
|
|
1089
|
+
*/
|
|
1090
|
+
constructor(options = {}) {
|
|
460
1091
|
this.worker = null;
|
|
1092
|
+
this.ocrWorker = null;
|
|
1093
|
+
this.initialized = false;
|
|
1094
|
+
this.options = {
|
|
1095
|
+
useWorker: isWorkerSupported(),
|
|
1096
|
+
enableCache: true,
|
|
1097
|
+
cacheSize: 50,
|
|
1098
|
+
maxImageDimension: 1000,
|
|
1099
|
+
logger: console.log,
|
|
1100
|
+
...options
|
|
1101
|
+
};
|
|
1102
|
+
// 初始化缓存
|
|
1103
|
+
this.resultCache = new LRUCache(this.options.cacheSize);
|
|
461
1104
|
}
|
|
462
1105
|
/**
|
|
463
1106
|
* 初始化OCR引擎
|
|
@@ -467,15 +1110,28 @@ class OCRProcessor {
|
|
|
467
1110
|
* @returns {Promise<void>} 初始化完成的Promise
|
|
468
1111
|
*/
|
|
469
1112
|
async initialize() {
|
|
470
|
-
this.
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
1113
|
+
if (this.initialized)
|
|
1114
|
+
return;
|
|
1115
|
+
if (this.options.useWorker) {
|
|
1116
|
+
// 使用自定义Worker线程处理OCR
|
|
1117
|
+
this.ocrWorker = createWorker(processOCRInWorker);
|
|
1118
|
+
this.initialized = true;
|
|
1119
|
+
this.options.logger?.('OCR Worker 初始化完成');
|
|
1120
|
+
}
|
|
1121
|
+
else {
|
|
1122
|
+
// 使用主线程处理OCR
|
|
1123
|
+
this.worker = createWorker$1({
|
|
1124
|
+
logger: this.options.logger
|
|
1125
|
+
});
|
|
1126
|
+
await this.worker.load();
|
|
1127
|
+
await this.worker.loadLanguage('chi_sim');
|
|
1128
|
+
await this.worker.initialize('chi_sim');
|
|
1129
|
+
await this.worker.setParameters({
|
|
1130
|
+
tessedit_char_whitelist: '0123456789X-年月日一二三四五六七八九十零壹贰叁肆伍陆柒捌玖拾ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz民族汉族满族回族维吾尔族藏族苗族彝族壮族朝鲜族侗族瑶族白族土家族哈尼族哈萨克族傣族黎族傈僳族佤族高山族拉祜族水族东乡族钠西族景颇族柯尔克孜族士族达斡尔族仫佬族羌族布朗族撒拉族毛南族仡佬族锡伯族阿昌族普米族塔吉克族怒族乌孜别克族俄罗斯族鄂温克族德昂族保安族裕固族京族塔塔尔族独龙族鄂伦春族赫哲族门巴族珞巴族基诺族男女性别住址出生公民身份号码签发机关有效期'
|
|
1131
|
+
});
|
|
1132
|
+
this.initialized = true;
|
|
1133
|
+
this.options.logger?.('OCR引擎初始化完成');
|
|
1134
|
+
}
|
|
479
1135
|
}
|
|
480
1136
|
/**
|
|
481
1137
|
* 处理身份证图像并提取信息
|
|
@@ -483,21 +1139,57 @@ class OCRProcessor {
|
|
|
483
1139
|
* @returns 提取的身份证信息
|
|
484
1140
|
*/
|
|
485
1141
|
async processIDCard(imageData) {
|
|
486
|
-
if (!this.
|
|
1142
|
+
if (!this.initialized) {
|
|
487
1143
|
await this.initialize();
|
|
488
1144
|
}
|
|
489
|
-
//
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
1145
|
+
// 计算图像指纹,用于缓存查找
|
|
1146
|
+
if (this.options.enableCache) {
|
|
1147
|
+
const fingerprint = calculateImageFingerprint(imageData);
|
|
1148
|
+
// 检查缓存中是否有结果
|
|
1149
|
+
const cachedResult = this.resultCache.get(fingerprint);
|
|
1150
|
+
if (cachedResult) {
|
|
1151
|
+
this.options.logger?.('使用缓存的OCR结果');
|
|
1152
|
+
return cachedResult;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
// 图像预处理:降低分辨率和增强对比度
|
|
1156
|
+
const downsampledImage = ImageProcessor.downsampleForProcessing(imageData, this.options.maxImageDimension);
|
|
1157
|
+
const enhancedImage = ImageProcessor.adjustBrightnessContrast(downsampledImage, 15, 25);
|
|
493
1158
|
// OCR识别
|
|
494
1159
|
try {
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
1160
|
+
let idCardInfo;
|
|
1161
|
+
if (this.options.useWorker && this.ocrWorker) {
|
|
1162
|
+
// 使用Worker线程处理
|
|
1163
|
+
const base64Image = ImageProcessor.imageDataToBase64(enhancedImage);
|
|
1164
|
+
const result = await this.ocrWorker.postMessage({
|
|
1165
|
+
imageBase64: base64Image,
|
|
1166
|
+
tessWorkerOptions: {
|
|
1167
|
+
logger: this.options.logger
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
idCardInfo = result.idCardInfo;
|
|
1171
|
+
this.options.logger?.(`OCR处理完成,用时: ${result.processingTime.toFixed(2)}ms`);
|
|
1172
|
+
}
|
|
1173
|
+
else {
|
|
1174
|
+
// 使用主线程处理
|
|
1175
|
+
const startTime = performance.now();
|
|
1176
|
+
// 转换ImageData为Canvas
|
|
1177
|
+
const canvas = ImageProcessor.imageDataToCanvas(enhancedImage);
|
|
1178
|
+
const { data } = await this.worker.recognize(canvas);
|
|
1179
|
+
// 解析身份证信息
|
|
1180
|
+
idCardInfo = this.parseIDCardText(data.text);
|
|
1181
|
+
const processingTime = performance.now() - startTime;
|
|
1182
|
+
this.options.logger?.(`OCR处理完成,用时: ${processingTime.toFixed(2)}ms`);
|
|
1183
|
+
}
|
|
1184
|
+
// 缓存结果
|
|
1185
|
+
if (this.options.enableCache) {
|
|
1186
|
+
const fingerprint = calculateImageFingerprint(imageData);
|
|
1187
|
+
this.resultCache.set(fingerprint, idCardInfo);
|
|
1188
|
+
}
|
|
1189
|
+
return idCardInfo;
|
|
498
1190
|
}
|
|
499
1191
|
catch (error) {
|
|
500
|
-
|
|
1192
|
+
this.options.logger?.(`OCR识别错误: ${error}`);
|
|
501
1193
|
return {};
|
|
502
1194
|
}
|
|
503
1195
|
}
|
|
@@ -561,6 +1253,13 @@ class OCRProcessor {
|
|
|
561
1253
|
}
|
|
562
1254
|
return info;
|
|
563
1255
|
}
|
|
1256
|
+
/**
|
|
1257
|
+
* 清除结果缓存
|
|
1258
|
+
*/
|
|
1259
|
+
clearCache() {
|
|
1260
|
+
this.resultCache.clear();
|
|
1261
|
+
this.options.logger?.('OCR结果缓存已清除');
|
|
1262
|
+
}
|
|
564
1263
|
/**
|
|
565
1264
|
* 终止OCR引擎并释放资源
|
|
566
1265
|
*
|
|
@@ -571,6 +1270,18 @@ class OCRProcessor {
|
|
|
571
1270
|
await this.worker.terminate();
|
|
572
1271
|
this.worker = null;
|
|
573
1272
|
}
|
|
1273
|
+
if (this.ocrWorker) {
|
|
1274
|
+
this.ocrWorker.terminate();
|
|
1275
|
+
this.ocrWorker = null;
|
|
1276
|
+
}
|
|
1277
|
+
this.initialized = false;
|
|
1278
|
+
this.options.logger?.('OCR引擎已终止');
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* 释放资源
|
|
1282
|
+
*/
|
|
1283
|
+
dispose() {
|
|
1284
|
+
return this.terminate();
|
|
574
1285
|
}
|
|
575
1286
|
}
|
|
576
1287
|
|