颤振-如何为OCR ML视觉结果提供页边距/填充?

时间:2019-02-21 03:33:19

标签: dart flutter widget

我正在使用此firebase_ml_vision插件处理Flutter ML Vision。

我希望扫描结果和照片有空白和黑色背景,如下所示: result scan i want

扫描后我当前应用程序的以下显示: current scan

请参阅下面的代码:

main.dart

void main() => runApp(MaterialApp(home: _MyHomePage()));

class _MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<_MyHomePage> {
  File _imageFile;
  // Size _imageSize;
  // dynamic _scanResults;
  // Detector _currentDetector = Detector.text;

  Future<void> _getAndScanImage() async {
    // setState(() {
    //   _imageFile = null;
    //   _imageSize = null;
    // });

    try {
      final File imageFile =
          await ImagePicker.pickImage(source: ImageSource.camera);

      if (imageFile == null) {
        // _getImageSize(imageFile);
        // _scanImage(imageFile);
        throw Exception('File is not available');
      }

      Navigator.push(
        context,
        new MaterialPageRoute(builder: (context) => DetailPage(imageFile)),
      );

      setState(() {
        _imageFile = imageFile;
      });
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ML Vision Example'),
      ),
      body: _imageFile == null
          ? const Center(child: Text('No image selected.'))
          : Container(),
      floatingActionButton: FloatingActionButton(
        onPressed: _getAndScanImage,
        tooltip: 'Pick Image',
        child: const Icon(Icons.add_a_photo),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}

detector_painter.dart

// Paints rectangles around all the text in the image.
class TextDetectorPainter extends CustomPainter {
  TextDetectorPainter(this.absoluteImageSize, this.visionText);

  final Size absoluteImageSize;
  final VisionText visionText;

  @override
  void paint(Canvas canvas, Size size) {
    final double scaleX = size.width / absoluteImageSize.width;
    final double scaleY = size.height / absoluteImageSize.height;

    Rect scaleRect(TextContainer container) {
      return Rect.fromLTRB(
        container.boundingBox.left * scaleX,
        container.boundingBox.top * scaleY,
        container.boundingBox.right * scaleX,
        container.boundingBox.bottom * scaleY,
      );
    }

    final Paint paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    for (TextBlock block in visionText.blocks) {
      print(block.text.toString());
      for (TextLine line in block.lines) {
        for (TextElement element in line.elements) {
          paint.color = Colors.green;
          canvas.drawRect(scaleRect(element), paint);
        }

        paint.color = Colors.yellow;
        canvas.drawRect(scaleRect(line), paint);
      }

      paint.color = Colors.red;
      canvas.drawRect(scaleRect(block), paint);
    }
  }

  @override
  bool shouldRepaint(TextDetectorPainter oldDelegate) {
    return oldDelegate.absoluteImageSize != absoluteImageSize ||
        oldDelegate.visionText != visionText;
  }
}

detail_page.dart 这是我的详细信息页面。

class DetailPage extends StatefulWidget {
  final File imageFile;
  // final Size imageSize;
  // final dynamic results;

  DetailPage(this.imageFile);

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  // File _imageFile;
  Size _imageSize;
  dynamic _scanResults;

  @override
  void initState() {
    super.initState();

    Timer(Duration(milliseconds: 1000), () {
      this._scanImage();
    });
  }

  Future<void> _scanImage() async {
    setState(() {
      _scanResults = null;
    });

    final FirebaseVisionImage visionImage =
        FirebaseVisionImage.fromFile(widget.imageFile);

    dynamic results;

    final TextRecognizer recognizer = FirebaseVision.instance.textRecognizer();
    results = await recognizer.processImage(visionImage);

    _getImageSize(Image.file(widget.imageFile, fit: BoxFit.fill));

    setState(() {
      _scanResults = results;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Details"),
        ),
        bottomSheet: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                height: 50,
                child: RaisedButton.icon(
                  clipBehavior: Clip.none,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(0))
                  ),
                icon: Icon(Icons.close, color: Colors.white,),
                label: Text("CANCEL", style: TextStyle(
                  color: Colors.white
                ),),
                onPressed: () {},
                color: Colors.blue,
              ),
            )),
            Expanded(
              child: Container(
                height: 50,
                child: RaisedButton.icon(

                  clipBehavior: Clip.none,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(0))
                  ),
                icon: Icon(Icons.check, color: Colors.white),
                label: Text("SAVE", style: TextStyle(
                  color: Colors.white
                )),
                onPressed: () {},
                color: Colors.blue,
              ),
            )),
          ],
        ),
        body: _buildImage());
  }

  Future<void> _getImageSize(Image imageFile) async {
    final Completer<Size> completer = Completer<Size>();
    imageFile.image.resolve(const ImageConfiguration()).addListener(
      (ImageInfo info, bool _) {
        completer.complete(Size(
          info.image.width.toDouble(),
          info.image.height.toDouble(),
        ));
      },
    );

    final Size imageSize = await completer.future;
    setState(() {
      _imageSize = imageSize;
    });
  }

  CustomPaint _buildResults(Size imageSize, dynamic results) {
    return CustomPaint(
      painter: TextDetectorPainter(_imageSize, results),
    );
  }

  Widget _buildImage() {
    return _imageSize == null || _scanResults == null
        ? const Center(child: CircularProgressIndicator())
        : Container(
            constraints: const BoxConstraints.expand(),
            decoration: BoxDecoration(
              // color: Colors.black,
              image: DecorationImage(
                  image: Image.file(
                    widget.imageFile,
                    fit: BoxFit.fill,
                  ).image,
                  fit: BoxFit.fill),
            ),
            child: _buildResults(_imageSize, _scanResults),
          );
  }
}

如何解决?

0 个答案:

没有答案