🐛 [firebase_ml_vision] Non-existent barcode is detected
Bug report
Describe the bug As soon as I launch the app, the camera detects an unexistent code.
Steps to reproduce
Steps to reproduce the behavior:
- Create a flutter application with firebase_ml_vision version 0.10.0
- Use plugin camera version ^0.7.0+1 to scan images
- Expect the plugin to capture barcodes
Expected behavior
Unless a real barcode is scanned, no barcodes are detected. But an unexistent barcode is detected, no mather where the camera is pointing.
Additional context
The scanned barcode is of type text, is always a JSON similar to this:
{"typeNumber": "0", "errorCode": "3", "version": "242"}
Flutter doctor
Run flutter doctor and paste the output below:
Click To Expand
[✓] Flutter (Channel stable, 1.22.6, on Linux, locale en_US.UTF-8)
• Flutter version 1.22.6 at /home/svprdga/opt/flutter
• Framework revision 9b2d32b605 (12 days ago), 2021-01-22 14:36:39 -0800
• Engine revision 2f0af37152
• Dart version 2.10.5
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
• Android SDK at /home/svprdga/Android/Sdk
• Platform android-30, build-tools 30.0.2
• Java binary at: /usr/bin/java
• Java version OpenJDK Runtime Environment (build
11.0.9.1+1-Ubuntu-0ubuntu1.20.04)
• All Android licenses accepted.
[!] Android Studio (not installed)
• Android Studio not found; download from
https://developer.android.com/studio/index.html
(or visit https://flutter.dev/docs/get-started/install/linux#android-setup
for detailed instructions).
[✓] VS Code (version 1.52.1)
• VS Code at /usr/share/code
• Flutter extension version 3.19.0
[!] Connected device
! No devices available
! Doctor found issues in 2 categories.
Flutter dependencies
Run flutter pub deps -- --style=compact and paste the output below:
Click To Expand
PASTE OUTPUT INSIDE HERE
Hi @svprdga Could you please provide a minimal complete reproducible code sample? Thank you
Hi @markusaksli-nc.
Find the sample code below, please make sure to run it with camera permissions granted:
import 'dart:typed_data';
import 'package:camera/camera.dart';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(SampleApp());
}
class SampleApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ScannerScreen(),
);
}
}
class ScannerScreen extends StatefulWidget {
ScannerScreen({Key key}) : super(key: key);
@override
_ScannerScreenState createState() => _ScannerScreenState();
}
class _ScannerScreenState extends State<ScannerScreen>
with WidgetsBindingObserver {
CameraController _cameraController;
bool _isDetecting = false;
final BarcodeDetector _barcodeDetector =
FirebaseVision.instance.barcodeDetector();
ScannerUtils _scannerUtils = ScannerUtils();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Camera lifecycle.
if (state == AppLifecycleState.inactive) {
_stopCamera();
} else if (state == AppLifecycleState.resumed &&
_cameraController != null &&
_cameraController.value.isInitialized) {
_startCamera();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<CameraDescription>>(
future: availableCameras(),
builder: (BuildContext context,
AsyncSnapshot<List<CameraDescription>> snapshot) {
Widget body;
if (snapshot.hasData) {
_initCameraController(snapshot.data);
body = _cameraController.value.isInitialized
? Container(
color: Colors.white,
child: Center(
child: CameraPreview(_cameraController),
),
)
: Container();
} else {
body = CircularProgressIndicator();
}
return body;
},
),
);
}
_startCamera() {
_cameraSelected(_cameraController.description);
_isDetecting = false;
}
_stopCamera() {
_cameraController.dispose();
}
_initCameraController(List<CameraDescription> cameras) {
// Select the first rear camera.
CameraDescription camera;
for (var i = 0; i < cameras.length; i++) {
CameraDescription current = cameras[i];
if (current.lensDirection == CameraLensDirection.back) {
camera = current;
break;
}
}
if (_cameraController == null) {
_cameraSelected(camera);
}
}
_cameraSelected(CameraDescription camera) async {
_cameraController =
CameraController(camera, ResolutionPreset.medium, enableAudio: false);
await _cameraController.initialize();
if (!mounted) {
return;
}
setState(() {});
_cameraController.startImageStream((CameraImage image) {
_processFrame(camera, image);
});
}
_processFrame(CameraDescription camera, CameraImage image) async {
if (_isDetecting) {
return;
} else {
_isDetecting = true;
}
try {
FirebaseVisionImage resultImage =
_scannerUtils.createVisionImage(image, camera.sensorOrientation);
final List<Barcode> barcodes =
await _barcodeDetector.detectInImage(resultImage);
_processBarcodes(barcodes);
} catch (e) {
print('Error processing camera frame: $e');
_isDetecting = false;
}
}
_processBarcodes(List<Barcode> barcodes) async {
Barcode barcode;
if (barcodes.isNotEmpty) {
barcode = barcodes.first;
print(' ');
print('*********');
print('Code scanned: ${barcode.rawValue}');
print('*********');
print(' ');
}
_isDetecting = false;
}
}
class ScannerUtils {
//***************************** PUBLIC METHODS *************************** //
FirebaseVisionImage createVisionImage(
CameraImage image,
int imageRotation,
) {
return FirebaseVisionImage.fromBytes(
_concatenatePlanes(image.planes),
_buildMetaData(image, _rotationIntToImageRotation(imageRotation)),
);
}
// *************************** PRIVATE METHODS *************************** //
Uint8List _concatenatePlanes(List<Plane> planes) {
final WriteBuffer allBytes = WriteBuffer();
for (Plane plane in planes) {
allBytes.putUint8List(plane.bytes);
}
return allBytes.done().buffer.asUint8List();
}
FirebaseVisionImageMetadata _buildMetaData(
CameraImage image,
ImageRotation rotation,
) {
return FirebaseVisionImageMetadata(
rawFormat: image.format.raw,
size: Size(image.width.toDouble(), image.height.toDouble()),
rotation: rotation,
planeData: image.planes.map(
(Plane plane) {
return FirebaseVisionImagePlaneMetadata(
bytesPerRow: plane.bytesPerRow,
height: plane.height,
width: plane.width,
);
},
).toList(),
);
}
static ImageRotation _rotationIntToImageRotation(int rotation) {
switch (rotation) {
case 0:
return ImageRotation.rotation0;
case 90:
return ImageRotation.rotation90;
case 180:
return ImageRotation.rotation180;
default:
assert(rotation == 270);
return ImageRotation.rotation270;
}
}
}
Thanks, seeing this as well on the latest master 1.26.0-18.0.pre.210 with firebase_ml_vision: ^0.10.0
flutter doctor -v
[√] Flutter (Channel master, 1.26.0-18.0.pre.210, on Microsoft Windows [Version 10.0.19041.746], locale et-EE)
• Flutter version 1.26.0-18.0.pre.210 at C:\Development\flutter_master
• Framework revision a77388e670 (4 hours ago), 2021-02-04 22:51:04 -0800
• Engine revision b04955656c
• Dart version 2.13.0 (build 2.13.0-0.0.dev)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
• Android SDK at C:\Users\marku\AppData\Local\Android\sdk
• Platform android-30, build-tools 30.0.2
• Java binary at: C:\Users\marku\AppData\Local\JetBrains\Toolbox\apps\AndroidStudio\ch-0\201.7042882\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe
[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.7.7)
• Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\Community
• Visual Studio Community 2019 version 16.7.30621.155
• Windows 10 SDK version 10.0.18362.0
[√] Android Studio (version 4.1.0)
• Android Studio at C:\Users\marku\AppData\Local\JetBrains\Toolbox\apps\AndroidStudio\ch-0\201.7042882
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
[√] Connected device (4 available)
• SM G950F (mobile) • ce12171c51cc001c03 • android-arm64 • Android 9 (API 28)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19041.746]
• Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.104
• Edge (web) • edge • web-javascript • Microsoft Edge 88.0.705.56
• No issues found!
{"typeNumber": "0", "errorCode": "3", "version": "240"}
This was somewhat tracked in https://github.com/FirebaseExtended/flutterfire/issues/3665 before but this is now detecting it on non-existent barcodes.
For me
{"typeNumber": "0", "errorCode": "3", "version": "213"} when using 0.9.10 {"typeNumber": "0", "errorCode": "3", "version": "83"} when using 0.10.0
the barcode format value is always -1
This happens if using barcode format all on an android device
try wih ResolutionPreset.high
Hey, :wave:, the firebase_ml_vision package is now discontinued since its APIs have been deprecated and removed from the Android & iOS Firebase SDKs.
I'd recommend switching to the alternatives now;
- for on-device vision APIs; switch to Google's standalone ML Kit library via google_ml_kit
- for cloud vision APIs; the recommended approach now is to use Firebase Authentication and Functions, which gives you a managed, serverless gateway to the Google Cloud Vision APIs. For an example Functions project see the vision-annotate-images sample project. You'd deploy this project for example and then call the cloud function from your app with your image data to get the annotation result.
Apologies for any inconvenience here and best of luck switching over the the new APIs. firebase_ml_custom is not affected by this deprecation.
Thanks