id-scanner-lib 1.6.6 → 1.7.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/dist/id-scanner-lib.esm.js +915 -838
- package/dist/id-scanner-lib.esm.js.map +1 -1
- package/dist/id-scanner-lib.js +915 -838
- package/dist/id-scanner-lib.js.map +1 -1
- package/package.json +1 -1
- package/src/core/camera-manager.ts +43 -76
- package/src/core/camera-stream-manager.ts +318 -0
- package/src/core/logger.ts +158 -81
- package/src/modules/face/face-comparator.ts +150 -0
- package/src/modules/face/face-detector-options.ts +104 -0
- package/src/modules/face/face-detector.ts +121 -376
- package/src/modules/face/face-detector.ts.bak +991 -0
- package/src/modules/face/face-model-loader.ts +222 -0
- package/src/modules/face/face-result-converter.ts +225 -0
- package/src/modules/face/face-tracker.ts +207 -0
- package/src/modules/face/liveness-detector.ts +2 -2
- package/src/modules/id-card/id-card-text-parser.ts +151 -0
- package/src/modules/id-card/ocr-processor.ts +20 -257
- package/src/modules/id-card/ocr-worker.ts +2 -183
- package/src/utils/canvas-pool.ts +273 -0
- package/src/utils/edge-detector.ts +232 -0
- package/src/utils/image-processing.ts +110 -446
- package/src/utils/index.ts +1 -0
- package/src/core/plugin-manager.ts +0 -429
package/dist/id-scanner-lib.js
CHANGED
|
@@ -284,18 +284,20 @@
|
|
|
284
284
|
handle(entry) {
|
|
285
285
|
const timestamp = new Date(entry.timestamp).toISOString();
|
|
286
286
|
const prefix = `[${timestamp}] [${entry.level.toUpperCase()}] [${entry.tag}]`;
|
|
287
|
+
// 优先使用 error,其次使用 data
|
|
288
|
+
const extra = entry.error || entry.data || '';
|
|
287
289
|
switch (entry.level) {
|
|
288
290
|
case exports.LoggerLevel.DEBUG:
|
|
289
|
-
console.debug(prefix, entry.message,
|
|
291
|
+
console.debug(prefix, entry.message, extra);
|
|
290
292
|
break;
|
|
291
293
|
case exports.LoggerLevel.INFO:
|
|
292
|
-
console.info(prefix, entry.message,
|
|
294
|
+
console.info(prefix, entry.message, extra);
|
|
293
295
|
break;
|
|
294
296
|
case exports.LoggerLevel.WARN:
|
|
295
|
-
console.warn(prefix, entry.message,
|
|
297
|
+
console.warn(prefix, entry.message, extra);
|
|
296
298
|
break;
|
|
297
299
|
case exports.LoggerLevel.ERROR:
|
|
298
|
-
console.error(prefix, entry.message,
|
|
300
|
+
console.error(prefix, entry.message, extra);
|
|
299
301
|
break;
|
|
300
302
|
// 输出什么也不做
|
|
301
303
|
}
|
|
@@ -369,10 +371,13 @@
|
|
|
369
371
|
this.queue = [];
|
|
370
372
|
/** 定时发送的计时器ID */
|
|
371
373
|
this.timerId = null;
|
|
374
|
+
/** 当前连续失败计数 */
|
|
375
|
+
this.consecutiveFailures = 0;
|
|
372
376
|
this.endpoint = endpoint;
|
|
373
377
|
this.maxQueueSize = maxQueueSize;
|
|
374
378
|
this.flushInterval = flushInterval;
|
|
375
379
|
this.isBrowser = typeof window !== 'undefined' && typeof window.addEventListener === 'function';
|
|
380
|
+
this.maxConsecutiveFailures = 10;
|
|
376
381
|
// 设置定时发送
|
|
377
382
|
this.startTimer();
|
|
378
383
|
// 页面卸载前尝试发送剩余日志
|
|
@@ -402,47 +407,55 @@
|
|
|
402
407
|
flush() {
|
|
403
408
|
if (this.queue.length === 0)
|
|
404
409
|
return;
|
|
405
|
-
|
|
406
|
-
this.
|
|
407
|
-
|
|
408
|
-
const sendCount = this._sendCount || 0;
|
|
409
|
-
this._sendCount = sendCount + 1;
|
|
410
|
-
// 如果发送次数过多,停止发送以防止无限循环
|
|
411
|
-
if (sendCount > 10) {
|
|
412
|
-
console.warn('RemoteLogHandler: Too many failed sends, stopping. Clear queue.');
|
|
410
|
+
// 如果连续失败次数过多,停止发送以防止无限循环
|
|
411
|
+
if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
|
|
412
|
+
console.warn('RemoteLogHandler: Too many consecutive failures, stopping. Clear queue.');
|
|
413
413
|
this.queue = [];
|
|
414
|
-
this.
|
|
414
|
+
this.consecutiveFailures = 0;
|
|
415
415
|
return;
|
|
416
416
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
417
|
+
const entriesToSend = [...this.queue];
|
|
418
|
+
this.queue = [];
|
|
419
|
+
this.sendLogEntries(entriesToSend);
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* 发送日志条目到远程服务器
|
|
423
|
+
* @param entries 日志条目数组
|
|
424
|
+
*/
|
|
425
|
+
sendLogEntries(entries) {
|
|
426
|
+
if (entries.length === 0)
|
|
427
|
+
return;
|
|
428
|
+
const controller = new AbortController();
|
|
429
|
+
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s 超时
|
|
430
|
+
fetch(this.endpoint, {
|
|
431
|
+
method: 'POST',
|
|
432
|
+
headers: {
|
|
433
|
+
'Content-Type': 'application/json'
|
|
434
|
+
},
|
|
435
|
+
body: JSON.stringify(entries),
|
|
436
|
+
keepalive: true,
|
|
437
|
+
signal: controller.signal
|
|
438
|
+
}).then(() => {
|
|
439
|
+
clearTimeout(timeoutId);
|
|
440
|
+
this.consecutiveFailures = 0; // 发送成功,重置失败计数
|
|
441
|
+
}).catch((err) => {
|
|
442
|
+
clearTimeout(timeoutId);
|
|
443
|
+
console.error('Failed to send logs to remote server:', err);
|
|
444
|
+
this.consecutiveFailures++;
|
|
445
|
+
// 如果失败次数过多,丢弃日志防止内存泄漏
|
|
446
|
+
if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
|
|
447
|
+
console.warn('RemoteLogHandler: Max consecutive failures exceeded, discarding logs');
|
|
448
|
+
this.queue = [];
|
|
449
|
+
this.consecutiveFailures = 0;
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
// 失败时把日志放回队列,但防止无限增长
|
|
453
|
+
const maxReturn = Math.min(entries.length, this.maxQueueSize - this.queue.length);
|
|
454
|
+
if (maxReturn > 0) {
|
|
455
|
+
const returnedEntries = entries.slice(0, maxReturn);
|
|
456
|
+
this.queue = [...returnedEntries, ...this.queue];
|
|
457
|
+
}
|
|
458
|
+
});
|
|
446
459
|
}
|
|
447
460
|
/**
|
|
448
461
|
* 开始定时发送
|
|
@@ -452,7 +465,7 @@
|
|
|
452
465
|
return;
|
|
453
466
|
if (this.timerId !== null)
|
|
454
467
|
return;
|
|
455
|
-
this.timerId =
|
|
468
|
+
this.timerId = setInterval(() => {
|
|
456
469
|
this.flush();
|
|
457
470
|
}, this.flushInterval);
|
|
458
471
|
}
|
|
@@ -461,7 +474,7 @@
|
|
|
461
474
|
*/
|
|
462
475
|
stopTimer() {
|
|
463
476
|
if (this.timerId !== null) {
|
|
464
|
-
|
|
477
|
+
clearInterval(this.timerId);
|
|
465
478
|
this.timerId = null;
|
|
466
479
|
}
|
|
467
480
|
}
|
|
@@ -538,37 +551,57 @@
|
|
|
538
551
|
* 记录调试级别日志
|
|
539
552
|
* @param tag 标签
|
|
540
553
|
* @param message 消息
|
|
541
|
-
* @param
|
|
554
|
+
* @param errorOrData 错误对象或结构化数据
|
|
542
555
|
*/
|
|
543
|
-
debug(tag, message,
|
|
544
|
-
|
|
556
|
+
debug(tag, message, errorOrData) {
|
|
557
|
+
if (errorOrData instanceof Error) {
|
|
558
|
+
this.log(exports.LoggerLevel.DEBUG, tag, message, errorOrData);
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
this.logWithData(exports.LoggerLevel.DEBUG, tag, message, errorOrData);
|
|
562
|
+
}
|
|
545
563
|
}
|
|
546
564
|
/**
|
|
547
565
|
* 记录信息级别日志
|
|
548
566
|
* @param tag 标签
|
|
549
567
|
* @param message 消息
|
|
550
|
-
* @param
|
|
568
|
+
* @param errorOrData 错误对象或结构化数据
|
|
551
569
|
*/
|
|
552
|
-
info(tag, message,
|
|
553
|
-
|
|
570
|
+
info(tag, message, errorOrData) {
|
|
571
|
+
if (errorOrData instanceof Error) {
|
|
572
|
+
this.log(exports.LoggerLevel.INFO, tag, message, errorOrData);
|
|
573
|
+
}
|
|
574
|
+
else {
|
|
575
|
+
this.logWithData(exports.LoggerLevel.INFO, tag, message, errorOrData);
|
|
576
|
+
}
|
|
554
577
|
}
|
|
555
578
|
/**
|
|
556
579
|
* 记录警告级别日志
|
|
557
580
|
* @param tag 标签
|
|
558
581
|
* @param message 消息
|
|
559
|
-
* @param
|
|
582
|
+
* @param errorOrData 错误对象或结构化数据
|
|
560
583
|
*/
|
|
561
|
-
warn(tag, message,
|
|
562
|
-
|
|
584
|
+
warn(tag, message, errorOrData) {
|
|
585
|
+
if (errorOrData instanceof Error) {
|
|
586
|
+
this.log(exports.LoggerLevel.WARN, tag, message, errorOrData);
|
|
587
|
+
}
|
|
588
|
+
else {
|
|
589
|
+
this.logWithData(exports.LoggerLevel.WARN, tag, message, errorOrData);
|
|
590
|
+
}
|
|
563
591
|
}
|
|
564
592
|
/**
|
|
565
593
|
* 记录错误级别日志
|
|
566
594
|
* @param tag 标签
|
|
567
595
|
* @param message 消息
|
|
568
|
-
* @param
|
|
596
|
+
* @param errorOrData 错误对象或结构化数据
|
|
569
597
|
*/
|
|
570
|
-
error(tag, message,
|
|
571
|
-
|
|
598
|
+
error(tag, message, errorOrData) {
|
|
599
|
+
if (errorOrData instanceof Error) {
|
|
600
|
+
this.log(exports.LoggerLevel.ERROR, tag, message, errorOrData);
|
|
601
|
+
}
|
|
602
|
+
else {
|
|
603
|
+
this.logWithData(exports.LoggerLevel.ERROR, tag, message, errorOrData);
|
|
604
|
+
}
|
|
572
605
|
}
|
|
573
606
|
/**
|
|
574
607
|
* 创建标记了特定标签的日志记录器
|
|
@@ -613,6 +646,42 @@
|
|
|
613
646
|
this.consoleOutput(entry);
|
|
614
647
|
}
|
|
615
648
|
}
|
|
649
|
+
/**
|
|
650
|
+
* 记录日志(支持结构化数据)
|
|
651
|
+
* @param level 日志级别
|
|
652
|
+
* @param tag 标签
|
|
653
|
+
* @param message 消息
|
|
654
|
+
* @param data 结构化数据
|
|
655
|
+
*/
|
|
656
|
+
logWithData(level, tag, message, data) {
|
|
657
|
+
// 检查日志级别
|
|
658
|
+
const levelValue = this.getLevelValue(level);
|
|
659
|
+
const currentLevelValue = this.getLevelValue(this.logLevel);
|
|
660
|
+
if (levelValue < currentLevelValue) {
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
// 创建日志条目
|
|
664
|
+
const entry = {
|
|
665
|
+
timestamp: Date.now(),
|
|
666
|
+
level: level,
|
|
667
|
+
tag: tag || this.defaultTag,
|
|
668
|
+
message,
|
|
669
|
+
data
|
|
670
|
+
};
|
|
671
|
+
// 分发到所有处理程序
|
|
672
|
+
for (const handler of this.handlers) {
|
|
673
|
+
try {
|
|
674
|
+
handler.handle(entry);
|
|
675
|
+
}
|
|
676
|
+
catch (handlerError) {
|
|
677
|
+
console.error(`[Logger] 处理程序错误:`, handlerError);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
// 如果没有处理程序,使用控制台
|
|
681
|
+
if (this.handlers.length === 0) {
|
|
682
|
+
this.consoleOutput(entry);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
616
685
|
/**
|
|
617
686
|
* 控制台输出
|
|
618
687
|
* @param entry 日志条目
|
|
@@ -620,18 +689,20 @@
|
|
|
620
689
|
consoleOutput(entry) {
|
|
621
690
|
const timestamp = new Date(entry.timestamp).toISOString();
|
|
622
691
|
const prefix = `[${timestamp}] [${entry.level.toUpperCase()}] [${entry.tag}]`;
|
|
692
|
+
// 构造日志内容:错误对象或数据对象
|
|
693
|
+
const extra = entry.error || entry.data || '';
|
|
623
694
|
switch (entry.level) {
|
|
624
695
|
case exports.LoggerLevel.DEBUG:
|
|
625
|
-
console.debug(`${prefix} ${entry.message}`,
|
|
696
|
+
console.debug(`${prefix} ${entry.message}`, extra);
|
|
626
697
|
break;
|
|
627
698
|
case exports.LoggerLevel.INFO:
|
|
628
|
-
console.info(`${prefix} ${entry.message}`,
|
|
699
|
+
console.info(`${prefix} ${entry.message}`, extra);
|
|
629
700
|
break;
|
|
630
701
|
case exports.LoggerLevel.WARN:
|
|
631
|
-
console.warn(`${prefix} ${entry.message}`,
|
|
702
|
+
console.warn(`${prefix} ${entry.message}`, extra);
|
|
632
703
|
break;
|
|
633
704
|
case exports.LoggerLevel.ERROR:
|
|
634
|
-
console.error(`${prefix} ${entry.message}`,
|
|
705
|
+
console.error(`${prefix} ${entry.message}`, extra);
|
|
635
706
|
break;
|
|
636
707
|
}
|
|
637
708
|
}
|
|
@@ -1598,93 +1669,685 @@
|
|
|
1598
1669
|
}
|
|
1599
1670
|
|
|
1600
1671
|
/**
|
|
1601
|
-
*
|
|
1602
|
-
* @description 提供图像预处理功能,用于提高OCR识别率
|
|
1603
|
-
* @module ImageProcessor
|
|
1604
|
-
* @version 1.3.2
|
|
1672
|
+
* 格式化日期字符串为标准格式 (YYYY-MM-DD)
|
|
1605
1673
|
*/
|
|
1674
|
+
function formatDateString(dateStr) {
|
|
1675
|
+
const dateMatch = dateStr.match(/(\d{4})[-\.\u5e74\s]*(\d{1,2})[-\.\u6708\s]*(\d{1,2})[日]*/);
|
|
1676
|
+
if (dateMatch) {
|
|
1677
|
+
const year = dateMatch[1];
|
|
1678
|
+
const month = dateMatch[2].padStart(2, "0");
|
|
1679
|
+
const day = dateMatch[3].padStart(2, "0");
|
|
1680
|
+
return `${year}-${month}-${day}`;
|
|
1681
|
+
}
|
|
1682
|
+
if (/^\d{8}$/.test(dateStr)) {
|
|
1683
|
+
const year = dateStr.substring(0, 4);
|
|
1684
|
+
const month = dateStr.substring(4, 6);
|
|
1685
|
+
const day = dateStr.substring(6, 8);
|
|
1686
|
+
return `${year}-${month}-${day}`;
|
|
1687
|
+
}
|
|
1688
|
+
return dateStr;
|
|
1689
|
+
}
|
|
1606
1690
|
/**
|
|
1607
|
-
*
|
|
1691
|
+
* IDCardTextParser - 统一解析身份证OCR文本
|
|
1692
|
+
* 提取 ocr-processor.ts 和 ocr-worker.ts 中的解析逻辑
|
|
1693
|
+
*/
|
|
1694
|
+
class IDCardTextParser {
|
|
1695
|
+
/**
|
|
1696
|
+
* 解析身份证文本
|
|
1697
|
+
* @param text OCR识别的原始文本
|
|
1698
|
+
* @returns 解析后的身份证信息
|
|
1699
|
+
*/
|
|
1700
|
+
static parse(text) {
|
|
1701
|
+
const info = {};
|
|
1702
|
+
const processedText = text.replace(/\s+/g, " ").trim();
|
|
1703
|
+
const lines = processedText.split("\n").filter((line) => line.trim());
|
|
1704
|
+
// 1. 解析身份证号码
|
|
1705
|
+
const idNumberRegex = /(\d{17}[\dX])/;
|
|
1706
|
+
const idNumberWithPrefixRegex = /公民身份号码[\s\:]*(\d{17}[\dX])/;
|
|
1707
|
+
const basicMatch = processedText.match(idNumberRegex);
|
|
1708
|
+
const prefixMatch = processedText.match(idNumberWithPrefixRegex);
|
|
1709
|
+
if (prefixMatch && prefixMatch[1]) {
|
|
1710
|
+
info.idNumber = prefixMatch[1];
|
|
1711
|
+
}
|
|
1712
|
+
else if (basicMatch && basicMatch[1]) {
|
|
1713
|
+
info.idNumber = basicMatch[1];
|
|
1714
|
+
}
|
|
1715
|
+
// 2. 解析姓名
|
|
1716
|
+
const nameWithLabelRegex = /姓名[\s\:]*([一-龥]{2,4})/;
|
|
1717
|
+
const nameMatch = processedText.match(nameWithLabelRegex);
|
|
1718
|
+
if (nameMatch && nameMatch[1]) {
|
|
1719
|
+
info.name = nameMatch[1].trim();
|
|
1720
|
+
}
|
|
1721
|
+
else {
|
|
1722
|
+
for (const line of lines) {
|
|
1723
|
+
if (line.length >= 2 && line.length <= 5 && /^[一-龥]+$/.test(line) &&
|
|
1724
|
+
!/性别|民族|住址|公民|签发|有效/.test(line)) {
|
|
1725
|
+
info.name = line.trim();
|
|
1726
|
+
break;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
// 3. 解析性别和民族
|
|
1731
|
+
const genderAndNationalityRegex = /性别[\s\:]*([男女])[\s ]*民族[\s\:]*([一-龥]+族)/;
|
|
1732
|
+
const genderOnlyRegex = /性别[\s\:]*([男女])/;
|
|
1733
|
+
const nationalityOnlyRegex = /民族[\s\:]*([一-龥]+族)/;
|
|
1734
|
+
const genderNationalityMatch = processedText.match(genderAndNationalityRegex);
|
|
1735
|
+
const genderOnlyMatch = processedText.match(genderOnlyRegex);
|
|
1736
|
+
const nationalityOnlyMatch = processedText.match(nationalityOnlyRegex);
|
|
1737
|
+
if (genderNationalityMatch) {
|
|
1738
|
+
info.gender = genderNationalityMatch[1];
|
|
1739
|
+
info.ethnicity = genderNationalityMatch[2];
|
|
1740
|
+
}
|
|
1741
|
+
else {
|
|
1742
|
+
if (genderOnlyMatch)
|
|
1743
|
+
info.gender = genderOnlyMatch[1];
|
|
1744
|
+
if (nationalityOnlyMatch)
|
|
1745
|
+
info.ethnicity = nationalityOnlyMatch[1];
|
|
1746
|
+
}
|
|
1747
|
+
// 4. 判断身份证类型
|
|
1748
|
+
if (processedText.includes('出生') || processedText.includes('公民身份号码')) {
|
|
1749
|
+
info.type = exports.IDCardType.FRONT;
|
|
1750
|
+
}
|
|
1751
|
+
else if (processedText.includes('签发机关') || processedText.includes('有效期')) {
|
|
1752
|
+
info.type = exports.IDCardType.BACK;
|
|
1753
|
+
}
|
|
1754
|
+
// 5. 解析出生日期
|
|
1755
|
+
const birthDateRegex1 = /出生[\s\:]*(\d{4})年(\d{1,2})月(\d{1,2})[日号]/;
|
|
1756
|
+
const birthDateRegex2 = /出生[\s\:]*(\d{4})[-\/\.](\d{1,2})[-\/\.](\d{1,2})/;
|
|
1757
|
+
const birthDateRegex3 = /出生日期[\s\:]*(\d{4})[-\/\.\u5e74](\d{1,2})[-\/\.\u6708](\d{1,2})[日号]?/;
|
|
1758
|
+
const birthDateMatch = processedText.match(birthDateRegex1) || processedText.match(birthDateRegex2) || processedText.match(birthDateRegex3);
|
|
1759
|
+
if (!birthDateMatch && info.idNumber && info.idNumber.length === 18) {
|
|
1760
|
+
const year = info.idNumber.substring(6, 10);
|
|
1761
|
+
const month = info.idNumber.substring(10, 12);
|
|
1762
|
+
const day = info.idNumber.substring(12, 14);
|
|
1763
|
+
info.birthDate = `${year}-${month}-${day}`;
|
|
1764
|
+
}
|
|
1765
|
+
else if (birthDateMatch) {
|
|
1766
|
+
const year = birthDateMatch[1];
|
|
1767
|
+
const month = birthDateMatch[2].padStart(2, "0");
|
|
1768
|
+
const day = birthDateMatch[3].padStart(2, "0");
|
|
1769
|
+
info.birthDate = `${year}-${month}-${day}`;
|
|
1770
|
+
}
|
|
1771
|
+
// 6. 解析地址
|
|
1772
|
+
const addressRegex1 = /住址[\s\:]*([\s\S]*?)(?=公民身份|出生|性别|签发)/;
|
|
1773
|
+
const addressRegex2 = /住址[\s\:]*([一-龥a-zA-Z0-9\s\.\-]+)/;
|
|
1774
|
+
const addressMatch = processedText.match(addressRegex1) || processedText.match(addressRegex2);
|
|
1775
|
+
if (addressMatch && addressMatch[1]) {
|
|
1776
|
+
info.address = addressMatch[1].replace(/\s+/g, "").replace(/\n/g, "").trim();
|
|
1777
|
+
if (info.address.length > 70)
|
|
1778
|
+
info.address = info.address.substring(0, 70);
|
|
1779
|
+
if (!/[一-龥]/.test(info.address))
|
|
1780
|
+
info.address = '';
|
|
1781
|
+
}
|
|
1782
|
+
// 7. 解析签发机关
|
|
1783
|
+
const authorityRegex1 = /签发机关[\s\:]*([\s\S]*?)(?=有效|公民|出生|\d{8}|$)/;
|
|
1784
|
+
const authorityRegex2 = /签发机关[\s\:]*([一-龥\s]+)/;
|
|
1785
|
+
const authorityMatch = processedText.match(authorityRegex1) || processedText.match(authorityRegex2);
|
|
1786
|
+
if (authorityMatch && authorityMatch[1]) {
|
|
1787
|
+
info.issueAuthority = authorityMatch[1].replace(/\s+/g, "").replace(/\n/g, "").trim();
|
|
1788
|
+
}
|
|
1789
|
+
// 8. 解析有效期限
|
|
1790
|
+
const validPeriodRegex1 = /有效期限[\s\:]*(\d{4}[-\.\u5e74\s]\d{1,2}[-\.\u6708\s]\d{1,2}[日\s]*)[-\s]*(至|-)[-\s]*(\d{4}[-\.\u5e74\s]\d{1,2}[-\.\u6708\s]\d{1,2}[日]*|[永久长期]*)/;
|
|
1791
|
+
const validPeriodRegex2 = /有效期限[\s\:]*(\d{8})[-\s]*(至|-)[-\s]*(\d{8}|[永久长期]*)/;
|
|
1792
|
+
const validPeriodMatch = processedText.match(validPeriodRegex1) || processedText.match(validPeriodRegex2);
|
|
1793
|
+
if (validPeriodMatch && validPeriodMatch[1] && validPeriodMatch[3]) {
|
|
1794
|
+
const startDate = formatDateString(validPeriodMatch[1]);
|
|
1795
|
+
const endDate = /\d/.test(validPeriodMatch[3]) ? formatDateString(validPeriodMatch[3]) : '长期有效';
|
|
1796
|
+
info.validFrom = startDate;
|
|
1797
|
+
info.validTo = endDate;
|
|
1798
|
+
info.validPeriod = `${startDate}-${endDate}`;
|
|
1799
|
+
}
|
|
1800
|
+
else if (validPeriodMatch) {
|
|
1801
|
+
info.validPeriod = validPeriodMatch[0].replace("有效期限", "").trim();
|
|
1802
|
+
}
|
|
1803
|
+
return info;
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
/**
|
|
1808
|
+
* @file Canvas 对象池
|
|
1809
|
+
* @description 提供 Canvas 元素的复用机制,减少内存分配和 GC 压力
|
|
1810
|
+
* @module utils/canvas-pool
|
|
1811
|
+
*/
|
|
1812
|
+
/**
|
|
1813
|
+
* Canvas 对象池
|
|
1608
1814
|
*
|
|
1609
|
-
*
|
|
1815
|
+
* 复用 Canvas 元素,避免频繁创建和销毁导致的内存抖动
|
|
1816
|
+
*
|
|
1817
|
+
* @example
|
|
1818
|
+
* ```typescript
|
|
1819
|
+
* const pool = CanvasPool.getInstance();
|
|
1820
|
+
* const { canvas, context } = pool.acquire(100, 200);
|
|
1821
|
+
* // 使用 canvas 进行绘制...
|
|
1822
|
+
* pool.release(canvas);
|
|
1823
|
+
* ```
|
|
1610
1824
|
*/
|
|
1611
|
-
class
|
|
1825
|
+
class CanvasPool {
|
|
1612
1826
|
/**
|
|
1613
|
-
*
|
|
1614
|
-
*
|
|
1615
|
-
* @param {ImageData} imageData - 要转换的图像数据
|
|
1616
|
-
* @returns {HTMLCanvasElement} 包含图像的Canvas元素
|
|
1827
|
+
* 获取单例实例
|
|
1617
1828
|
*/
|
|
1618
|
-
static
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
canvas.height = imageData.height;
|
|
1622
|
-
const ctx = canvas.getContext("2d");
|
|
1623
|
-
if (ctx) {
|
|
1624
|
-
ctx.putImageData(imageData, 0, 0);
|
|
1829
|
+
static getInstance() {
|
|
1830
|
+
if (!CanvasPool.instance) {
|
|
1831
|
+
CanvasPool.instance = new CanvasPool();
|
|
1625
1832
|
}
|
|
1626
|
-
return
|
|
1833
|
+
return CanvasPool.instance;
|
|
1627
1834
|
}
|
|
1628
1835
|
/**
|
|
1629
|
-
*
|
|
1630
|
-
*
|
|
1631
|
-
* @param {HTMLCanvasElement} canvas - 要转换的Canvas元素
|
|
1632
|
-
* @returns {ImageData|null} Canvas的图像数据,如果获取失败则返回null
|
|
1836
|
+
* 重置单例实例(主要用于测试)
|
|
1633
1837
|
*/
|
|
1634
|
-
static
|
|
1635
|
-
|
|
1636
|
-
|
|
1838
|
+
static resetInstance() {
|
|
1839
|
+
if (CanvasPool.instance) {
|
|
1840
|
+
CanvasPool.instance.dispose();
|
|
1841
|
+
CanvasPool.instance = null;
|
|
1842
|
+
}
|
|
1637
1843
|
}
|
|
1638
1844
|
/**
|
|
1639
|
-
*
|
|
1640
|
-
*
|
|
1641
|
-
* @param imageData 原始图像数据
|
|
1642
|
-
* @param brightness 亮度调整值 (-100到100)
|
|
1643
|
-
* @param contrast 对比度调整值 (-100到100)
|
|
1644
|
-
* @returns 处理后的图像数据
|
|
1845
|
+
* 私有构造函数
|
|
1645
1846
|
*/
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1847
|
+
constructor() {
|
|
1848
|
+
/** Canvas 池存储 */
|
|
1849
|
+
this.pool = new Map();
|
|
1850
|
+
/** 已借出的 Canvas */
|
|
1851
|
+
this.borrowed = new Map();
|
|
1852
|
+
/** 最大池大小(每个尺寸) */
|
|
1853
|
+
this.maxPoolSize = 4;
|
|
1854
|
+
/** Canvas 尺寸容差(允许一定范围的尺寸复用) */
|
|
1855
|
+
this.sizeTolerance = 10;
|
|
1856
|
+
// 页面卸载前清理
|
|
1857
|
+
if (typeof window !== 'undefined') {
|
|
1858
|
+
window.addEventListener('beforeunload', () => this.dispose());
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
/**
|
|
1862
|
+
* 生成尺寸键
|
|
1863
|
+
* @param width 宽度
|
|
1864
|
+
* @param height 高度
|
|
1865
|
+
*/
|
|
1866
|
+
getSizeKey(width, height) {
|
|
1867
|
+
return `${width}x${height}`;
|
|
1868
|
+
}
|
|
1869
|
+
/**
|
|
1870
|
+
* 查找匹配的尺寸键(考虑容差)
|
|
1871
|
+
* @param width 宽度
|
|
1872
|
+
* @param height 高度
|
|
1873
|
+
*/
|
|
1874
|
+
findMatchingSizeKey(width, height) {
|
|
1875
|
+
for (const [key, items] of this.pool.entries()) {
|
|
1876
|
+
const [w, h] = key.split('x').map(Number);
|
|
1877
|
+
if (Math.abs(w - width) <= this.sizeTolerance &&
|
|
1878
|
+
Math.abs(h - height) <= this.sizeTolerance) {
|
|
1879
|
+
// 找到可用的
|
|
1880
|
+
const available = items.filter(item => !item.inUse);
|
|
1881
|
+
if (available.length > 0) {
|
|
1882
|
+
return key;
|
|
1883
|
+
}
|
|
1661
1884
|
}
|
|
1662
|
-
// Alpha 通道保持不变
|
|
1663
1885
|
}
|
|
1664
|
-
return
|
|
1886
|
+
return null;
|
|
1665
1887
|
}
|
|
1666
1888
|
/**
|
|
1667
|
-
*
|
|
1889
|
+
* 从池中获取 Canvas
|
|
1668
1890
|
*
|
|
1669
|
-
* @param
|
|
1670
|
-
* @
|
|
1891
|
+
* @param width 宽度
|
|
1892
|
+
* @param height 高度
|
|
1893
|
+
* @returns Canvas 和其上下文
|
|
1894
|
+
*/
|
|
1895
|
+
acquire(width, height) {
|
|
1896
|
+
// 先尝试精确匹配
|
|
1897
|
+
let sizeKey = this.getSizeKey(width, height);
|
|
1898
|
+
let items = this.pool.get(sizeKey);
|
|
1899
|
+
// 如果没有精确匹配,尝试模糊匹配
|
|
1900
|
+
if (!items || items.every(item => item.inUse)) {
|
|
1901
|
+
const matchedKey = this.findMatchingSizeKey(width, height);
|
|
1902
|
+
if (matchedKey) {
|
|
1903
|
+
sizeKey = matchedKey;
|
|
1904
|
+
items = this.pool.get(sizeKey);
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
// 如果没有可用的,创建一个新的
|
|
1908
|
+
if (!items || items.every(item => item.inUse)) {
|
|
1909
|
+
const canvas = document.createElement('canvas');
|
|
1910
|
+
canvas.width = width;
|
|
1911
|
+
canvas.height = height;
|
|
1912
|
+
const context = canvas.getContext('2d');
|
|
1913
|
+
const item = {
|
|
1914
|
+
canvas,
|
|
1915
|
+
context,
|
|
1916
|
+
inUse: true,
|
|
1917
|
+
lastUsed: Date.now(),
|
|
1918
|
+
sizeKey: this.getSizeKey(width, height)
|
|
1919
|
+
};
|
|
1920
|
+
// 如果池已满,移除最老的
|
|
1921
|
+
if (!items) {
|
|
1922
|
+
items = [];
|
|
1923
|
+
this.pool.set(sizeKey, items);
|
|
1924
|
+
}
|
|
1925
|
+
else if (items.length >= this.maxPoolSize) {
|
|
1926
|
+
// 找到最老的未使用项并移除
|
|
1927
|
+
let oldestIdx = 0;
|
|
1928
|
+
let oldestTime = Infinity;
|
|
1929
|
+
items.forEach((item, idx) => {
|
|
1930
|
+
if (!item.inUse && item.lastUsed < oldestTime) {
|
|
1931
|
+
oldestTime = item.lastUsed;
|
|
1932
|
+
oldestIdx = idx;
|
|
1933
|
+
}
|
|
1934
|
+
});
|
|
1935
|
+
const removed = items.splice(oldestIdx, 1)[0];
|
|
1936
|
+
this.borrowed.delete(removed.canvas);
|
|
1937
|
+
}
|
|
1938
|
+
items.push(item);
|
|
1939
|
+
this.borrowed.set(canvas, item);
|
|
1940
|
+
return { canvas, context };
|
|
1941
|
+
}
|
|
1942
|
+
// 找到一个空闲的
|
|
1943
|
+
const available = items.find(item => !item.inUse);
|
|
1944
|
+
available.inUse = true;
|
|
1945
|
+
available.lastUsed = Date.now();
|
|
1946
|
+
// 如果尺寸变化,更新 canvas
|
|
1947
|
+
if (available.canvas.width !== width || available.canvas.height !== height) {
|
|
1948
|
+
available.canvas.width = width;
|
|
1949
|
+
available.canvas.height = height;
|
|
1950
|
+
available.sizeKey = sizeKey;
|
|
1951
|
+
}
|
|
1952
|
+
// 清除之前的上下文状态
|
|
1953
|
+
available.context.setTransform(1, 0, 0, 1, 0, 0);
|
|
1954
|
+
available.context.clearRect(0, 0, width, height);
|
|
1955
|
+
this.borrowed.set(available.canvas, available);
|
|
1956
|
+
return { canvas: available.canvas, context: available.context };
|
|
1957
|
+
}
|
|
1958
|
+
/**
|
|
1959
|
+
* 释放 Canvas 回池中
|
|
1960
|
+
*
|
|
1961
|
+
* @param canvas 要释放的 Canvas
|
|
1671
1962
|
*/
|
|
1672
|
-
|
|
1673
|
-
const
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
const gray = data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11;
|
|
1678
|
-
data[i] = data[i + 1] = data[i + 2] = gray;
|
|
1963
|
+
release(canvas) {
|
|
1964
|
+
const item = this.borrowed.get(canvas);
|
|
1965
|
+
if (!item) {
|
|
1966
|
+
// 不属于我们管理的 Canvas,忽略
|
|
1967
|
+
return;
|
|
1679
1968
|
}
|
|
1680
|
-
|
|
1969
|
+
item.inUse = false;
|
|
1970
|
+
item.lastUsed = Date.now();
|
|
1971
|
+
this.borrowed.delete(canvas);
|
|
1681
1972
|
}
|
|
1682
1973
|
/**
|
|
1683
|
-
*
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1974
|
+
* 批量释放所有借出的 Canvas
|
|
1975
|
+
*/
|
|
1976
|
+
releaseAll() {
|
|
1977
|
+
for (const [, item] of this.borrowed) {
|
|
1978
|
+
item.inUse = false;
|
|
1979
|
+
item.lastUsed = Date.now();
|
|
1980
|
+
}
|
|
1981
|
+
this.borrowed.clear();
|
|
1982
|
+
}
|
|
1983
|
+
/**
|
|
1984
|
+
* 预热池(预创建指定尺寸的 Canvas)
|
|
1985
|
+
*
|
|
1986
|
+
* @param sizes 尺寸数组,每项为 [width, height]
|
|
1987
|
+
*/
|
|
1988
|
+
warmup(sizes) {
|
|
1989
|
+
for (const [width, height] of sizes) {
|
|
1990
|
+
this.acquire(width, height);
|
|
1991
|
+
// 立即释放,让它们进入池中
|
|
1992
|
+
const sizeKey = this.getSizeKey(width, height);
|
|
1993
|
+
const items = this.pool.get(sizeKey);
|
|
1994
|
+
if (items && items.length > 0) {
|
|
1995
|
+
const item = items[items.length - 1];
|
|
1996
|
+
item.inUse = false;
|
|
1997
|
+
this.borrowed.delete(item.canvas);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* 获取池统计信息
|
|
2003
|
+
*/
|
|
2004
|
+
getStats() {
|
|
2005
|
+
let totalItems = 0;
|
|
2006
|
+
let borrowedCount = 0;
|
|
2007
|
+
const poolSizes = {};
|
|
2008
|
+
for (const [key, items] of this.pool.entries()) {
|
|
2009
|
+
totalItems += items.length;
|
|
2010
|
+
borrowedCount += items.filter(i => i.inUse).length;
|
|
2011
|
+
poolSizes[key] = {
|
|
2012
|
+
total: items.length,
|
|
2013
|
+
available: items.filter(i => !i.inUse).length
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
return { totalItems, borrowedCount, poolSizes };
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* 清理并释放所有资源
|
|
2020
|
+
*/
|
|
2021
|
+
dispose() {
|
|
2022
|
+
this.pool.clear();
|
|
2023
|
+
this.borrowed.clear();
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
/** 单例实例 */
|
|
2027
|
+
CanvasPool.instance = null;
|
|
2028
|
+
|
|
2029
|
+
/**
|
|
2030
|
+
* @file 边缘检测器
|
|
2031
|
+
* @description 提供边缘检测算法(Sobel、Canny等)
|
|
2032
|
+
* @module utils/edge-detector
|
|
2033
|
+
*/
|
|
2034
|
+
/**
|
|
2035
|
+
* 边缘检测器类
|
|
2036
|
+
* 提供各种边缘检测算法用于图像处理
|
|
2037
|
+
*/
|
|
2038
|
+
class EdgeDetector {
|
|
2039
|
+
/**
|
|
2040
|
+
* 使用Sobel算子进行边缘检测
|
|
2041
|
+
* @param imageData 灰度图像数据
|
|
2042
|
+
* @param threshold 边缘阈值,默认为30
|
|
2043
|
+
* @returns 检测到边缘的图像数据
|
|
2044
|
+
*/
|
|
2045
|
+
static detectEdges(imageData, threshold = 30) {
|
|
2046
|
+
const grayscaleImage = this.toGrayscale(new ImageData(new Uint8ClampedArray(imageData.data), imageData.width, imageData.height));
|
|
2047
|
+
const width = grayscaleImage.width;
|
|
2048
|
+
const height = grayscaleImage.height;
|
|
2049
|
+
const inputData = grayscaleImage.data;
|
|
2050
|
+
const outputData = new Uint8ClampedArray(inputData.length);
|
|
2051
|
+
const sobelX = [-1, 0, 1, -2, 0, 2, -1, 0, 1];
|
|
2052
|
+
const sobelY = [-1, -2, -1, 0, 0, 0, 1, 2, 1];
|
|
2053
|
+
for (let y = 1; y < height - 1; y++) {
|
|
2054
|
+
for (let x = 1; x < width - 1; x++) {
|
|
2055
|
+
let gx = 0, gy = 0;
|
|
2056
|
+
for (let ky = -1; ky <= 1; ky++) {
|
|
2057
|
+
for (let kx = -1; kx <= 1; kx++) {
|
|
2058
|
+
const pixelPos = ((y + ky) * width + (x + kx)) * 4;
|
|
2059
|
+
const pixelVal = inputData[pixelPos];
|
|
2060
|
+
const kernelIdx = (ky + 1) * 3 + (kx + 1);
|
|
2061
|
+
gx += pixelVal * sobelX[kernelIdx];
|
|
2062
|
+
gy += pixelVal * sobelY[kernelIdx];
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
let magnitude = Math.sqrt(gx * gx + gy * gy);
|
|
2066
|
+
magnitude = magnitude > threshold ? 255 : 0;
|
|
2067
|
+
const pos = (y * width + x) * 4;
|
|
2068
|
+
outputData[pos] = outputData[pos + 1] = outputData[pos + 2] = magnitude;
|
|
2069
|
+
outputData[pos + 3] = 255;
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
// 处理边缘
|
|
2073
|
+
for (let i = 0; i < width * 4; i++) {
|
|
2074
|
+
outputData[i] = 0;
|
|
2075
|
+
outputData[(height - 1) * width * 4 + i] = 0;
|
|
2076
|
+
}
|
|
2077
|
+
for (let i = 0; i < height; i++) {
|
|
2078
|
+
const leftPos = i * width * 4;
|
|
2079
|
+
const rightPos = (i * width + width - 1) * 4;
|
|
2080
|
+
for (let j = 0; j < 4; j++) {
|
|
2081
|
+
outputData[leftPos + j] = 0;
|
|
2082
|
+
outputData[rightPos + j] = 0;
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
return new ImageData(outputData, width, height);
|
|
2086
|
+
}
|
|
2087
|
+
/**
|
|
2088
|
+
* 卡尼-德里奇边缘检测
|
|
2089
|
+
*/
|
|
2090
|
+
static cannyEdgeDetection(imageData, lowThreshold = 20, highThreshold = 50) {
|
|
2091
|
+
const grayscaleImage = this.toGrayscale(new ImageData(new Uint8ClampedArray(imageData.data), imageData.width, imageData.height));
|
|
2092
|
+
const blurredImage = this.gaussianBlur(grayscaleImage, 1.5);
|
|
2093
|
+
const { gradientMagnitude, gradientDirection } = this.computeGradients(blurredImage);
|
|
2094
|
+
const nonMaxSuppressed = this.nonMaxSuppression(gradientMagnitude, gradientDirection, blurredImage.width, blurredImage.height);
|
|
2095
|
+
const thresholdResult = this.hysteresisThresholding(nonMaxSuppressed, blurredImage.width, blurredImage.height, lowThreshold, highThreshold);
|
|
2096
|
+
const outputData = new Uint8ClampedArray(imageData.data.length);
|
|
2097
|
+
for (let i = 0; i < thresholdResult.length; i++) {
|
|
2098
|
+
const pos = i * 4;
|
|
2099
|
+
const value = thresholdResult[i] ? 255 : 0;
|
|
2100
|
+
outputData[pos] = outputData[pos + 1] = outputData[pos + 2] = value;
|
|
2101
|
+
outputData[pos + 3] = 255;
|
|
2102
|
+
}
|
|
2103
|
+
return new ImageData(outputData, blurredImage.width, blurredImage.height);
|
|
2104
|
+
}
|
|
2105
|
+
static toGrayscale(imageData) {
|
|
2106
|
+
const srcData = imageData.data;
|
|
2107
|
+
const destData = new Uint8ClampedArray(srcData);
|
|
2108
|
+
for (let i = 0; i < srcData.length; i += 4) {
|
|
2109
|
+
const gray = srcData[i] * 0.3 + srcData[i + 1] * 0.59 + srcData[i + 2] * 0.11;
|
|
2110
|
+
destData[i] = destData[i + 1] = destData[i + 2] = gray;
|
|
2111
|
+
destData[i + 3] = srcData[i + 3];
|
|
2112
|
+
}
|
|
2113
|
+
return new ImageData(destData, imageData.width, imageData.height);
|
|
2114
|
+
}
|
|
2115
|
+
static gaussianBlur(imageData, sigma = 1.5) {
|
|
2116
|
+
const width = imageData.width, height = imageData.height;
|
|
2117
|
+
const inputData = imageData.data, outputData = new Uint8ClampedArray(inputData.length);
|
|
2118
|
+
const kernelSize = Math.max(3, Math.floor(sigma * 3) * 2 + 1);
|
|
2119
|
+
const halfKernel = Math.floor(kernelSize / 2);
|
|
2120
|
+
const kernel = this.generateGaussianKernel(kernelSize, sigma);
|
|
2121
|
+
for (let y = 0; y < height; y++) {
|
|
2122
|
+
for (let x = 0; x < width; x++) {
|
|
2123
|
+
let sum = 0, weightSum = 0;
|
|
2124
|
+
for (let ky = -halfKernel; ky <= halfKernel; ky++) {
|
|
2125
|
+
for (let kx = -halfKernel; kx <= halfKernel; kx++) {
|
|
2126
|
+
const pixelY = Math.min(Math.max(y + ky, 0), height - 1);
|
|
2127
|
+
const pixelX = Math.min(Math.max(x + kx, 0), width - 1);
|
|
2128
|
+
const pixelPos = (pixelY * width + pixelX) * 4;
|
|
2129
|
+
const kernelY = ky + halfKernel, kernelX = kx + halfKernel;
|
|
2130
|
+
const weight = kernel[kernelY * kernelSize + kernelX];
|
|
2131
|
+
sum += inputData[pixelPos] * weight;
|
|
2132
|
+
weightSum += weight;
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
const pos = (y * width + x) * 4;
|
|
2136
|
+
const value = Math.round(sum / weightSum);
|
|
2137
|
+
outputData[pos] = outputData[pos + 1] = outputData[pos + 2] = value;
|
|
2138
|
+
outputData[pos + 3] = 255;
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
return new ImageData(outputData, width, height);
|
|
2142
|
+
}
|
|
2143
|
+
static generateGaussianKernel(size, sigma) {
|
|
2144
|
+
const kernel = new Array(size * size);
|
|
2145
|
+
const center = Math.floor(size / 2);
|
|
2146
|
+
let sum = 0;
|
|
2147
|
+
for (let y = 0; y < size; y++) {
|
|
2148
|
+
for (let x = 0; x < size; x++) {
|
|
2149
|
+
const distance = Math.sqrt((x - center) ** 2 + (y - center) ** 2);
|
|
2150
|
+
kernel[y * size + x] = Math.exp(-(distance ** 2) / (2 * sigma ** 2));
|
|
2151
|
+
sum += kernel[y * size + x];
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
for (let i = 0; i < kernel.length; i++)
|
|
2155
|
+
kernel[i] /= sum;
|
|
2156
|
+
return kernel;
|
|
2157
|
+
}
|
|
2158
|
+
static computeGradients(imageData) {
|
|
2159
|
+
const width = imageData.width, height = imageData.height;
|
|
2160
|
+
const inputData = imageData.data;
|
|
2161
|
+
const gradientMagnitude = new Array(width * height);
|
|
2162
|
+
const gradientDirection = new Array(width * height);
|
|
2163
|
+
const sobelX = [-1, 0, 1, -2, 0, 2, -1, 0, 1];
|
|
2164
|
+
const sobelY = [-1, -2, -1, 0, 0, 0, 1, 2, 1];
|
|
2165
|
+
for (let y = 1; y < height - 1; y++) {
|
|
2166
|
+
for (let x = 1; x < width - 1; x++) {
|
|
2167
|
+
let gx = 0, gy = 0;
|
|
2168
|
+
for (let ky = -1; ky <= 1; ky++) {
|
|
2169
|
+
for (let kx = -1; kx <= 1; kx++) {
|
|
2170
|
+
const pixelPos = ((y + ky) * width + (x + kx)) * 4;
|
|
2171
|
+
const pixelVal = inputData[pixelPos];
|
|
2172
|
+
const kernelIdx = (ky + 1) * 3 + (kx + 1);
|
|
2173
|
+
gx += pixelVal * sobelX[kernelIdx];
|
|
2174
|
+
gy += pixelVal * sobelY[kernelIdx];
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
const idx = y * width + x;
|
|
2178
|
+
gradientMagnitude[idx] = Math.sqrt(gx * gx + gy * gy);
|
|
2179
|
+
gradientDirection[idx] = Math.atan2(gy, gx);
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
return { gradientMagnitude, gradientDirection };
|
|
2183
|
+
}
|
|
2184
|
+
static nonMaxSuppression(gradientMagnitude, gradientDirection, width, height) {
|
|
2185
|
+
const result = new Array(width * height).fill(0);
|
|
2186
|
+
for (let y = 1; y < height - 1; y++) {
|
|
2187
|
+
for (let x = 1; x < width - 1; x++) {
|
|
2188
|
+
const idx = y * width + x;
|
|
2189
|
+
const magnitude = gradientMagnitude[idx];
|
|
2190
|
+
const direction = gradientDirection[idx];
|
|
2191
|
+
const degrees = (direction * 180 / Math.PI + 180) % 180;
|
|
2192
|
+
let neighbor1Idx, neighbor2Idx;
|
|
2193
|
+
if ((degrees >= 0 && degrees < 22.5) || (degrees >= 157.5 && degrees <= 180)) {
|
|
2194
|
+
neighbor1Idx = idx - 1;
|
|
2195
|
+
neighbor2Idx = idx + 1;
|
|
2196
|
+
}
|
|
2197
|
+
else if (degrees >= 22.5 && degrees < 67.5) {
|
|
2198
|
+
neighbor1Idx = (y - 1) * width + (x + 1);
|
|
2199
|
+
neighbor2Idx = (y + 1) * width + (x - 1);
|
|
2200
|
+
}
|
|
2201
|
+
else if (degrees >= 67.5 && degrees < 112.5) {
|
|
2202
|
+
neighbor1Idx = (y - 1) * width + x;
|
|
2203
|
+
neighbor2Idx = (y + 1) * width + x;
|
|
2204
|
+
}
|
|
2205
|
+
else {
|
|
2206
|
+
neighbor1Idx = (y - 1) * width + (x - 1);
|
|
2207
|
+
neighbor2Idx = (y + 1) * width + (x + 1);
|
|
2208
|
+
}
|
|
2209
|
+
if (magnitude >= gradientMagnitude[neighbor1Idx] && magnitude >= gradientMagnitude[neighbor2Idx]) {
|
|
2210
|
+
result[idx] = magnitude;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
return result;
|
|
2215
|
+
}
|
|
2216
|
+
static hysteresisThresholding(nonMaxSuppressed, width, height, lowThreshold, highThreshold) {
|
|
2217
|
+
const result = new Array(width * height).fill(false);
|
|
2218
|
+
const visited = new Array(width * height).fill(false);
|
|
2219
|
+
const stack = [];
|
|
2220
|
+
for (let i = 0; i < nonMaxSuppressed.length; i++) {
|
|
2221
|
+
if (nonMaxSuppressed[i] >= highThreshold) {
|
|
2222
|
+
result[i] = true;
|
|
2223
|
+
stack.push(i);
|
|
2224
|
+
visited[i] = true;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
const dx = [-1, 0, 1, -1, 1, -1, 0, 1];
|
|
2228
|
+
const dy = [-1, -1, -1, 0, 0, 1, 1, 1];
|
|
2229
|
+
while (stack.length > 0) {
|
|
2230
|
+
const currentIdx = stack.pop();
|
|
2231
|
+
const currentX = currentIdx % width;
|
|
2232
|
+
const currentY = Math.floor(currentIdx / width);
|
|
2233
|
+
for (let i = 0; i < 8; i++) {
|
|
2234
|
+
const newX = currentX + dx[i];
|
|
2235
|
+
const newY = currentY + dy[i];
|
|
2236
|
+
if (newX >= 0 && newX < width && newY >= 0 && newY < height) {
|
|
2237
|
+
const newIdx = newY * width + newX;
|
|
2238
|
+
if (!visited[newIdx] && nonMaxSuppressed[newIdx] >= lowThreshold) {
|
|
2239
|
+
result[newIdx] = true;
|
|
2240
|
+
stack.push(newIdx);
|
|
2241
|
+
visited[newIdx] = true;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
return result;
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
/**
|
|
2251
|
+
* @file 图像处理工具类
|
|
2252
|
+
* @description 提供图像预处理功能,用于提高OCR识别率
|
|
2253
|
+
* @module ImageProcessor
|
|
2254
|
+
* @version 1.4.0
|
|
2255
|
+
*/
|
|
2256
|
+
/**
|
|
2257
|
+
* 图像处理工具类
|
|
2258
|
+
*
|
|
2259
|
+
* 提供各种图像处理功能,用于优化识别效果
|
|
2260
|
+
*/
|
|
2261
|
+
class ImageProcessor {
|
|
2262
|
+
/**
|
|
2263
|
+
* 将ImageData转换为Canvas元素
|
|
2264
|
+
*
|
|
2265
|
+
* @param {ImageData} imageData - 要转换的图像数据
|
|
2266
|
+
* @returns {HTMLCanvasElement} 包含图像的Canvas元素
|
|
2267
|
+
*/
|
|
2268
|
+
static imageDataToCanvas(imageData, usePool = true) {
|
|
2269
|
+
let canvas;
|
|
2270
|
+
let context;
|
|
2271
|
+
if (usePool) {
|
|
2272
|
+
({ canvas, context } = CanvasPool.getInstance().acquire(imageData.width, imageData.height));
|
|
2273
|
+
}
|
|
2274
|
+
else {
|
|
2275
|
+
canvas = document.createElement("canvas");
|
|
2276
|
+
canvas.width = imageData.width;
|
|
2277
|
+
canvas.height = imageData.height;
|
|
2278
|
+
context = canvas.getContext("2d");
|
|
2279
|
+
}
|
|
2280
|
+
context.putImageData(imageData, 0, 0);
|
|
2281
|
+
if (usePool) {
|
|
2282
|
+
// 立即释放回池中,用户保留 canvas 引用即可
|
|
2283
|
+
CanvasPool.getInstance().release(canvas);
|
|
2284
|
+
}
|
|
2285
|
+
return canvas;
|
|
2286
|
+
}
|
|
2287
|
+
/**
|
|
2288
|
+
* 将Canvas转换为ImageData
|
|
2289
|
+
*
|
|
2290
|
+
* @param {HTMLCanvasElement} canvas - 要转换的Canvas元素
|
|
2291
|
+
* @returns {ImageData|null} Canvas的图像数据,如果获取失败则返回null
|
|
2292
|
+
*/
|
|
2293
|
+
static canvasToImageData(canvas) {
|
|
2294
|
+
const ctx = canvas.getContext("2d");
|
|
2295
|
+
return ctx ? ctx.getImageData(0, 0, canvas.width, canvas.height) : null;
|
|
2296
|
+
}
|
|
2297
|
+
/**
|
|
2298
|
+
* 调整图像亮度和对比度
|
|
2299
|
+
*
|
|
2300
|
+
* @param imageData 原始图像数据
|
|
2301
|
+
* @param brightness 亮度调整值 (-100到100)
|
|
2302
|
+
* @param contrast 对比度调整值 (-100到100)
|
|
2303
|
+
* @returns 处理后的图像数据
|
|
2304
|
+
*/
|
|
2305
|
+
static adjustBrightnessContrast(imageData, brightness = 0, contrast = 0) {
|
|
2306
|
+
// 将亮度和对比度范围限制在 -100 到 100 之间
|
|
2307
|
+
brightness = Math.max(-100, Math.min(100, brightness));
|
|
2308
|
+
contrast = Math.max(-100, Math.min(100, contrast));
|
|
2309
|
+
// 将范围转换为适合计算的值
|
|
2310
|
+
const factor = (259 * (contrast + 255)) / (255 * (259 - contrast));
|
|
2311
|
+
const briAdjust = (brightness / 100) * 255;
|
|
2312
|
+
const data = imageData.data;
|
|
2313
|
+
const length = data.length;
|
|
2314
|
+
for (let i = 0; i < length; i += 4) {
|
|
2315
|
+
// 分别处理 RGB 三个通道
|
|
2316
|
+
for (let j = 0; j < 3; j++) {
|
|
2317
|
+
// 应用亮度和对比度调整公式
|
|
2318
|
+
const newValue = factor * (data[i + j] + briAdjust - 128) + 128;
|
|
2319
|
+
data[i + j] = Math.max(0, Math.min(255, newValue));
|
|
2320
|
+
}
|
|
2321
|
+
// Alpha 通道保持不变
|
|
2322
|
+
}
|
|
2323
|
+
return imageData;
|
|
2324
|
+
}
|
|
2325
|
+
/**
|
|
2326
|
+
* 将图像转换为灰度图(返回新 ImageData,不修改原图)
|
|
2327
|
+
*
|
|
2328
|
+
* @param imageData 原始图像数据
|
|
2329
|
+
* @returns 灰度图像数据(新对象)
|
|
2330
|
+
*/
|
|
2331
|
+
static toGrayscale(imageData) {
|
|
2332
|
+
const srcData = imageData.data;
|
|
2333
|
+
const length = srcData.length;
|
|
2334
|
+
// 创建新数组,避免修改原图
|
|
2335
|
+
const destData = new Uint8ClampedArray(srcData);
|
|
2336
|
+
for (let i = 0; i < length; i += 4) {
|
|
2337
|
+
// 使用加权平均法将 RGB 转换为灰度值
|
|
2338
|
+
const gray = srcData[i] * 0.3 + srcData[i + 1] * 0.59 + srcData[i + 2] * 0.11;
|
|
2339
|
+
destData[i] = destData[i + 1] = destData[i + 2] = gray;
|
|
2340
|
+
// Alpha 通道保持不变
|
|
2341
|
+
destData[i + 3] = srcData[i + 3];
|
|
2342
|
+
}
|
|
2343
|
+
return new ImageData(destData, imageData.width, imageData.height);
|
|
2344
|
+
}
|
|
2345
|
+
/**
|
|
2346
|
+
* 锐化图像
|
|
2347
|
+
*
|
|
2348
|
+
* @param imageData 原始图像数据
|
|
2349
|
+
* @param amount 锐化程度,默认为2
|
|
2350
|
+
* @returns 锐化后的图像数据
|
|
1688
2351
|
*/
|
|
1689
2352
|
static sharpen(imageData, amount = 2) {
|
|
1690
2353
|
if (!imageData || !imageData.data)
|
|
@@ -1724,52 +2387,79 @@
|
|
|
1724
2387
|
outputData[pos + 3] = data[pos + 3]; // 保持透明度不变
|
|
1725
2388
|
}
|
|
1726
2389
|
}
|
|
1727
|
-
//
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
2390
|
+
// 处理边缘像素(仅遍历四条边,而非全图 O(width×height) → O(width+height))
|
|
2391
|
+
// 上边 + 下边
|
|
2392
|
+
for (let x = 0; x < width; x++) {
|
|
2393
|
+
const topPos = x * 4;
|
|
2394
|
+
const bottomPos = ((height - 1) * width + x) * 4;
|
|
2395
|
+
outputData[topPos] = data[topPos];
|
|
2396
|
+
outputData[topPos + 1] = data[topPos + 1];
|
|
2397
|
+
outputData[topPos + 2] = data[topPos + 2];
|
|
2398
|
+
outputData[topPos + 3] = data[topPos + 3];
|
|
2399
|
+
outputData[bottomPos] = data[bottomPos];
|
|
2400
|
+
outputData[bottomPos + 1] = data[bottomPos + 1];
|
|
2401
|
+
outputData[bottomPos + 2] = data[bottomPos + 2];
|
|
2402
|
+
outputData[bottomPos + 3] = data[bottomPos + 3];
|
|
2403
|
+
}
|
|
2404
|
+
// 左边 + 右边(排除四角,它们已在上下一行处理)
|
|
2405
|
+
for (let y = 1; y < height - 1; y++) {
|
|
2406
|
+
const leftPos = y * width * 4;
|
|
2407
|
+
const rightPos = (y * width + width - 1) * 4;
|
|
2408
|
+
outputData[leftPos] = data[leftPos];
|
|
2409
|
+
outputData[leftPos + 1] = data[leftPos + 1];
|
|
2410
|
+
outputData[leftPos + 2] = data[leftPos + 2];
|
|
2411
|
+
outputData[leftPos + 3] = data[leftPos + 3];
|
|
2412
|
+
outputData[rightPos] = data[rightPos];
|
|
2413
|
+
outputData[rightPos + 1] = data[rightPos + 1];
|
|
2414
|
+
outputData[rightPos + 2] = data[rightPos + 2];
|
|
2415
|
+
outputData[rightPos + 3] = data[rightPos + 3];
|
|
1738
2416
|
}
|
|
1739
2417
|
// 创建新的ImageData对象
|
|
1740
2418
|
return new ImageData(outputData, width, height);
|
|
1741
2419
|
}
|
|
1742
2420
|
/**
|
|
1743
|
-
*
|
|
2421
|
+
* 对图像应用阈值操作,增强对比度(二值化)
|
|
1744
2422
|
*
|
|
1745
2423
|
* @param imageData 原始图像数据
|
|
1746
2424
|
* @param threshold 阈值 (0-255)
|
|
1747
|
-
* @returns
|
|
2425
|
+
* @returns 处理后的图像数据(新对象,不修改原图)
|
|
1748
2426
|
*/
|
|
1749
2427
|
static threshold(imageData, threshold = 128) {
|
|
1750
|
-
//
|
|
1751
|
-
const grayscaleImage = this.toGrayscale(
|
|
1752
|
-
const
|
|
1753
|
-
const length =
|
|
2428
|
+
// 先转换为灰度图(返回新 ImageData,不修改原图)
|
|
2429
|
+
const grayscaleImage = this.toGrayscale(imageData);
|
|
2430
|
+
const srcData = grayscaleImage.data;
|
|
2431
|
+
const length = srcData.length;
|
|
2432
|
+
// 创建新数组存储二值化结果
|
|
2433
|
+
const destData = new Uint8ClampedArray(length);
|
|
1754
2434
|
for (let i = 0; i < length; i += 4) {
|
|
1755
2435
|
// 二值化处理
|
|
1756
|
-
const value =
|
|
1757
|
-
|
|
2436
|
+
const value = srcData[i] < threshold ? 0 : 255;
|
|
2437
|
+
destData[i] = destData[i + 1] = destData[i + 2] = value;
|
|
2438
|
+
destData[i + 3] = srcData[i + 3]; // 保持透明度
|
|
1758
2439
|
}
|
|
1759
|
-
return grayscaleImage;
|
|
2440
|
+
return new ImageData(destData, grayscaleImage.width, grayscaleImage.height);
|
|
1760
2441
|
}
|
|
1761
2442
|
/**
|
|
1762
|
-
*
|
|
2443
|
+
* 将图像转换为黑白图像(二值化,使用OTSU自动阈值)
|
|
1763
2444
|
*
|
|
1764
2445
|
* @param imageData 原始图像数据
|
|
1765
|
-
* @returns
|
|
2446
|
+
* @returns 二值化后的图像数据(新对象,不修改原图)
|
|
1766
2447
|
*/
|
|
1767
2448
|
static toBinaryImage(imageData) {
|
|
1768
|
-
//
|
|
1769
|
-
const grayscaleImage = this.toGrayscale(
|
|
2449
|
+
// 先转换为灰度图(返回新 ImageData,不修改原图)
|
|
2450
|
+
const grayscaleImage = this.toGrayscale(imageData);
|
|
1770
2451
|
// 使用OTSU算法自动确定阈值
|
|
1771
2452
|
const threshold = this.getOtsuThreshold(grayscaleImage);
|
|
1772
|
-
|
|
2453
|
+
// 直接对灰度图进行二值化,避免再次调用 toGrayscale
|
|
2454
|
+
const srcData = grayscaleImage.data;
|
|
2455
|
+
const length = srcData.length;
|
|
2456
|
+
const destData = new Uint8ClampedArray(length);
|
|
2457
|
+
for (let i = 0; i < length; i += 4) {
|
|
2458
|
+
const value = srcData[i] < threshold ? 0 : 255;
|
|
2459
|
+
destData[i] = destData[i + 1] = destData[i + 2] = value;
|
|
2460
|
+
destData[i + 3] = srcData[i + 3]; // 保持透明度
|
|
2461
|
+
}
|
|
2462
|
+
return new ImageData(destData, grayscaleImage.width, grayscaleImage.height);
|
|
1773
2463
|
}
|
|
1774
2464
|
/**
|
|
1775
2465
|
* 使用OTSU算法计算最佳阈值
|
|
@@ -1779,8 +2469,9 @@
|
|
|
1779
2469
|
*/
|
|
1780
2470
|
static getOtsuThreshold(imageData) {
|
|
1781
2471
|
const data = imageData.data;
|
|
1782
|
-
|
|
1783
|
-
|
|
2472
|
+
// 使用 Uint8Array 替代 Array<number>,避免 boxing 开销,提升直方图统计性能
|
|
2473
|
+
const histogram = new Uint32Array(256);
|
|
2474
|
+
// 统计灰度直方图(每4字节取R通道,即灰度值)
|
|
1784
2475
|
for (let i = 0; i < data.length; i += 4) {
|
|
1785
2476
|
histogram[data[i]]++;
|
|
1786
2477
|
}
|
|
@@ -1886,24 +2577,20 @@
|
|
|
1886
2577
|
const url = URL.createObjectURL(file);
|
|
1887
2578
|
img.onload = () => {
|
|
1888
2579
|
try {
|
|
1889
|
-
//
|
|
1890
|
-
const canvas =
|
|
1891
|
-
const ctx = canvas.getContext("2d");
|
|
1892
|
-
if (!ctx) {
|
|
1893
|
-
reject(new Error("无法创建2D上下文"));
|
|
1894
|
-
return;
|
|
1895
|
-
}
|
|
1896
|
-
canvas.width = img.width;
|
|
1897
|
-
canvas.height = img.height;
|
|
2580
|
+
// 使用 Canvas 池获取 canvas
|
|
2581
|
+
const { canvas, context } = CanvasPool.getInstance().acquire(img.width, img.height);
|
|
1898
2582
|
// 绘制图片到canvas
|
|
1899
|
-
|
|
2583
|
+
context.drawImage(img, 0, 0);
|
|
1900
2584
|
// 获取图像数据
|
|
1901
|
-
const imageData =
|
|
2585
|
+
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
|
|
2586
|
+
// 释放回池
|
|
2587
|
+
CanvasPool.getInstance().release(canvas);
|
|
1902
2588
|
// 释放资源
|
|
1903
2589
|
URL.revokeObjectURL(url);
|
|
1904
2590
|
resolve(imageData);
|
|
1905
2591
|
}
|
|
1906
2592
|
catch (e) {
|
|
2593
|
+
URL.revokeObjectURL(url);
|
|
1907
2594
|
reject(e);
|
|
1908
2595
|
}
|
|
1909
2596
|
};
|
|
@@ -1930,16 +2617,12 @@
|
|
|
1930
2617
|
static async imageDataToFile(imageData, fileName = "image.jpg", fileType = "image/jpeg", quality = 0.8) {
|
|
1931
2618
|
return new Promise((resolve, reject) => {
|
|
1932
2619
|
try {
|
|
1933
|
-
|
|
1934
|
-
canvas
|
|
1935
|
-
|
|
1936
|
-
const ctx = canvas.getContext("2d");
|
|
1937
|
-
if (!ctx) {
|
|
1938
|
-
reject(new Error("无法创建2D上下文"));
|
|
1939
|
-
return;
|
|
1940
|
-
}
|
|
1941
|
-
ctx.putImageData(imageData, 0, 0);
|
|
2620
|
+
// 使用 Canvas 池
|
|
2621
|
+
const { canvas, context } = CanvasPool.getInstance().acquire(imageData.width, imageData.height);
|
|
2622
|
+
context.putImageData(imageData, 0, 0);
|
|
1942
2623
|
canvas.toBlob((blob) => {
|
|
2624
|
+
// 释放回池
|
|
2625
|
+
CanvasPool.getInstance().release(canvas);
|
|
1943
2626
|
if (!blob) {
|
|
1944
2627
|
reject(new Error("无法创建图片Blob"));
|
|
1945
2628
|
return;
|
|
@@ -1973,327 +2656,67 @@
|
|
|
1973
2656
|
let height;
|
|
1974
2657
|
if (image instanceof ImageData) {
|
|
1975
2658
|
width = image.width;
|
|
1976
|
-
height = image.height;
|
|
1977
|
-
}
|
|
1978
|
-
else {
|
|
1979
|
-
width = image.width;
|
|
1980
|
-
height = image.height;
|
|
1981
|
-
}
|
|
1982
|
-
// 计算调整后的尺寸
|
|
1983
|
-
let newWidth = width;
|
|
1984
|
-
let newHeight = height;
|
|
1985
|
-
if (keepAspectRatio) {
|
|
1986
|
-
if (width > height) {
|
|
1987
|
-
if (width > maxWidth) {
|
|
1988
|
-
newHeight = Math.round(height * (maxWidth / width));
|
|
1989
|
-
newWidth = maxWidth;
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
else {
|
|
1993
|
-
if (height > maxHeight) {
|
|
1994
|
-
newWidth = Math.round(width * (maxHeight / height));
|
|
1995
|
-
newHeight = maxHeight;
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
else {
|
|
2000
|
-
newWidth = Math.min(width, maxWidth);
|
|
2001
|
-
newHeight = Math.min(height, maxHeight);
|
|
2002
|
-
}
|
|
2003
|
-
// 设置canvas尺寸
|
|
2004
|
-
canvas.width = newWidth;
|
|
2005
|
-
canvas.height = newHeight;
|
|
2006
|
-
// 绘制调整后的图像
|
|
2007
|
-
if (image instanceof ImageData) {
|
|
2008
|
-
// 创建临时canvas存储ImageData
|
|
2009
|
-
const tempCanvas = document.createElement('canvas');
|
|
2010
|
-
const tempCtx = tempCanvas.getContext('2d');
|
|
2011
|
-
if (!tempCtx) {
|
|
2012
|
-
throw new Error('无法创建临时Canvas上下文');
|
|
2013
|
-
}
|
|
2014
|
-
tempCanvas.width = image.width;
|
|
2015
|
-
tempCanvas.height = image.height;
|
|
2016
|
-
tempCtx.putImageData(image, 0, 0);
|
|
2017
|
-
// 绘制调整后的图像
|
|
2018
|
-
ctx.drawImage(tempCanvas, 0, 0, width, height, 0, 0, newWidth, newHeight);
|
|
2019
|
-
}
|
|
2020
|
-
else {
|
|
2021
|
-
ctx.drawImage(image, 0, 0, width, height, 0, 0, newWidth, newHeight);
|
|
2022
|
-
}
|
|
2023
|
-
// 返回调整后的ImageData
|
|
2024
|
-
return ctx.getImageData(0, 0, newWidth, newHeight);
|
|
2025
|
-
}
|
|
2026
|
-
/**
|
|
2027
|
-
* 边缘检测算法,用于识别图像中的边缘
|
|
2028
|
-
* 基于Sobel算子实现
|
|
2029
|
-
*
|
|
2030
|
-
* @param imageData 原始图像数据,应已转为灰度图
|
|
2031
|
-
* @param threshold 边缘阈值,默认为30
|
|
2032
|
-
* @returns 检测到边缘的图像数据
|
|
2033
|
-
*/
|
|
2034
|
-
static detectEdges(imageData, threshold = 30) {
|
|
2035
|
-
// 确保输入图像是灰度图
|
|
2036
|
-
const grayscaleImage = this.toGrayscale(new ImageData(new Uint8ClampedArray(imageData.data), imageData.width, imageData.height));
|
|
2037
|
-
const width = grayscaleImage.width;
|
|
2038
|
-
const height = grayscaleImage.height;
|
|
2039
|
-
const inputData = grayscaleImage.data;
|
|
2040
|
-
const outputData = new Uint8ClampedArray(inputData.length);
|
|
2041
|
-
// Sobel算子 - 水平和垂直方向
|
|
2042
|
-
const sobelX = [-1, 0, 1, -2, 0, 2, -1, 0, 1];
|
|
2043
|
-
const sobelY = [-1, -2, -1, 0, 0, 0, 1, 2, 1];
|
|
2044
|
-
// 对每个像素应用Sobel算子
|
|
2045
|
-
for (let y = 1; y < height - 1; y++) {
|
|
2046
|
-
for (let x = 1; x < width - 1; x++) {
|
|
2047
|
-
let gx = 0;
|
|
2048
|
-
let gy = 0;
|
|
2049
|
-
// 应用卷积
|
|
2050
|
-
for (let ky = -1; ky <= 1; ky++) {
|
|
2051
|
-
for (let kx = -1; kx <= 1; kx++) {
|
|
2052
|
-
const pixelPos = ((y + ky) * width + (x + kx)) * 4;
|
|
2053
|
-
const pixelVal = inputData[pixelPos]; // 灰度值
|
|
2054
|
-
const kernelIdx = (ky + 1) * 3 + (kx + 1);
|
|
2055
|
-
gx += pixelVal * sobelX[kernelIdx];
|
|
2056
|
-
gy += pixelVal * sobelY[kernelIdx];
|
|
2057
|
-
}
|
|
2058
|
-
}
|
|
2059
|
-
// 计算梯度强度
|
|
2060
|
-
let magnitude = Math.sqrt(gx * gx + gy * gy);
|
|
2061
|
-
// 应用阈值
|
|
2062
|
-
magnitude = magnitude > threshold ? 255 : 0;
|
|
2063
|
-
// 设置输出像素
|
|
2064
|
-
const pos = (y * width + x) * 4;
|
|
2065
|
-
outputData[pos] = outputData[pos + 1] = outputData[pos + 2] = magnitude;
|
|
2066
|
-
outputData[pos + 3] = 255; // 透明度保持完全不透明
|
|
2067
|
-
}
|
|
2068
|
-
}
|
|
2069
|
-
// 处理边缘像素
|
|
2070
|
-
for (let i = 0; i < width * 4; i++) {
|
|
2071
|
-
// 顶部和底部行
|
|
2072
|
-
outputData[i] = 0;
|
|
2073
|
-
outputData[(height - 1) * width * 4 + i] = 0;
|
|
2074
|
-
}
|
|
2075
|
-
for (let i = 0; i < height; i++) {
|
|
2076
|
-
// 左右两侧列
|
|
2077
|
-
const leftPos = i * width * 4;
|
|
2078
|
-
const rightPos = (i * width + width - 1) * 4;
|
|
2079
|
-
for (let j = 0; j < 4; j++) {
|
|
2080
|
-
outputData[leftPos + j] = 0;
|
|
2081
|
-
outputData[rightPos + j] = 0;
|
|
2082
|
-
}
|
|
2083
|
-
}
|
|
2084
|
-
return new ImageData(outputData, width, height);
|
|
2085
|
-
}
|
|
2086
|
-
/**
|
|
2087
|
-
* 卡尼-德里奇边缘检测
|
|
2088
|
-
* 相比Sobel更精确的边缘检测算法
|
|
2089
|
-
*
|
|
2090
|
-
* @param imageData 灰度图像数据
|
|
2091
|
-
* @param lowThreshold 低阈值
|
|
2092
|
-
* @param highThreshold 高阈值
|
|
2093
|
-
* @returns 边缘检测结果
|
|
2094
|
-
*/
|
|
2095
|
-
static cannyEdgeDetection(imageData, lowThreshold = 20, highThreshold = 50) {
|
|
2096
|
-
const grayscaleImage = this.toGrayscale(new ImageData(new Uint8ClampedArray(imageData.data), imageData.width, imageData.height));
|
|
2097
|
-
// 1. 高斯模糊
|
|
2098
|
-
const blurredImage = this.gaussianBlur(grayscaleImage, 1.5);
|
|
2099
|
-
// 2. 使用Sobel算子计算梯度
|
|
2100
|
-
const { gradientMagnitude, gradientDirection } = this.computeGradients(blurredImage);
|
|
2101
|
-
// 3. 非极大值抛弃
|
|
2102
|
-
const nonMaxSuppressed = this.nonMaxSuppression(gradientMagnitude, gradientDirection, blurredImage.width, blurredImage.height);
|
|
2103
|
-
// 4. 双阈值处理
|
|
2104
|
-
const thresholdResult = this.hysteresisThresholding(nonMaxSuppressed, blurredImage.width, blurredImage.height, lowThreshold, highThreshold);
|
|
2105
|
-
// 创建输出图像
|
|
2106
|
-
const outputData = new Uint8ClampedArray(imageData.data.length);
|
|
2107
|
-
// 将结果转换为ImageData
|
|
2108
|
-
for (let i = 0; i < thresholdResult.length; i++) {
|
|
2109
|
-
const pos = i * 4;
|
|
2110
|
-
const value = thresholdResult[i] ? 255 : 0;
|
|
2111
|
-
outputData[pos] = outputData[pos + 1] = outputData[pos + 2] = value;
|
|
2112
|
-
outputData[pos + 3] = 255;
|
|
2113
|
-
}
|
|
2114
|
-
return new ImageData(outputData, blurredImage.width, blurredImage.height);
|
|
2115
|
-
}
|
|
2116
|
-
/**
|
|
2117
|
-
* 高斯模糊
|
|
2118
|
-
*/
|
|
2119
|
-
static gaussianBlur(imageData, sigma = 1.5) {
|
|
2120
|
-
const width = imageData.width;
|
|
2121
|
-
const height = imageData.height;
|
|
2122
|
-
const inputData = imageData.data;
|
|
2123
|
-
const outputData = new Uint8ClampedArray(inputData.length);
|
|
2124
|
-
// 生成高斯核
|
|
2125
|
-
const kernelSize = Math.max(3, Math.floor(sigma * 3) * 2 + 1);
|
|
2126
|
-
const halfKernel = Math.floor(kernelSize / 2);
|
|
2127
|
-
const kernel = this.generateGaussianKernel(kernelSize, sigma);
|
|
2128
|
-
// 应用高斯核
|
|
2129
|
-
for (let y = 0; y < height; y++) {
|
|
2130
|
-
for (let x = 0; x < width; x++) {
|
|
2131
|
-
let sum = 0;
|
|
2132
|
-
let weightSum = 0;
|
|
2133
|
-
for (let ky = -halfKernel; ky <= halfKernel; ky++) {
|
|
2134
|
-
for (let kx = -halfKernel; kx <= halfKernel; kx++) {
|
|
2135
|
-
const pixelY = Math.min(Math.max(y + ky, 0), height - 1);
|
|
2136
|
-
const pixelX = Math.min(Math.max(x + kx, 0), width - 1);
|
|
2137
|
-
const pixelPos = (pixelY * width + pixelX) * 4;
|
|
2138
|
-
const kernelY = ky + halfKernel;
|
|
2139
|
-
const kernelX = kx + halfKernel;
|
|
2140
|
-
const weight = kernel[kernelY * kernelSize + kernelX];
|
|
2141
|
-
sum += inputData[pixelPos] * weight;
|
|
2142
|
-
weightSum += weight;
|
|
2143
|
-
}
|
|
2144
|
-
}
|
|
2145
|
-
const pos = (y * width + x) * 4;
|
|
2146
|
-
const value = Math.round(sum / weightSum);
|
|
2147
|
-
outputData[pos] = outputData[pos + 1] = outputData[pos + 2] = value;
|
|
2148
|
-
outputData[pos + 3] = 255;
|
|
2149
|
-
}
|
|
2150
|
-
}
|
|
2151
|
-
return new ImageData(outputData, width, height);
|
|
2152
|
-
}
|
|
2153
|
-
/**
|
|
2154
|
-
* 生成高斯核
|
|
2155
|
-
*/
|
|
2156
|
-
static generateGaussianKernel(size, sigma) {
|
|
2157
|
-
const kernel = new Array(size * size);
|
|
2158
|
-
const center = Math.floor(size / 2);
|
|
2159
|
-
let sum = 0;
|
|
2160
|
-
for (let y = 0; y < size; y++) {
|
|
2161
|
-
for (let x = 0; x < size; x++) {
|
|
2162
|
-
const distance = Math.sqrt((x - center) ** 2 + (y - center) ** 2);
|
|
2163
|
-
const value = Math.exp(-(distance ** 2) / (2 * sigma ** 2));
|
|
2164
|
-
kernel[y * size + x] = value;
|
|
2165
|
-
sum += value;
|
|
2166
|
-
}
|
|
2659
|
+
height = image.height;
|
|
2167
2660
|
}
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2661
|
+
else {
|
|
2662
|
+
width = image.width;
|
|
2663
|
+
height = image.height;
|
|
2171
2664
|
}
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
const inputData = imageData.data;
|
|
2181
|
-
const gradientMagnitude = new Array(width * height);
|
|
2182
|
-
const gradientDirection = new Array(width * height);
|
|
2183
|
-
// Sobel算子
|
|
2184
|
-
const sobelX = [-1, 0, 1, -2, 0, 2, -1, 0, 1];
|
|
2185
|
-
const sobelY = [-1, -2, -1, 0, 0, 0, 1, 2, 1];
|
|
2186
|
-
for (let y = 1; y < height - 1; y++) {
|
|
2187
|
-
for (let x = 1; x < width - 1; x++) {
|
|
2188
|
-
let gx = 0;
|
|
2189
|
-
let gy = 0;
|
|
2190
|
-
for (let ky = -1; ky <= 1; ky++) {
|
|
2191
|
-
for (let kx = -1; kx <= 1; kx++) {
|
|
2192
|
-
const pixelPos = ((y + ky) * width + (x + kx)) * 4;
|
|
2193
|
-
const pixelVal = inputData[pixelPos];
|
|
2194
|
-
const kernelIdx = (ky + 1) * 3 + (kx + 1);
|
|
2195
|
-
gx += pixelVal * sobelX[kernelIdx];
|
|
2196
|
-
gy += pixelVal * sobelY[kernelIdx];
|
|
2197
|
-
}
|
|
2665
|
+
// 计算调整后的尺寸
|
|
2666
|
+
let newWidth = width;
|
|
2667
|
+
let newHeight = height;
|
|
2668
|
+
if (keepAspectRatio) {
|
|
2669
|
+
if (width > height) {
|
|
2670
|
+
if (width > maxWidth) {
|
|
2671
|
+
newHeight = Math.round(height * (maxWidth / width));
|
|
2672
|
+
newWidth = maxWidth;
|
|
2198
2673
|
}
|
|
2199
|
-
const idx = y * width + x;
|
|
2200
|
-
gradientMagnitude[idx] = Math.sqrt(gx * gx + gy * gy);
|
|
2201
|
-
gradientDirection[idx] = Math.atan2(gy, gx);
|
|
2202
2674
|
}
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
if (y === 0 || y === height - 1 || x === 0 || x === width - 1) {
|
|
2208
|
-
const idx = y * width + x;
|
|
2209
|
-
gradientMagnitude[idx] = 0;
|
|
2210
|
-
gradientDirection[idx] = 0;
|
|
2675
|
+
else {
|
|
2676
|
+
if (height > maxHeight) {
|
|
2677
|
+
newWidth = Math.round(width * (maxHeight / height));
|
|
2678
|
+
newHeight = maxHeight;
|
|
2211
2679
|
}
|
|
2212
2680
|
}
|
|
2213
2681
|
}
|
|
2214
|
-
|
|
2682
|
+
else {
|
|
2683
|
+
newWidth = Math.min(width, maxWidth);
|
|
2684
|
+
newHeight = Math.min(height, maxHeight);
|
|
2685
|
+
}
|
|
2686
|
+
// 设置canvas尺寸
|
|
2687
|
+
canvas.width = newWidth;
|
|
2688
|
+
canvas.height = newHeight;
|
|
2689
|
+
// 绘制调整后的图像
|
|
2690
|
+
if (image instanceof ImageData) {
|
|
2691
|
+
// 创建临时canvas存储ImageData
|
|
2692
|
+
const tempCanvas = document.createElement('canvas');
|
|
2693
|
+
const tempCtx = tempCanvas.getContext('2d');
|
|
2694
|
+
if (!tempCtx) {
|
|
2695
|
+
throw new Error('无法创建临时Canvas上下文');
|
|
2696
|
+
}
|
|
2697
|
+
tempCanvas.width = image.width;
|
|
2698
|
+
tempCanvas.height = image.height;
|
|
2699
|
+
tempCtx.putImageData(image, 0, 0);
|
|
2700
|
+
// 绘制调整后的图像
|
|
2701
|
+
ctx.drawImage(tempCanvas, 0, 0, width, height, 0, 0, newWidth, newHeight);
|
|
2702
|
+
}
|
|
2703
|
+
else {
|
|
2704
|
+
ctx.drawImage(image, 0, 0, width, height, 0, 0, newWidth, newHeight);
|
|
2705
|
+
}
|
|
2706
|
+
// 返回调整后的ImageData
|
|
2707
|
+
return ctx.getImageData(0, 0, newWidth, newHeight);
|
|
2215
2708
|
}
|
|
2216
2709
|
/**
|
|
2217
|
-
*
|
|
2710
|
+
* @deprecated 请使用 EdgeDetector.detectEdges()
|
|
2218
2711
|
*/
|
|
2219
|
-
static
|
|
2220
|
-
|
|
2221
|
-
for (let y = 1; y < height - 1; y++) {
|
|
2222
|
-
for (let x = 1; x < width - 1; x++) {
|
|
2223
|
-
const idx = y * width + x;
|
|
2224
|
-
const magnitude = gradientMagnitude[idx];
|
|
2225
|
-
const direction = gradientDirection[idx];
|
|
2226
|
-
// 将方向转化为角度
|
|
2227
|
-
const degrees = (direction * 180 / Math.PI + 180) % 180;
|
|
2228
|
-
// 获取相邻像素索引
|
|
2229
|
-
let neighbor1Idx, neighbor2Idx;
|
|
2230
|
-
// 将方向量化为四个方向: 0°, 45°, 90°, 135°
|
|
2231
|
-
if ((degrees >= 0 && degrees < 22.5) || (degrees >= 157.5 && degrees <= 180)) {
|
|
2232
|
-
// 水平方向
|
|
2233
|
-
neighbor1Idx = idx - 1;
|
|
2234
|
-
neighbor2Idx = idx + 1;
|
|
2235
|
-
}
|
|
2236
|
-
else if (degrees >= 22.5 && degrees < 67.5) {
|
|
2237
|
-
// 45度方向
|
|
2238
|
-
neighbor1Idx = (y - 1) * width + (x + 1);
|
|
2239
|
-
neighbor2Idx = (y + 1) * width + (x - 1);
|
|
2240
|
-
}
|
|
2241
|
-
else if (degrees >= 67.5 && degrees < 112.5) {
|
|
2242
|
-
// 垂直方向
|
|
2243
|
-
neighbor1Idx = (y - 1) * width + x;
|
|
2244
|
-
neighbor2Idx = (y + 1) * width + x;
|
|
2245
|
-
}
|
|
2246
|
-
else {
|
|
2247
|
-
// 135度方向
|
|
2248
|
-
neighbor1Idx = (y - 1) * width + (x - 1);
|
|
2249
|
-
neighbor2Idx = (y + 1) * width + (x + 1);
|
|
2250
|
-
}
|
|
2251
|
-
// 检查当前像素是否是最大值
|
|
2252
|
-
if (magnitude >= gradientMagnitude[neighbor1Idx] &&
|
|
2253
|
-
magnitude >= gradientMagnitude[neighbor2Idx]) {
|
|
2254
|
-
result[idx] = magnitude;
|
|
2255
|
-
}
|
|
2256
|
-
}
|
|
2257
|
-
}
|
|
2258
|
-
return result;
|
|
2712
|
+
static detectEdges(imageData, threshold = 30) {
|
|
2713
|
+
return EdgeDetector.detectEdges(imageData, threshold);
|
|
2259
2714
|
}
|
|
2260
2715
|
/**
|
|
2261
|
-
*
|
|
2716
|
+
* @deprecated 请使用 EdgeDetector.cannyEdgeDetection()
|
|
2262
2717
|
*/
|
|
2263
|
-
static
|
|
2264
|
-
|
|
2265
|
-
const visited = new Array(width * height).fill(false);
|
|
2266
|
-
const stack = [];
|
|
2267
|
-
// 标记强边缘点
|
|
2268
|
-
for (let i = 0; i < nonMaxSuppressed.length; i++) {
|
|
2269
|
-
if (nonMaxSuppressed[i] >= highThreshold) {
|
|
2270
|
-
result[i] = true;
|
|
2271
|
-
stack.push(i);
|
|
2272
|
-
visited[i] = true;
|
|
2273
|
-
}
|
|
2274
|
-
}
|
|
2275
|
-
// 使用深度优先搜索连接弱边缘
|
|
2276
|
-
const dx = [-1, 0, 1, -1, 1, -1, 0, 1];
|
|
2277
|
-
const dy = [-1, -1, -1, 0, 0, 1, 1, 1];
|
|
2278
|
-
while (stack.length > 0) {
|
|
2279
|
-
const currentIdx = stack.pop();
|
|
2280
|
-
const currentX = currentIdx % width;
|
|
2281
|
-
const currentY = Math.floor(currentIdx / width);
|
|
2282
|
-
// 检查88个相邻方向
|
|
2283
|
-
for (let i = 0; i < 8; i++) {
|
|
2284
|
-
const newX = currentX + dx[i];
|
|
2285
|
-
const newY = currentY + dy[i];
|
|
2286
|
-
if (newX >= 0 && newX < width && newY >= 0 && newY < height) {
|
|
2287
|
-
const newIdx = newY * width + newX;
|
|
2288
|
-
if (!visited[newIdx] && nonMaxSuppressed[newIdx] >= lowThreshold) {
|
|
2289
|
-
result[newIdx] = true;
|
|
2290
|
-
stack.push(newIdx);
|
|
2291
|
-
visited[newIdx] = true;
|
|
2292
|
-
}
|
|
2293
|
-
}
|
|
2294
|
-
}
|
|
2295
|
-
}
|
|
2296
|
-
return result;
|
|
2718
|
+
static cannyEdgeDetection(imageData, lowThreshold = 20, highThreshold = 50) {
|
|
2719
|
+
return EdgeDetector.cannyEdgeDetection(imageData, lowThreshold, highThreshold);
|
|
2297
2720
|
}
|
|
2298
2721
|
}
|
|
2299
2722
|
|
|
@@ -2583,7 +3006,7 @@
|
|
|
2583
3006
|
// 识别图像
|
|
2584
3007
|
const { data } = await worker.recognize(input.imageBase64);
|
|
2585
3008
|
// 解析身份证信息
|
|
2586
|
-
const idCardInfo =
|
|
3009
|
+
const idCardInfo = IDCardTextParser.parse(data.text);
|
|
2587
3010
|
// 释放Worker资源
|
|
2588
3011
|
await worker.terminate();
|
|
2589
3012
|
const processingTime = performance.now() - startTime;
|
|
@@ -2597,160 +3020,6 @@
|
|
|
2597
3020
|
};
|
|
2598
3021
|
}
|
|
2599
3022
|
}
|
|
2600
|
-
/**
|
|
2601
|
-
* 解析身份证文本
|
|
2602
|
-
* @param text OCR识别的文本
|
|
2603
|
-
* @returns 解析后的身份证信息
|
|
2604
|
-
*/
|
|
2605
|
-
function parseIDCardText(text) {
|
|
2606
|
-
const info = {};
|
|
2607
|
-
// 预处理文本,清除多余空白
|
|
2608
|
-
const processedText = text.replace(/\s+/g, ' ').trim();
|
|
2609
|
-
// 解析身份证号码
|
|
2610
|
-
const idNumberRegex = /(\d{17}[\dX])/;
|
|
2611
|
-
const idNumberWithPrefixRegex = /公民身份号码[\s\:]*(\d{17}[\dX])/;
|
|
2612
|
-
const basicMatch = processedText.match(idNumberRegex);
|
|
2613
|
-
const prefixMatch = processedText.match(idNumberWithPrefixRegex);
|
|
2614
|
-
if (prefixMatch && prefixMatch[1]) {
|
|
2615
|
-
info.idNumber = prefixMatch[1];
|
|
2616
|
-
}
|
|
2617
|
-
else if (basicMatch && basicMatch[1]) {
|
|
2618
|
-
info.idNumber = basicMatch[1];
|
|
2619
|
-
}
|
|
2620
|
-
// 解析姓名
|
|
2621
|
-
const nameWithLabelRegex = /姓名[\s\:]*([一-龥]{2,4})/;
|
|
2622
|
-
const nameMatch = processedText.match(nameWithLabelRegex);
|
|
2623
|
-
if (nameMatch && nameMatch[1]) {
|
|
2624
|
-
info.name = nameMatch[1].trim();
|
|
2625
|
-
}
|
|
2626
|
-
else {
|
|
2627
|
-
// 备用方案:查找短行且内容全是汉字
|
|
2628
|
-
const lines = processedText.split('\n').filter(line => line.trim());
|
|
2629
|
-
for (const line of lines) {
|
|
2630
|
-
if (line.length >= 2 &&
|
|
2631
|
-
line.length <= 5 &&
|
|
2632
|
-
/^[一-龥]+$/.test(line) &&
|
|
2633
|
-
!/性别|民族|住址|公民|签发|有效/.test(line)) {
|
|
2634
|
-
info.name = line.trim();
|
|
2635
|
-
break;
|
|
2636
|
-
}
|
|
2637
|
-
}
|
|
2638
|
-
}
|
|
2639
|
-
// 解析性别和民族
|
|
2640
|
-
const genderAndNationalityRegex = /性别[\s\:]*([男女])[\s ]*民族[\s\:]*([一-龥]+族)/;
|
|
2641
|
-
const genderOnlyRegex = /性别[\s\:]*([男女])/;
|
|
2642
|
-
const nationalityOnlyRegex = /民族[\s\:]*([一-龥]+族)/;
|
|
2643
|
-
const genderNationalityMatch = processedText.match(genderAndNationalityRegex);
|
|
2644
|
-
const genderOnlyMatch = processedText.match(genderOnlyRegex);
|
|
2645
|
-
const nationalityOnlyMatch = processedText.match(nationalityOnlyRegex);
|
|
2646
|
-
if (genderNationalityMatch) {
|
|
2647
|
-
info.gender = genderNationalityMatch[1];
|
|
2648
|
-
info.ethnicity = genderNationalityMatch[2];
|
|
2649
|
-
}
|
|
2650
|
-
else {
|
|
2651
|
-
if (genderOnlyMatch)
|
|
2652
|
-
info.gender = genderOnlyMatch[1];
|
|
2653
|
-
if (nationalityOnlyMatch)
|
|
2654
|
-
info.ethnicity = nationalityOnlyMatch[1];
|
|
2655
|
-
}
|
|
2656
|
-
// 根据内容判断身份证类型
|
|
2657
|
-
if (processedText.includes('出生') || processedText.includes('公民身份号码')) {
|
|
2658
|
-
info.type = exports.IDCardType.FRONT; // 确保类型为枚举值而不是字符串
|
|
2659
|
-
}
|
|
2660
|
-
else if (processedText.includes('签发机关') || processedText.includes('有效期')) {
|
|
2661
|
-
info.type = exports.IDCardType.BACK; // 确保类型为枚举值而不是字符串
|
|
2662
|
-
}
|
|
2663
|
-
// 解析出生日期
|
|
2664
|
-
const birthDateRegex1 = /出生[\s\:]*(\d{4})年(\d{1,2})月(\d{1,2})[日号]/;
|
|
2665
|
-
const birthDateRegex2 = /出生[\s\:]*(\d{4})[-\/\.](\d{1,2})[-\/\.](\d{1,2})/;
|
|
2666
|
-
const birthDateRegex3 = /出生日期[\s\:]*(\d{4})[-\/\.\u5e74](\d{1,2})[-\/\.\u6708](\d{1,2})[日号]?/;
|
|
2667
|
-
const birthDateMatch = processedText.match(birthDateRegex1) ||
|
|
2668
|
-
processedText.match(birthDateRegex2) ||
|
|
2669
|
-
processedText.match(birthDateRegex3);
|
|
2670
|
-
if (!birthDateMatch && info.idNumber && info.idNumber.length === 18) {
|
|
2671
|
-
const year = info.idNumber.substring(6, 10);
|
|
2672
|
-
const month = info.idNumber.substring(10, 12);
|
|
2673
|
-
const day = info.idNumber.substring(12, 14);
|
|
2674
|
-
info.birthDate = `${year}-${month}-${day}`;
|
|
2675
|
-
}
|
|
2676
|
-
else if (birthDateMatch) {
|
|
2677
|
-
const year = birthDateMatch[1];
|
|
2678
|
-
const month = birthDateMatch[2].padStart(2, '0');
|
|
2679
|
-
const day = birthDateMatch[3].padStart(2, '0');
|
|
2680
|
-
info.birthDate = `${year}-${month}-${day}`;
|
|
2681
|
-
}
|
|
2682
|
-
// 解析地址
|
|
2683
|
-
const addressRegex1 = /住址[\s\:]*([\s\S]*?)(?=公民身份|出生|性别|签发)/;
|
|
2684
|
-
const addressRegex2 = /住址[\s\:]*([一-龥a-zA-Z0-9\s\.\-]+)/;
|
|
2685
|
-
const addressMatch = processedText.match(addressRegex1) || processedText.match(addressRegex2);
|
|
2686
|
-
if (addressMatch && addressMatch[1]) {
|
|
2687
|
-
info.address = addressMatch[1]
|
|
2688
|
-
.replace(/\s+/g, '')
|
|
2689
|
-
.replace(/\n/g, '')
|
|
2690
|
-
.trim();
|
|
2691
|
-
if (info.address.length > 70) {
|
|
2692
|
-
info.address = info.address.substring(0, 70);
|
|
2693
|
-
}
|
|
2694
|
-
if (!/[一-龥]/.test(info.address)) {
|
|
2695
|
-
info.address = '';
|
|
2696
|
-
}
|
|
2697
|
-
}
|
|
2698
|
-
// 解析签发机关
|
|
2699
|
-
const authorityRegex1 = /签发机关[\s\:]*([\s\S]*?)(?=有效|公民|出生|\d{8}|$)/;
|
|
2700
|
-
const authorityRegex2 = /签发机关[\s\:]*([一-龥\s]+)/;
|
|
2701
|
-
const authorityMatch = processedText.match(authorityRegex1) ||
|
|
2702
|
-
processedText.match(authorityRegex2);
|
|
2703
|
-
if (authorityMatch && authorityMatch[1]) {
|
|
2704
|
-
info.issueAuthority = authorityMatch[1]
|
|
2705
|
-
.replace(/\s+/g, '')
|
|
2706
|
-
.replace(/\n/g, '')
|
|
2707
|
-
.trim();
|
|
2708
|
-
}
|
|
2709
|
-
// 解析有效期限
|
|
2710
|
-
const validPeriodRegex1 = /有效期限[\s\:]*(\d{4}[-\.\u5e74\s]\d{1,2}[-\.\u6708\s]\d{1,2}[日\s]*)[-\s]*(至|-)[-\s]*(\d{4}[-\.\u5e74\s]\d{1,2}[-\.\u6708\s]\d{1,2}[日]*|[永久长期]*)/;
|
|
2711
|
-
const validPeriodRegex2 = /有效期限[\s\:]*(\d{8})[-\s]*(至|-)[-\s]*(\d{8}|[永久长期]*)/;
|
|
2712
|
-
const validPeriodMatch = processedText.match(validPeriodRegex1) ||
|
|
2713
|
-
processedText.match(validPeriodRegex2);
|
|
2714
|
-
if (validPeriodMatch) {
|
|
2715
|
-
if (validPeriodMatch[1] && validPeriodMatch[3]) {
|
|
2716
|
-
const startDate = formatDateString(validPeriodMatch[1]);
|
|
2717
|
-
const endDate = /\d/.test(validPeriodMatch[3])
|
|
2718
|
-
? formatDateString(validPeriodMatch[3])
|
|
2719
|
-
: '长期有效';
|
|
2720
|
-
info.validFrom = startDate;
|
|
2721
|
-
info.validTo = endDate;
|
|
2722
|
-
info.validPeriod = `${startDate}-${endDate}`;
|
|
2723
|
-
}
|
|
2724
|
-
else {
|
|
2725
|
-
info.validPeriod = validPeriodMatch[0].replace('有效期限', '').trim();
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
return info;
|
|
2729
|
-
}
|
|
2730
|
-
/**
|
|
2731
|
-
* 格式化日期字符串
|
|
2732
|
-
* @param dateStr 原始日期字符串
|
|
2733
|
-
* @returns 格式化后的日期字符串
|
|
2734
|
-
*/
|
|
2735
|
-
function formatDateString(dateStr) {
|
|
2736
|
-
// 提取年月日
|
|
2737
|
-
const dateMatch = dateStr.match(/(\d{4})[-\.\u5e74\s]*(\d{1,2})[-\.\u6708\s]*(\d{1,2})[日]*/);
|
|
2738
|
-
if (dateMatch) {
|
|
2739
|
-
const year = dateMatch[1];
|
|
2740
|
-
const month = dateMatch[2].padStart(2, '0');
|
|
2741
|
-
const day = dateMatch[3].padStart(2, '0');
|
|
2742
|
-
return `${year}-${month}-${day}`;
|
|
2743
|
-
}
|
|
2744
|
-
// 纯数字格式如 20220101
|
|
2745
|
-
if (/^\d{8}$/.test(dateStr)) {
|
|
2746
|
-
const year = dateStr.substring(0, 4);
|
|
2747
|
-
const month = dateStr.substring(4, 6);
|
|
2748
|
-
const day = dateStr.substring(6, 8);
|
|
2749
|
-
return `${year}-${month}-${day}`;
|
|
2750
|
-
}
|
|
2751
|
-
// 无法格式化,返回原始字符串
|
|
2752
|
-
return dateStr;
|
|
2753
|
-
}
|
|
2754
3023
|
|
|
2755
3024
|
/**
|
|
2756
3025
|
* @file OCR处理器
|
|
@@ -2802,7 +3071,7 @@
|
|
|
2802
3071
|
/**
|
|
2803
3072
|
* 初始化OCR引擎
|
|
2804
3073
|
*
|
|
2805
|
-
* 加载Tesseract OCR
|
|
3074
|
+
* 加载Tesseract OCR引擎和中文简体语言包,并设置适合身份证识别的参数
|
|
2806
3075
|
*
|
|
2807
3076
|
* @returns {Promise<void>} 初始化完成的Promise
|
|
2808
3077
|
*/
|
|
@@ -2824,11 +3093,11 @@
|
|
|
2824
3093
|
await this.worker.loadLanguage("chi_sim");
|
|
2825
3094
|
await this.worker.initialize("chi_sim");
|
|
2826
3095
|
await this.worker.setParameters({
|
|
2827
|
-
tessedit_char_whitelist: "0123456789X年月日壹贰叁肆伍陆柒捌玖拾民族汉满回维吾尔藏苗彝壮朝鲜侗瑶白土家哈尼哈萨克傣黎傈僳佤高山拉祜水东乡纳西景颇柯尔克孜达斡尔仫佬羌布朗撒拉毛南仡佬锡伯阿昌普米塔吉克怒乌孜别克俄罗斯鄂温克德昂保安裕固京塔塔尔独龙鄂伦春赫哲门巴珞巴基诺男女住址出生公民身份号码签发机关有效期省市区县乡镇街道号楼单元室ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", //
|
|
3096
|
+
tessedit_char_whitelist: "0123456789X年月日壹贰叁肆伍陆柒捌玖拾民族汉满回维吾尔藏苗彝壮朝鲜侗瑶白土家哈尼哈萨克傣黎傈僳佤高山拉祜水东乡纳西景颇柯尔克孜达斡尔仫佬羌布朗撒拉毛南仡佬锡伯阿昌普米塔吉克怒乌孜别克俄罗斯鄂温克德昂保安裕固京塔塔尔独龙鄂伦春赫哲门巴珞巴基诺男女住址出生公民身份号码签发机关有效期省市区县乡镇街道号楼单元室ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", // 优化字符白名单,增加常见地址字符,移除部分不常用汉字
|
|
2828
3097
|
});
|
|
2829
|
-
//
|
|
3098
|
+
// 增加一些针对性的参数,提高识别率
|
|
2830
3099
|
await this.worker.setParameters({
|
|
2831
|
-
tessedit_pageseg_mode: 7, // PSM_SINGLE_LINE
|
|
3100
|
+
tessedit_pageseg_mode: 7, // PSM_SINGLE_LINE,使用数字而不是字符串
|
|
2832
3101
|
preserve_interword_spaces: "1", // 保留单词间的空格
|
|
2833
3102
|
});
|
|
2834
3103
|
this.initialized = true;
|
|
@@ -2844,7 +3113,7 @@
|
|
|
2844
3113
|
if (!this.initialized) {
|
|
2845
3114
|
await this.initialize();
|
|
2846
3115
|
}
|
|
2847
|
-
//
|
|
3116
|
+
// 计算图像指纹,用于缓存查找
|
|
2848
3117
|
if (this.options.enableCache) {
|
|
2849
3118
|
const fingerprint = calculateImageFingerprint(imageData);
|
|
2850
3119
|
// 检查缓存中是否有结果
|
|
@@ -2861,7 +3130,7 @@
|
|
|
2861
3130
|
const enhancedImage = ImageProcessor.batchProcess(downsampledImage, {
|
|
2862
3131
|
brightness: this.options.brightness !== undefined ? this.options.brightness : 10, // 调整默认亮度
|
|
2863
3132
|
contrast: this.options.contrast !== undefined ? this.options.contrast : 20, // 调整默认对比度
|
|
2864
|
-
sharpen: true, //
|
|
3133
|
+
sharpen: true, // 默认启用锐化,通常对OCR有益
|
|
2865
3134
|
});
|
|
2866
3135
|
// 转换为base64供Tesseract处理
|
|
2867
3136
|
// 创建一个canvas元素
|
|
@@ -2883,11 +3152,11 @@
|
|
|
2883
3152
|
// 使用Worker线程处理
|
|
2884
3153
|
const result = await this.ocrWorker.postMessage({
|
|
2885
3154
|
imageBase64: base64Image,
|
|
2886
|
-
//
|
|
3155
|
+
// 不传递函数对象,避免DataCloneError
|
|
2887
3156
|
tessWorkerOptions: {},
|
|
2888
3157
|
});
|
|
2889
3158
|
idCardInfo = result.idCardInfo;
|
|
2890
|
-
this.options.logger?.(`OCR
|
|
3159
|
+
this.options.logger?.(`OCR处理完成,用时: ${result.processingTime.toFixed(2)}ms`);
|
|
2891
3160
|
}
|
|
2892
3161
|
else {
|
|
2893
3162
|
// 使用主线程处理
|
|
@@ -2900,9 +3169,9 @@
|
|
|
2900
3169
|
}
|
|
2901
3170
|
const { data } = (await this.worker.recognize(canvas));
|
|
2902
3171
|
// 解析身份证信息
|
|
2903
|
-
idCardInfo =
|
|
3172
|
+
idCardInfo = IDCardTextParser.parse(data.text);
|
|
2904
3173
|
const processingTime = performance.now() - startTime;
|
|
2905
|
-
this.options.logger?.(`OCR
|
|
3174
|
+
this.options.logger?.(`OCR处理完成,用时: ${processingTime.toFixed(2)}ms`);
|
|
2906
3175
|
}
|
|
2907
3176
|
// 缓存结果
|
|
2908
3177
|
if (this.options.enableCache) {
|
|
@@ -2919,7 +3188,7 @@
|
|
|
2919
3188
|
? JSON.stringify(error)
|
|
2920
3189
|
: String(error);
|
|
2921
3190
|
this.options.logger?.(`OCR识别错误: ${errorMessage}`);
|
|
2922
|
-
// 返回 null
|
|
3191
|
+
// 返回 null,让调用方知道识别失败
|
|
2923
3192
|
return null;
|
|
2924
3193
|
}
|
|
2925
3194
|
}
|
|
@@ -2932,198 +3201,6 @@
|
|
|
2932
3201
|
* @param {string} text - OCR识别到的文本
|
|
2933
3202
|
* @returns {IDCardInfo} 提取到的身份证信息对象
|
|
2934
3203
|
*/
|
|
2935
|
-
/**
|
|
2936
|
-
* 格式化日期字符串为标准格式 (YYYY-MM-DD)
|
|
2937
|
-
* @param dateStr 原始日期字符串
|
|
2938
|
-
* @returns 格式化后的日期字符串
|
|
2939
|
-
*/
|
|
2940
|
-
formatDateString(dateStr) {
|
|
2941
|
-
// 先尝试提取年月日
|
|
2942
|
-
const dateMatch = dateStr.match(/(\d{4})[-\.\u5e74\s]*(\d{1,2})[-\.\u6708\s]*(\d{1,2})[日]*/);
|
|
2943
|
-
if (dateMatch) {
|
|
2944
|
-
const year = dateMatch[1];
|
|
2945
|
-
const month = dateMatch[2].padStart(2, "0");
|
|
2946
|
-
const day = dateMatch[3].padStart(2, "0");
|
|
2947
|
-
return `${year}-${month}-${day}`;
|
|
2948
|
-
}
|
|
2949
|
-
// 如果是纯数字格式如 20220101
|
|
2950
|
-
if (/^\d{8}$/.test(dateStr)) {
|
|
2951
|
-
const year = dateStr.substring(0, 4);
|
|
2952
|
-
const month = dateStr.substring(4, 6);
|
|
2953
|
-
const day = dateStr.substring(6, 8);
|
|
2954
|
-
return `${year}-${month}-${day}`;
|
|
2955
|
-
}
|
|
2956
|
-
// 如果无法格式化,返回原始字符串
|
|
2957
|
-
return dateStr;
|
|
2958
|
-
}
|
|
2959
|
-
/**
|
|
2960
|
-
* 验证身份证号是否符合规则
|
|
2961
|
-
* @param idNumber 身份证号
|
|
2962
|
-
* @returns 是否有效
|
|
2963
|
-
*/
|
|
2964
|
-
validateIDNumber(idNumber) {
|
|
2965
|
-
// 基本验证,校验位有效性和长度
|
|
2966
|
-
if (!idNumber || idNumber.length !== 18) {
|
|
2967
|
-
return false;
|
|
2968
|
-
}
|
|
2969
|
-
// 检查格式,前17位必须为数字,最后一位可以是数字或'X'
|
|
2970
|
-
const pattern = /^\d{17}[\dX]$/;
|
|
2971
|
-
if (!pattern.test(idNumber)) {
|
|
2972
|
-
return false;
|
|
2973
|
-
}
|
|
2974
|
-
// 检查日期部分
|
|
2975
|
-
parseInt(idNumber.substr(6, 4));
|
|
2976
|
-
const month = parseInt(idNumber.substr(10, 2));
|
|
2977
|
-
const day = parseInt(idNumber.substr(12, 2));
|
|
2978
|
-
if (month < 1 || month > 12 || day < 1 || day > 31) {
|
|
2979
|
-
return false;
|
|
2980
|
-
}
|
|
2981
|
-
// 更详细的检查可以添加校验位的验证等逻辑...
|
|
2982
|
-
return true;
|
|
2983
|
-
}
|
|
2984
|
-
parseIDCardText(text) {
|
|
2985
|
-
const info = {};
|
|
2986
|
-
// 预处理文本,清除多余空白
|
|
2987
|
-
const processedText = text.replace(/\s+/g, " ").trim();
|
|
2988
|
-
// 拆分为行,并过滤空行
|
|
2989
|
-
const lines = processedText.split("\n").filter((line) => line.trim());
|
|
2990
|
-
// 解析身份证号码 - 多种模式匹配
|
|
2991
|
-
// 1. 普通18位身份证号模式
|
|
2992
|
-
const idNumberRegex = /(\d{17}[\dX])/;
|
|
2993
|
-
// 2. 带前缀的模式
|
|
2994
|
-
const idNumberWithPrefixRegex = /公民身份号码[\s\:]*(\d{17}[\dX])/;
|
|
2995
|
-
// 尝试所有模式
|
|
2996
|
-
let idNumber = null;
|
|
2997
|
-
const basicMatch = processedText.match(idNumberRegex);
|
|
2998
|
-
const prefixMatch = processedText.match(idNumberWithPrefixRegex);
|
|
2999
|
-
if (prefixMatch && prefixMatch[1]) {
|
|
3000
|
-
idNumber = prefixMatch[1]; // 首选带前缀的匹配,因为最可靠
|
|
3001
|
-
}
|
|
3002
|
-
else if (basicMatch && basicMatch[1]) {
|
|
3003
|
-
idNumber = basicMatch[1]; // 其次是常规匹配
|
|
3004
|
-
}
|
|
3005
|
-
if (idNumber) {
|
|
3006
|
-
info.idNumber = idNumber;
|
|
3007
|
-
}
|
|
3008
|
-
// 解析姓名 - 使用多种策略
|
|
3009
|
-
// 1. 直接匹配姓名标签近的内容
|
|
3010
|
-
const nameWithLabelRegex = /姓名[\s\:]*([一-龥]{2,4})/;
|
|
3011
|
-
const nameMatch = processedText.match(nameWithLabelRegex);
|
|
3012
|
-
// 2. 分析行文本寻找姓名
|
|
3013
|
-
if (nameMatch && nameMatch[1]) {
|
|
3014
|
-
info.name = nameMatch[1].trim();
|
|
3015
|
-
}
|
|
3016
|
-
else {
|
|
3017
|
-
// 备用方案:查找短行且内容全是汉字
|
|
3018
|
-
for (const line of lines) {
|
|
3019
|
-
if (line.length >= 2 &&
|
|
3020
|
-
line.length <= 5 &&
|
|
3021
|
-
/^[一-龥]+$/.test(line) &&
|
|
3022
|
-
!/性别|民族|住址|公民|签发|有效/.test(line)) {
|
|
3023
|
-
info.name = line.trim();
|
|
3024
|
-
break;
|
|
3025
|
-
}
|
|
3026
|
-
}
|
|
3027
|
-
}
|
|
3028
|
-
// 解析性别和民族 - 多种模式匹配
|
|
3029
|
-
// 1. 标准格式匹配
|
|
3030
|
-
const genderAndNationalityRegex = /性别[\s\:]*([男女])[\s ]*民族[\s\:]*([一-龥]+族)/;
|
|
3031
|
-
const genderNationalityMatch = processedText.match(genderAndNationalityRegex);
|
|
3032
|
-
// 2. 只匹配性别
|
|
3033
|
-
const genderOnlyRegex = /性别[\s\:]*([男女])/;
|
|
3034
|
-
const genderOnlyMatch = processedText.match(genderOnlyRegex);
|
|
3035
|
-
// 3. 只匹配民族
|
|
3036
|
-
const nationalityOnlyRegex = /民族[\s\:]*([一-龥]+族)/;
|
|
3037
|
-
const nationalityOnlyMatch = processedText.match(nationalityOnlyRegex);
|
|
3038
|
-
if (genderNationalityMatch) {
|
|
3039
|
-
info.gender = genderNationalityMatch[1];
|
|
3040
|
-
info.nationality = genderNationalityMatch[2];
|
|
3041
|
-
}
|
|
3042
|
-
else {
|
|
3043
|
-
// 分开获取
|
|
3044
|
-
if (genderOnlyMatch)
|
|
3045
|
-
info.gender = genderOnlyMatch[1];
|
|
3046
|
-
if (nationalityOnlyMatch)
|
|
3047
|
-
info.nationality = nationalityOnlyMatch[1];
|
|
3048
|
-
}
|
|
3049
|
-
// 解析出生日期 - 支持多种格式
|
|
3050
|
-
// 1. 标准格式:YYYY年MM月DD日
|
|
3051
|
-
const birthDateRegex1 = /出生[\s\:]*(\d{4})年(\d{1,2})月(\d{1,2})[日号]/;
|
|
3052
|
-
// 2. 美式日期格式:YYYY-MM-DD或YYYY/MM/DD
|
|
3053
|
-
const birthDateRegex2 = /出生[\s\:]*(\d{4})[-\/\.](\d{1,2})[-\/\.](\d{1,2})/;
|
|
3054
|
-
// 3. 带前缀的格式
|
|
3055
|
-
const birthDateRegex3 = /出生日期[\s\:]*(\d{4})[-\/\.\u5e74](\d{1,2})[-\/\.\u6708](\d{1,2})[日号]?/;
|
|
3056
|
-
let birthDateMatch = processedText.match(birthDateRegex1) ||
|
|
3057
|
-
processedText.match(birthDateRegex2) ||
|
|
3058
|
-
processedText.match(birthDateRegex3);
|
|
3059
|
-
// 4. 从身份证号码中提取出生日期(如果上述方法失败)
|
|
3060
|
-
if (!birthDateMatch && info.idNumber && info.idNumber.length === 18) {
|
|
3061
|
-
const year = info.idNumber.substring(6, 10);
|
|
3062
|
-
const month = info.idNumber.substring(10, 12);
|
|
3063
|
-
const day = info.idNumber.substring(12, 14);
|
|
3064
|
-
info.birthDate = `${year}-${month}-${day}`;
|
|
3065
|
-
}
|
|
3066
|
-
else if (birthDateMatch) {
|
|
3067
|
-
// 确保月份和日期是两位数
|
|
3068
|
-
const year = birthDateMatch[1];
|
|
3069
|
-
const month = birthDateMatch[2].padStart(2, "0");
|
|
3070
|
-
const day = birthDateMatch[3].padStart(2, "0");
|
|
3071
|
-
info.birthDate = `${year}-${month}-${day}`;
|
|
3072
|
-
}
|
|
3073
|
-
// 解析地址 - 改进的正则匹配
|
|
3074
|
-
// 1. 常规模式
|
|
3075
|
-
const addressRegex1 = /住址[\s\:]*([\s\S]*?)(?=公民身份|出生|性别|签发)/;
|
|
3076
|
-
// 2. 更宽松的模式
|
|
3077
|
-
const addressRegex2 = /住址[\s\:]*([一-龥a-zA-Z0-9\s\.\-]+)/;
|
|
3078
|
-
const addressMatch = processedText.match(addressRegex1) || processedText.match(addressRegex2);
|
|
3079
|
-
if (addressMatch && addressMatch[1]) {
|
|
3080
|
-
// 清理地址中的常见错误和多余空格
|
|
3081
|
-
info.address = addressMatch[1]
|
|
3082
|
-
.replace(/\s+/g, "")
|
|
3083
|
-
.replace(/\n/g, "")
|
|
3084
|
-
.trim();
|
|
3085
|
-
// 限制地址长度并判断地址合理性
|
|
3086
|
-
if (info.address.length > 70) {
|
|
3087
|
-
info.address = info.address.substring(0, 70);
|
|
3088
|
-
}
|
|
3089
|
-
// 确保地址是合理的(不仅仅包含符号或数字)
|
|
3090
|
-
if (!/[一-龥]/.test(info.address)) {
|
|
3091
|
-
info.address = ""; // 如果没有中文字符,可能不是有效地址
|
|
3092
|
-
}
|
|
3093
|
-
}
|
|
3094
|
-
// 解析签发机关
|
|
3095
|
-
const authorityRegex1 = /签发机关[\s\:]*([\s\S]*?)(?=有效|公民|出生|\d{8}|$)/;
|
|
3096
|
-
const authorityRegex2 = /签发机关[\s\:]*([一-龥\s]+)/;
|
|
3097
|
-
const authorityMatch = processedText.match(authorityRegex1) ||
|
|
3098
|
-
processedText.match(authorityRegex2);
|
|
3099
|
-
if (authorityMatch && authorityMatch[1]) {
|
|
3100
|
-
info.issuingAuthority = authorityMatch[1]
|
|
3101
|
-
.replace(/\s+/g, "")
|
|
3102
|
-
.replace(/\n/g, "")
|
|
3103
|
-
.trim();
|
|
3104
|
-
}
|
|
3105
|
-
// 解析有效期限 - 支持多种格式
|
|
3106
|
-
// 1. 常规格式:YYYY.MM.DD-YYYY.MM.DD
|
|
3107
|
-
const validPeriodRegex1 = /有效期限[\s\:]*(\d{4}[-\.\u5e74\s]\d{1,2}[-\.\u6708\s]\d{1,2}[日\s]*)[-\s]*(至|-)[-\s]*(\d{4}[-\.\u5e74\s]\d{1,2}[-\.\u6708\s]\d{1,2}[日]*|[永久长期]*)/;
|
|
3108
|
-
// 2. 简化格式:YYYYMMDD-YYYYMMDD
|
|
3109
|
-
const validPeriodRegex2 = /有效期限[\s\:]*(\d{8})[-\s]*(至|-)[-\s]*(\d{8}|[永久长期]*)/;
|
|
3110
|
-
const validPeriodMatch = processedText.match(validPeriodRegex1) ||
|
|
3111
|
-
processedText.match(validPeriodRegex2);
|
|
3112
|
-
if (validPeriodMatch) {
|
|
3113
|
-
// 格式化为统一的有效期限形式
|
|
3114
|
-
if (validPeriodMatch[1] && validPeriodMatch[3]) {
|
|
3115
|
-
const startDate = this.formatDateString(validPeriodMatch[1]);
|
|
3116
|
-
const endDate = /\d/.test(validPeriodMatch[3])
|
|
3117
|
-
? this.formatDateString(validPeriodMatch[3])
|
|
3118
|
-
: "长期有效";
|
|
3119
|
-
info.validPeriod = `${startDate}-${endDate}`;
|
|
3120
|
-
}
|
|
3121
|
-
else {
|
|
3122
|
-
info.validPeriod = validPeriodMatch[0].replace("有效期限", "").trim();
|
|
3123
|
-
}
|
|
3124
|
-
}
|
|
3125
|
-
return info;
|
|
3126
|
-
}
|
|
3127
3204
|
/**
|
|
3128
3205
|
* 清除结果缓存
|
|
3129
3206
|
*/
|