Rotate camera preview to Portrait Android OpenCV Camera

前端 未结 17 1595
日久生厌
日久生厌 2020-12-07 15:45

I am trying to use OpenCV 2.4.3.2 to create a camera app and do some opencv processing. I would like it to be able to have multiple UI orientations, not just Landscape.

17条回答
  •  我在风中等你
    2020-12-07 16:32

    As in other answers, I've written my personal version of deliverAndDrawFrame (I've also notified through comments where my code starts and ends):

    protected void deliverAndDrawFrame(CvCameraViewFrame frame) {
        Mat modified;
    
        if (mListener != null) {
            modified = mListener.onCameraFrame(frame);
        } else {
            modified = frame.rgba();
        }
    
        boolean bmpValid = true;
        if (modified != null) {
            try {
                Utils.matToBitmap(modified, mCacheBitmap);
            } catch(Exception e) {
                Log.e(TAG, "Mat type: " + modified);
                Log.e(TAG, "Bitmap type: " + mCacheBitmap.getWidth() + "*" + mCacheBitmap.getHeight());
                Log.e(TAG, "Utils.matToBitmap() throws an exception: " + e.getMessage());
                bmpValid = false;
            }
        }
    
        if (bmpValid && mCacheBitmap != null) {
            Canvas canvas = getHolder().lockCanvas();
            if (canvas != null) {
                canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "mStretch value: " + mScale);
                }
    
                // Start of the fix
                Matrix matrix = new Matrix();
                matrix.preTranslate( ( canvas.getWidth() - mCacheBitmap.getWidth() ) / 2f, ( canvas.getHeight() - mCacheBitmap.getHeight() ) / 2f );
                matrix.postRotate( 90f, ( canvas.getWidth()) / 2f, canvas.getHeight() / 2f );
                float scale = (float) canvas.getWidth() / (float) mCacheBitmap.getHeight();
                matrix.postScale(scale, scale, canvas.getWidth() / 2f , canvas.getHeight() / 2f );
                canvas.drawBitmap( mCacheBitmap, matrix, null );
    
                // Back to original OpenCV code
                if (mFpsMeter != null) {
                    mFpsMeter.measure();
                    mFpsMeter.draw(canvas, 20, 30);
                }
    
                getHolder().unlockCanvasAndPost(canvas);
            }
        }
    
    }
    

    Preview is now in Portrait mode, as you can see:

提交回复
热议问题