Android camera2.params.face rectangle placement on canvas

后端 未结 1 1052
清歌不尽
清歌不尽 2021-02-09 18:15

I\'m trying to implement face detection in my camera preview. I followed the Android reference pages to implement a custom camera preview in a TextureView, placed i

1条回答
  •  孤街浪徒
    2021-02-09 18:57

    For future reference, this is the solution I ended up with:

    set a class/Activity variable called orientation_offset :

    orientation_offset = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    

    This is the angle that the camera sensor's view (or rectangle for face detection) needs to be rotated to be viewed correctly.

    Then, I changed onSurfaceTextureUpdated() :

    Canvas currentCanvas = rectangleView.getHolder().lockCanvas();
        if (currentCanvas != null) {
    
            currentCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
    
            if (detectedFace != null && rectangleFace.height() > 0) {
    
                int canvasWidth = currentCanvas.getWidth();
                int canvasHeight = currentCanvas.getHeight();
                int faceWidthOffset = rectangleFace.width()/8;
                int faceHeightOffset = rectangleFace.height()/8;
    
                currentCanvas.save();
                currentCanvas.rotate(360 - orientation_offset, canvasWidth / 2, 
                    canvasHeight / 2);
    
                int l = rectangleFace.right;
                int t = rectangleFace.bottom;
                int r = rectangleFace.left;
                int b = rectangleFace.top;
                int left = (canvasWidth - (canvasWidth*l)/cameraWidth)-(faceWidthOffset);
                int top  = (canvasHeight*t)/cameraHeight - (faceHeightOffset);
                int right = (canvasWidth - (canvasWidth*r)/cameraWidth) + (faceWidthOffset);
                int bottom = (canvasHeight*b)/cameraHeight + (faceHeightOffset);
    
                currentCanvas.drawRect(left, top, right, bottom, purplePaint);
                currentCanvas.restore();
            }
        }
        rectangleView.getHolder().unlockCanvasAndPost(currentCanvas);
    

    I'll leave the question open in case somebody else has a solution to offer.

    0 讨论(0)
提交回复
热议问题