OcrUtil.java
12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package com.xly.ocr.util;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.benjaminwan.ocrlibrary.OcrResult;
import com.benjaminwan.ocrlibrary.TextBlock;
import io.github.mymonstercat.Model;
import io.github.mymonstercat.ocr.InferenceEngine;
import io.github.mymonstercat.ocr.config.ParamConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Slf4j
public class OcrUtil {
// 引擎实例(单例,避免重复初始化)
private static volatile InferenceEngine engine;
private static final Object LOCK = new Object();
/**
* 获取 OCR 引擎实例(懒加载单例)
*/
private static InferenceEngine getEngine() {
if (engine == null) {
synchronized (LOCK) {
if (engine == null) {
try {
log.info("初始化 OCR 引擎 (PP-OCRv4)...");
engine = InferenceEngine.getInstance(Model.ONNX_PPOCR_V4);
log.info("OCR 引擎初始化成功");
} catch (Exception e) {
log.error("OCR 引擎初始化失败: {}", e.getMessage(), e);
throw new RuntimeException("OCR 引擎初始化失败", e);
}
}
}
}
return engine;
}
/**
* 识别图片中的文字
* @param imageFile 上传的图片文件
* @param tempDir 临时目录路径
* @return 识别出的文字
*/
public static String ocrFile(MultipartFile imageFile, String tempDir) {
File tempImageFile = null;
String processedImagePath = null;
try {
log.info("开始 OCR 识别,文件: {}", imageFile.getOriginalFilename());
// 1. 验证输入
if (imageFile == null || imageFile.isEmpty()) {
log.warn("图片文件为空");
return StrUtil.EMPTY;
}
// 2. 创建临时目录
ensureTempDirExists(tempDir);
// 3. MultipartFile 转 File
tempImageFile = multipartFileToFile(imageFile, tempDir);
if (tempImageFile == null || !tempImageFile.exists()) {
log.error("转换临时文件失败");
return StrUtil.EMPTY;
}
// 4. 图像预处理
BufferedImage processedImage = preprocessImage(tempImageFile);
if (processedImage == null) {
log.error("图像预处理失败");
return StrUtil.EMPTY;
}
// 5. 保存预处理图片
processedImagePath = saveProcessedImage(processedImage, tempDir);
if (processedImagePath == null) {
log.error("保存预处理图片失败");
return StrUtil.EMPTY;
}
// 6. 执行 OCR 识别
String text = performOcr(processedImagePath);
// 7. 记录识别结果
if (StrUtil.isNotBlank(text)) {
log.info("OCR 识别成功,文字长度: {} 字符", text.length());
log.debug("识别结果: {}", text);
} else {
log.warn("OCR 识别结果为空");
}
return text;
} catch (Exception e) {
log.error("OCR 识别失败: {}", e.getMessage(), e);
return StrUtil.EMPTY;
} finally {
// 清理临时文件
cleanupTempFiles(tempImageFile, processedImagePath);
}
}
/**
* 确保临时目录存在
*/
private static void ensureTempDirExists(String tempDir) {
if (StrUtil.isBlank(tempDir)) {
tempDir = System.getProperty("java.io.tmpdir");
}
File dir = new File(tempDir);
if (!dir.exists()) {
boolean created = dir.mkdirs();
if (created) {
log.debug("创建临时目录: {}", tempDir);
} else {
log.warn("无法创建临时目录: {}", tempDir);
}
}
}
/**
* MultipartFile 转 File
* @param multipartFile 上传文件
* @param tempDir 临时目录
* @return File 对象
*/
public static File multipartFileToFile(MultipartFile multipartFile, String tempDir) throws IOException {
if (multipartFile == null || multipartFile.isEmpty()) {
return null;
}
// 获取文件扩展名
String originalFilename = multipartFile.getOriginalFilename();
String extension = getFileExtension(originalFilename);
// 生成唯一文件名
String uniqueFilename = UUID.randomUUID().toString() + extension;
String filePath = tempDir + File.separator + uniqueFilename;
File file = new File(filePath);
multipartFile.transferTo(file);
log.debug("创建临时文件: {}", filePath);
return file;
}
/**
* 执行 OCR 识别
*/
private static String performOcr(String imagePath) {
try {
// 获取引擎实例
InferenceEngine engine = getEngine();
// 创建参数配置
ParamConfig config = createOptimizedParamConfig();
// 执行识别
long startTime = System.currentTimeMillis();
OcrResult ocrResult = engine.runOcr(imagePath, config);
long endTime = System.currentTimeMillis();
log.info("OCR 识别耗时: {} ms", (endTime - startTime));
// 输出文本块详情(DEBUG 级别)
if (log.isDebugEnabled() && ocrResult.getTextBlocks() != null) {
List<TextBlock> textBlocks = ocrResult.getTextBlocks();
log.debug("识别到 {} 个文本块", textBlocks.size());
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock block = textBlocks.get(i);
log.debug(" 块{}: {} (置信度: {})",
i + 1, block.getText(), block.getBoxScore());
}
}
return ocrResult.getStrRes().trim();
} catch (Exception e) {
log.error("执行 OCR 识别失败: {}", e.getMessage(), e);
return StrUtil.EMPTY;
}
}
/**
* 保存预处理后的图片
*/
private static String saveProcessedImage(BufferedImage image, String tempDir) throws IOException {
if (image == null) {
return null;
}
String filename = "processed_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + ".png";
String filePath = tempDir + File.separator + filename;
File outputFile = new File(filePath);
ImageIO.write(image, "png", outputFile);
log.debug("保存预处理图片: {}", filePath);
return filePath;
}
/**
* 清理临时文件
*/
private static void cleanupTempFiles(File tempImageFile, String processedImagePath) {
// 清理原始临时文件
if (tempImageFile != null && tempImageFile.exists()) {
boolean deleted = tempImageFile.delete();
if (deleted) {
log.debug("删除临时文件: {}", tempImageFile.getPath());
} else {
log.warn("删除临时文件失败: {}", tempImageFile.getPath());
tempImageFile.deleteOnExit();
}
}
// 清理预处理图片
if (StrUtil.isNotBlank(processedImagePath)) {
File processedFile = new File(processedImagePath);
if (processedFile.exists()) {
boolean deleted = processedFile.delete();
if (deleted) {
log.debug("删除预处理图片: {}", processedImagePath);
} else {
log.warn("删除预处理图片失败: {}", processedImagePath);
processedFile.deleteOnExit();
}
}
}
}
/**
* 创建优化的参数配置
*/
private static ParamConfig createOptimizedParamConfig() {
ParamConfig config = new ParamConfig();
// 文本区域扩展
config.setPadding(50);
// 最大边长限制(0 表示不限制)
config.setMaxSideLen(0);
// 文本块置信度阈值
config.setBoxScoreThresh(0.4f);
config.setBoxThresh(0.25f);
// 文本区域扩展比例
config.setUnClipRatio(1.8f);
// 角度检测
config.setDoAngle(true);
config.setMostAngle(true);
log.debug("OCR 参数配置: padding={}, unClipRatio={}",
config.getPadding(), config.getUnClipRatio());
return config;
}
/**
* 图像预处理
*/
private static BufferedImage preprocessImage(File imageFile) throws IOException {
BufferedImage original = ImageIO.read(imageFile);
if (original == null) {
throw new IOException("无法读取图片: " + imageFile.getPath());
}
log.debug("原始图片尺寸: {}x{}", original.getWidth(), original.getHeight());
BufferedImage processed = original;
// 1. 如果图片太大,缩小尺寸
if (processed.getWidth() > 2000 || processed.getHeight() > 2000) {
processed = resizeImage(processed, 1600, 1600);
log.debug("缩小图片尺寸: {}x{}", processed.getWidth(), processed.getHeight());
}
// 2. 增强对比度
processed = enhanceContrast(processed);
return processed;
}
/**
* 调整图片大小
*/
private static BufferedImage resizeImage(BufferedImage image, int maxWidth, int maxHeight) {
int w = image.getWidth();
int h = image.getHeight();
// 计算缩放比例
double ratio = Math.min((double) maxWidth / w, (double) maxHeight / h);
if (ratio >= 1.0) {
return image;
}
int newW = (int) (w * ratio);
int newH = (int) (h * ratio);
BufferedImage resized = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawImage(image, 0, 0, newW, newH, null);
g.dispose();
return resized;
}
/**
* 增强对比度
*/
private static BufferedImage enhanceContrast(BufferedImage image) {
BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color c = new Color(image.getRGB(x, y));
int r = Math.min(255, (int) (c.getRed() * 1.15));
int g = Math.min(255, (int) (c.getGreen() * 1.15));
int b = Math.min(255, (int) (c.getBlue() * 1.15));
result.setRGB(x, y, new Color(r, g, b).getRGB());
}
}
return result;
}
/**
* 获取文件扩展名
*/
private static String getFileExtension(String filename) {
if (StrUtil.isBlank(filename)) {
return ".jpg";
}
int lastDotIndex = filename.lastIndexOf(".");
if (lastDotIndex == -1) {
return ".jpg";
}
return filename.substring(lastDotIndex);
}
/**
* 测试方法
*/
public static void main(String[] args) {
String tempDir = "D:/temp/ocrJava";
// 测试识别
try {
String imagePath = "E:/aa/b.jpg";
File imageFile = new File(imagePath);
if (!imageFile.exists()) {
System.err.println("图片文件不存在: " + imagePath);
return;
}
// 手动测试(实际使用中应该通过 MultipartFile)
BufferedImage processedImage = preprocessImage(imageFile);
String processedPath = saveProcessedImage(processedImage, tempDir);
String result = performOcr(processedPath);
System.out.println("识别结果: " + result);
// 清理
new File(processedPath).delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}