一、需求来源
今天无意中发现了一个OCR 中英文识别准确率非常高(测试图中99%,错了一个汉字)的库 google_mlkit_text_recognition ,分享给大家。
二、使用示例
scala
//
// OcrPhotoDemo.dart
// flutter_templet_project
//
// Created by shang on 2024/11/16 10:52.
// Copyright © 2024/11/16 shang. All rights reserved.
//
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:image_picker/image_picker.dart';
class OcrPhotoDemo extends StatefulWidget {
const OcrPhotoDemo({super.key});
@override
_OcrPhotoDemoState createState() => _OcrPhotoDemoState();
}
class _OcrPhotoDemoState extends State<OcrPhotoDemo> {
File? _imageFile;
String _recognizedText = "请上传图片进行文字识别";
final _picker = ImagePicker();
final _textRecognizer = TextRecognizer(script: TextRecognitionScript.chinese);
Future<void> _pickImage() async {
final image = await _picker.pickImage(source: ImageSource.gallery);
if (image != null) {
_imageFile = File(image.path);
_recognizedText = "正在识别文字...";
setState(() {});
_processImage(_imageFile!);
}
}
Future<void> _processImage(File imageFile) async {
final inputImage = InputImage.fromFile(imageFile);
try {
final recognizedText = await _textRecognizer.processImage(inputImage);
_recognizedText = recognizedText.text.isEmpty ? "未检测到文字" : recognizedText.text;
setState(() {});
} catch (e) {
_recognizedText = "识别失败:$e";
setState(() {});
}
}
@override
void dispose() {
_textRecognizer.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("文字识别")),
body: Scrollbar(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
if (_imageFile != null) Image.file(_imageFile!) else Icon(Icons.image, size: 100, color: Colors.grey),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: ElevatedButton(
onPressed: _pickImage,
child: Text("选择图片"),
),
),
Text(
_recognizedText,
textAlign: TextAlign.center,
),
SizedBox(height: 20),
],
),
),
),
);
}
}
三、使用指南
最后、总结
没什么可说的,目前 flutter 中使用最简单好用的库,强烈推荐!
注意点:
此包默认只支持拉丁字符的识别,如果需要识别其他语言,需要手动添加依赖。
对于 iOS 平台,在ios/Podfile
文件中手动添加:
dart
# Add language package you need to use
pod 'GoogleMLKit/TextRecognitionChinese', '~> 7.0.0'
pod 'GoogleMLKit/TextRecognitionDevanagari', '~> 7.0.0'
pod 'GoogleMLKit/TextRecognitionJapanese', '~> 7.0.0'
pod 'GoogleMLKit/TextRecognitionKorean', '~> 7.0.0'
对于 Android 平台,在android/app/build.gradle
文件中添加:
dart
dependencies {
// Add language package you need to use
implementation 'com.google.mlkit:text-recognition-chinese:16.0.0'
implementation 'com.google.mlkit:text-recognition-devanagari:16.0.0'
implementation 'com.google.mlkit:text-recognition-japanese:16.0.0'
implementation 'com.google.mlkit:text-recognition-korean:16.0.0'
}