ML Kit 条形码扫描器有时会拾取错误的扫描
ML Kit Barcode scanner picks up wrong scans sometimes
我正在尝试使用 ML Kit 和 CameraX 制作条码扫描仪。我的程序偶尔会进行错误的扫描,我已经从 google play 下载了几个使用 ML Kit 的应用程序,它们也有同样的问题,我也在其他手机上测试过。另一方面,我从 Github 中提取的 ML Kit 快速启动应用程序工作正常,所以它必须是我的代码。谁能帮我找到问题所在?
我无法上传 img 但您可以使用在线条形码生成器(代码 128)并为 PAN/230954 创建条形码我的应用程序将读取为 PAN/2
30954☒。这是条形码
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.AspectRatio;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.mlkit.vision.barcode.Barcode;
import com.google.mlkit.vision.barcode.BarcodeScanner;
import com.google.mlkit.vision.barcode.BarcodeScannerOptions;
import com.google.mlkit.vision.barcode.BarcodeScanning;
import com.google.mlkit.vision.common.InputImage;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
private static final String[] CAMERA_PERMISSION = new String[]{Manifest.permission.CAMERA};
private static final int CAMERA_REQUEST_CODE = 10;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
PreviewView previewView;
ImageAnalysis imageAnalysis;
ProcessCameraProvider cameraProvider;
String barcodeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView = findViewById(R.id.previewView);
if (!hasCameraPermission()) {
requestPermission();
}
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
}
}, ContextCompat.getMainExecutor(this));
}
void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
Preview preview = new Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_4_3)
.build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
imageAnalysis =
new ImageAnalysis.Builder()
//.setTargetAspectRatio(AspectRatio.RATIO_4_3)
//.setTargetResolution(new Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)//keep the latest
//to prevent bottleneck
.build();
BarcodeScannerOptions barcodeScannerOptions = new BarcodeScannerOptions.Builder()
.setBarcodeFormats(// input all desired code formats to be scanned
Barcode.FORMAT_CODE_128
//Barcode.FORMAT_CODE_39
).build();
BarcodeScanner scanner = BarcodeScanning.getClient(barcodeScannerOptions);
imageAnalysis.setAnalyzer(Executors.newSingleThreadExecutor(), new ImageAnalysis.Analyzer() {
@Override
public void analyze(@NonNull ImageProxy imageProxy) {
@SuppressLint({"UnsafeExperimentalUsageError", "UnsafeOptInUsageError"}) Image mediaImage = imageProxy.getImage();
if (mediaImage != null) {
InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
Task<List<Barcode>> result = scanner.process(image);// get a list of barcode
result.addOnSuccessListener(new OnSuccessListener<List<Barcode>>() {
@Override
public void onSuccess(List<Barcode> barcodes) {
processBarcode(barcodes);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Could not detect barcode!", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<List<Barcode>>() {
@Override
public void onComplete(@NonNull Task<List<Barcode>> task) {
mediaImage.close();
imageProxy.close();
}
});
}
}
});
cameraProvider.unbindAll();
// Toast.makeText(this, String.valueOf(cameraProviderFuture.isDone()), Toast.LENGTH_SHORT).show();
cameraProvider.bindToLifecycle(this, cameraSelector, imageAnalysis, preview);
// Toast.makeText(this, String.valueOf(cameraProviderFuture.isDone()), Toast.LENGTH_SHORT).show();
}
private void processBarcode(List<Barcode> barcodes){
Log.e("barcodes:",String.valueOf(barcodes));
for(Barcode barcode: barcodes){
barcodeText=barcode.getRawValue();
Toast.makeText(getApplicationContext(),barcodeText,Toast.LENGTH_SHORT).show();
}
}
/////handle camera permission////////////
private boolean hasCameraPermission() {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(
this,
CAMERA_PERMISSION,
CAMERA_REQUEST_CODE
);
}
//////////////////////
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="415dp"
android:layout_height="587dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="588dp">
</androidx.camera.view.PreviewView>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
build.grade(应用程序)
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.sunrise.barcodescantest"
minSdkVersion 26
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
def camerax_version = "1.1.0-alpha08"
// The following line is optional, as the core library is included indirectly by camera-camera2
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
// If you want to additionally use the CameraX Lifecycle library
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
// If you want to additionally use the CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha28"
// If you want to additionally use the CameraX Extensions library
implementation "androidx.camera:camera-extensions:1.0.0-alpha28"
//BUNDLED MODE ML KIT
implementation 'com.google.mlkit:barcode-scanning:17.0.0'
//Apache common library
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sunrise.barcodescantest">
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BarcodeScanTest">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
我发现了问题。我使用了 barcode.getRawValue() ,其中 return 是原始值。对于我尝试扫描的条码,校验和为 29,因此原始值是条码文本 + acii 代码为 29 的字符。所以我使用 barcode.getDisplayValue() 代替
我正在尝试使用 ML Kit 和 CameraX 制作条码扫描仪。我的程序偶尔会进行错误的扫描,我已经从 google play 下载了几个使用 ML Kit 的应用程序,它们也有同样的问题,我也在其他手机上测试过。另一方面,我从 Github 中提取的 ML Kit 快速启动应用程序工作正常,所以它必须是我的代码。谁能帮我找到问题所在? 我无法上传 img 但您可以使用在线条形码生成器(代码 128)并为 PAN/230954 创建条形码我的应用程序将读取为 PAN/2 30954☒。这是条形码
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.AspectRatio;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.mlkit.vision.barcode.Barcode;
import com.google.mlkit.vision.barcode.BarcodeScanner;
import com.google.mlkit.vision.barcode.BarcodeScannerOptions;
import com.google.mlkit.vision.barcode.BarcodeScanning;
import com.google.mlkit.vision.common.InputImage;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
private static final String[] CAMERA_PERMISSION = new String[]{Manifest.permission.CAMERA};
private static final int CAMERA_REQUEST_CODE = 10;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
PreviewView previewView;
ImageAnalysis imageAnalysis;
ProcessCameraProvider cameraProvider;
String barcodeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView = findViewById(R.id.previewView);
if (!hasCameraPermission()) {
requestPermission();
}
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
}
}, ContextCompat.getMainExecutor(this));
}
void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
Preview preview = new Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_4_3)
.build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
imageAnalysis =
new ImageAnalysis.Builder()
//.setTargetAspectRatio(AspectRatio.RATIO_4_3)
//.setTargetResolution(new Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)//keep the latest
//to prevent bottleneck
.build();
BarcodeScannerOptions barcodeScannerOptions = new BarcodeScannerOptions.Builder()
.setBarcodeFormats(// input all desired code formats to be scanned
Barcode.FORMAT_CODE_128
//Barcode.FORMAT_CODE_39
).build();
BarcodeScanner scanner = BarcodeScanning.getClient(barcodeScannerOptions);
imageAnalysis.setAnalyzer(Executors.newSingleThreadExecutor(), new ImageAnalysis.Analyzer() {
@Override
public void analyze(@NonNull ImageProxy imageProxy) {
@SuppressLint({"UnsafeExperimentalUsageError", "UnsafeOptInUsageError"}) Image mediaImage = imageProxy.getImage();
if (mediaImage != null) {
InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
Task<List<Barcode>> result = scanner.process(image);// get a list of barcode
result.addOnSuccessListener(new OnSuccessListener<List<Barcode>>() {
@Override
public void onSuccess(List<Barcode> barcodes) {
processBarcode(barcodes);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Could not detect barcode!", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<List<Barcode>>() {
@Override
public void onComplete(@NonNull Task<List<Barcode>> task) {
mediaImage.close();
imageProxy.close();
}
});
}
}
});
cameraProvider.unbindAll();
// Toast.makeText(this, String.valueOf(cameraProviderFuture.isDone()), Toast.LENGTH_SHORT).show();
cameraProvider.bindToLifecycle(this, cameraSelector, imageAnalysis, preview);
// Toast.makeText(this, String.valueOf(cameraProviderFuture.isDone()), Toast.LENGTH_SHORT).show();
}
private void processBarcode(List<Barcode> barcodes){
Log.e("barcodes:",String.valueOf(barcodes));
for(Barcode barcode: barcodes){
barcodeText=barcode.getRawValue();
Toast.makeText(getApplicationContext(),barcodeText,Toast.LENGTH_SHORT).show();
}
}
/////handle camera permission////////////
private boolean hasCameraPermission() {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(
this,
CAMERA_PERMISSION,
CAMERA_REQUEST_CODE
);
}
//////////////////////
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="415dp"
android:layout_height="587dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="588dp">
</androidx.camera.view.PreviewView>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
build.grade(应用程序)
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.sunrise.barcodescantest"
minSdkVersion 26
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
def camerax_version = "1.1.0-alpha08"
// The following line is optional, as the core library is included indirectly by camera-camera2
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
// If you want to additionally use the CameraX Lifecycle library
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
// If you want to additionally use the CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha28"
// If you want to additionally use the CameraX Extensions library
implementation "androidx.camera:camera-extensions:1.0.0-alpha28"
//BUNDLED MODE ML KIT
implementation 'com.google.mlkit:barcode-scanning:17.0.0'
//Apache common library
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sunrise.barcodescantest">
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BarcodeScanTest">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
我发现了问题。我使用了 barcode.getRawValue() ,其中 return 是原始值。对于我尝试扫描的条码,校验和为 29,因此原始值是条码文本 + acii 代码为 29 的字符。所以我使用 barcode.getDisplayValue() 代替