Flutter进阶:基于 MLKit 的 OCR 文字识别

一、需求来源

今天无意中发现了一个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'
}

github

相关推荐
HookJames1 分钟前
Turnkey PCBA - Hero
前端·php
深海鱼在掘金5 分钟前
Next.js从入门到实战保姆级教程(第十章):表单处理与 Server Actions
前端·typescript·next.js
深海鱼在掘金5 分钟前
Next.js从入门到实战保姆级教程(第九章):元数据与 SEO 优化
前端·typescript·next.js
сокол5 分钟前
【网安-Web渗透测试-Linux提权】SUID提权
linux·前端·web安全·网络安全
深海鱼在掘金6 分钟前
Next.js从入门到实战保姆级教程(第八章):图像、字体与媒体优化
前端·typescript·next.js
英俊潇洒美少年6 分钟前
Vue2 高德地图地址选择器完整实战(组件抽离+高并发优化+@amap/amap-jsapi-loader最佳实践)
前端·javascript·vue.js
深海鱼在掘金9 分钟前
Next.js从入门到实战保姆级教程(第七章):样式方案与 UI 优化
前端·typescript·next.js
晴天丨16 分钟前
🛡️ Vue 3 错误处理完全指南:全局异常捕获、前端监控、用户反馈
前端·vue.js
孙凯亮16 分钟前
Electron 接口请求全解析:从疑问到落地(真实开发对话整理)
前端·electron
闲坐含香咀翠17 分钟前
Electron 桌面端多语言优化实战:从静态全量加载到懒加载与用户自定义
前端·electron·客户端