简体   繁体   English

ImageAnalysis 用例 CameraX 人脸检测

[英]ImageAnalysis usecase CameraX Facedetection

I'm trying to develop an app that analyzes the live frames of the camera using CameraX and the MLKit Facedetecion API .我正在尝试开发一个应用程序,使用CameraXMLKit Facedetecion API分析相机的实时帧。 It works fine in the preview use-case, but the image analysis use case doesn't work at all.它在预览用例中工作正常,但图像分析用例根本不起作用。

I don't understand why because I'm following the latest official documentation.我不明白为什么,因为我正在关注最新的官方文档。 My code:我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    previewView = findViewById(R.id.previewView);
    if (previewView == null) {
        Toast.makeText(this,
            "PreviewView not found",
            Toast.LENGTH_SHORT).show();
    }
    iv = findViewById(R.id.face_image_view);
    if (iv == null) {
        Toast.makeText(this,
            "ImageView not found",
            Toast.LENGTH_SHORT).show();
    }

    cameraProviderFuture = ProcessCameraProvider.getInstance(this);

    cameraProviderFuture.addListener(() - > {
        try {
            ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
            if (allPermissionsGranted()) {
                bindPreview(cameraProvider);
                Log.i(TAG, "here1");
            } else {
                ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSION);
            }


        } 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) {
    cameraProvider.unbindAll();

    //bind preview
    Preview preview = new Preview.Builder()
        .build();

    CameraSelector cameraSelector = new CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
        .build();

    preview.setSurfaceProvider(previewView.getSurfaceProvider());

    //bind image analysis
    ImageAnalysis imageAnalysis =
        new ImageAnalysis.Builder()
        .setTargetResolution(new Size(previewView.getWidth(), previewView.getHeight()))
        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
        .build();

    imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
        @Override
        public void analyze(@NonNull ImageProxy imageProxy) {

            int rotationDegrees = imageProxy.getImageInfo().getRotationDegrees();

            Log.i(TAG, "here analyzer");
            @SuppressLint("UnsafeOptInUsageError") Image mediaImage = imageProxy.getImage();
            if (mediaImage != null) {
                InputImage image =
                    InputImage.fromMediaImage(mediaImage, rotationDegrees);

                initDrawingUtils(image);

                //START configuration of the facedetector
                FaceDetectorOptions realTimeOpts =
                    new FaceDetectorOptions.Builder()
                    .setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)
                    .build();

                FaceDetector detector = FaceDetection.getClient(realTimeOpts);
                //END of configuration of face detector

                // START detector
                detector.process(image)
                    .addOnSuccessListener(
                        new OnSuccessListener < List < Face >> () {
                            @Override
                            public void onSuccess(List < Face > faces) {
                                if (!faces.isEmpty()) {
                                    //Get information about detected faces
                                    processFaces(faces);
                                } else {
                                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY);
                                    Log.i(TAG, "vuoto");
                                }
                            }
                        })
                    .addOnFailureListener(
                        e - > {
                            e.printStackTrace();
                        });
            }
        }
    });

    Log.i(TAG, "here4");

    //add preview and analysis to the lifecycle
    cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageAnalysis);

    Log.i(TAG, "here5");
}

the code never reaches the analyzer and so doesn't process the live frames.代码永远不会到达分析器,因此不会处理实时帧。 Could someone help me please?有人可以帮我吗?

Not sure if that's the main issue but it looks like you forgot to close your ImageProxy after you processed the image.不确定这是否是主要问题,但看起来您在处理图像后忘记关闭 ImageProxy。 Try to add this listener to the value returned from the process method:尝试将此侦听器添加到从process方法返回的值中:

.addOnCompleteListener(task -> imageProxy.close());

From the documentation:从文档中:

If you are using the CameraX API, make sure to close the ImageProxy when finish using it, eg, by adding an OnCompleteListener to the Task returned from the process method.如果您使用的是CameraX API,请确保在使用完毕后关闭ImageProxy,例如,通过将OnCompleteListener 添加到从process 方法返回的Task 中。 See the VisionProcessorBase class in the quickstart sample app for an example.有关示例,请参阅快速入门示例应用程序中的 VisionProcessorBase class。

Little late answer, anyway I've encountered and solved the same problem today.迟到的答案,无论如何我今天遇到并解决了同样的问题。

You should call the ImageProxy.close() at the end of the analyze method, this will allow for the next image to be delivered for analysis:您应该在analyze方法结束时调用ImageProxy.close() ,这将允许传送下一张图像进行分析:

imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
    @Override
    public void analyze(@NonNull ImageProxy imageProxy) {
        int rotationDegrees = imageProxy.getImageInfo().getRotationDegrees();

        @SuppressLint("UnsafeOptInUsageError") 
        Image mediaImage = imageProxy.getImage();
        if (mediaImage != null) {
            ...
        }

        imageProxy.close() // <-- Add this line
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM