Flutter文字识别插件focused_area_ocr_flutter的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter文字识别插件focused_area_ocr_flutter的使用

focused_area_ocr_flutter 是一个基于OCR技术的文字识别插件,可以从相机聚焦区域中获取文本。该插件依赖于 google_mlkit_text_recognition

特性

通过这个插件,您可以从相机聚焦区域中提取文本内容。以下是插件的功能展示:

示例图片

开始使用

iOS 设置

ios/Runner/Info.plist 文件中添加以下代码以请求相机和麦克风权限:

<key>NSCameraUsageDescription</key>
<string>your usage description here</string>
<key>NSMicrophoneUsageDescription</key>
<string>your usage description here</string>

编辑 ios/Runner/Info.plist 文件如下:

platform :ios, '12.0'  # 或更新版本

...

# 添加这行:
$iOSVersion = '12.0'  # 或更新版本

post_install do |installer|
  # 添加这些行:
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=*]"] = "armv7"
    config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = $iOSVersion
  end
  
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    
    # 添加这些行:
    target.build_configurations.each do |config|
      if Gem::Version.new($iOSVersion) > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'])
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = $iOSVersion
      end
    end
    
  end
end

Android 设置

编辑 android/app/build.gradle 并设置以下SDK版本:

  • minSdkVersion: 21
  • targetSdkVersion: 33
  • compileSdkVersion: 33

使用方法

这是一个使用 focused_area_ocr_flutter 插件的Flutter项目的完整示例:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:focused_area_ocr_flutter/focused_area_ocr_view.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Focused Area OCR Flutter',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final StreamController<String> controller = StreamController<String>();
  final double _textViewHeight = 80.0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).viewPadding.top;
    final Offset focusedAreaCenter = Offset(
      0,
      (statusBarHeight + kToolbarHeight + _textViewHeight) / 2,
    );
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          FocusedAreaOCRView(
            onScanText: (text) {
              controller.add(text);
            },
            focusedAreaCenter: focusedAreaCenter,
          ),
          Column(
            children: [
              SizedBox(
                height: statusBarHeight + kToolbarHeight,
                child: AppBar(
                  title: const Text('Focused Area OCR Flutter'),
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
              ),
              Container(
                padding: const EdgeInsets.all(16.0),
                width: double.infinity,
                height: _textViewHeight,
                color: Colors.black,
                child: StreamBuilder<String>(
                  stream: controller.stream,
                  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                    return Text(
                      snapshot.data != null ? snapshot.data! : '',
                      style: const TextStyle(color: Colors.white),
                    );
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

更多关于Flutter文字识别插件focused_area_ocr_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文字识别插件focused_area_ocr_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用 focused_area_ocr_flutter 插件的一个基本示例。这个插件允许你进行局部区域的OCR(光学字符识别)。

步骤1:添加依赖

首先,在你的 pubspec.yaml 文件中添加 focused_area_ocr_flutter 依赖:

dependencies:
  flutter:
    sdk: flutter
  focused_area_ocr_flutter: ^最新版本号  # 请替换为实际发布的最新版本号

步骤2:运行 Flutter pub get

在终端中运行以下命令以获取依赖项:

flutter pub get

步骤3:配置 Android 权限

由于OCR功能通常需要使用相机,因此你需要在 android/app/src/main/AndroidManifest.xml 文件中添加相机权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- 其他配置 -->

</manifest>

步骤4:编写 Flutter 代码

在你的 Dart 文件中,你可以按照以下示例来使用 focused_area_ocr_flutter 插件:

import 'package:flutter/material.dart';
import 'package:focused_area_ocr_flutter/focused_area_ocr_flutter.dart';
import 'package:image_picker/image_picker.dart';  // 用于选择图像

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: OcrScreen(),
    );
  }
}

class OcrScreen extends StatefulWidget {
  @override
  _OcrScreenState createState() => _OcrScreenState();
}

class _OcrScreenState extends State<OcrScreen> {
  final ImagePicker _picker = ImagePicker();
  File? _imageFile;
  String _ocrResult = '';

  Future<void> _pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.camera);

    if (image != null && image.path != null) {
      setState(() {
        _imageFile = File(image.path!);
      });

      // 进行OCR识别
      _performOCR();
    }
  }

  Future<void> _performOCR() async {
    if (_imageFile == null) return;

    try {
      // 假设你有一个矩形区域需要识别,这里使用整个图像作为示例
      final Rect rect = Rect.fromLTWH(0, 0, _imageFile!.width!.toDouble(), _imageFile!.height!.toDouble());
      final String result = await FocusedAreaOcrFlutter.performOcr(
        imagePath: _imageFile!.path,
        rect: rect,
        language: 'eng',  // 识别语言,例如 'eng' 表示英语
      );

      setState(() {
        _ocrResult = result;
      });
    } catch (e) {
      print('OCR Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OCR Demo'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _imageFile == null
              ? Text('No image selected.')
              : Image.file(_imageFile!),
          SizedBox(height: 20),
          Text('OCR Result:'),
          Text(_ocrResult, style: TextStyle(fontSize: 18)),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: _pickImage,
            child: Text('Pick Image from Camera'),
          ),
        ],
      ),
    );
  }
}

注意事项

  1. 依赖项:示例代码中使用了 image_picker 插件来选择图像。确保你已经在 pubspec.yaml 中添加了 image_picker 依赖,并运行 flutter pub get
  2. 权限处理:在实际应用中,你可能需要在运行时请求相机和存储权限。可以使用 permission_handler 插件来处理这些权限请求。
  3. 错误处理:示例代码中的错误处理非常简单。在实际应用中,你可能需要更复杂的错误处理逻辑。

通过以上步骤,你应该能够在Flutter应用中成功集成并使用 focused_area_ocr_flutter 插件进行局部区域的OCR识别。

回到顶部