为TextureView裁剪相机预览

28

我有一个宽高固定的TextureView,想在里面展示相机预览。为了让相机预览不会在TextureView里被拉伸,我需要对其进行裁剪。如何进行裁剪?如果需要使用OpenGL,如何将Surface Texture与OpenGL绑定,并使用OpenGL进行裁剪?

public class MyActivity extends Activity implements TextureView.SurfaceTextureListener 
{

   private Camera mCamera;
   private TextureView mTextureView;

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

    mTextureView = (TextureView) findViewById(R.id.camera_preview);
    mTextureView.setSurfaceTextureListener(this);
}

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
    mCamera = Camera.open();

    try 
    {
        mCamera.setPreviewTexture(surface);
        mCamera.startPreview();
    } catch (IOException ioe) {
        // Something bad happened
    }
}

@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
    mCamera.stopPreview();
    mCamera.release();
    return true;
}

@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}

@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface)
 {
    // Invoked every time there's a new Camera preview frame
 }
}

另外,在正确预览后,我需要能够实时读取裁剪图像中心发现的像素。


我不确定这会不会对你有帮助,但你可以尝试使用较小的预览尺寸。初始情况下,相机提供默认的较大预览尺寸。 - Amrendra
1
我知道预览尺寸。但这对我没有帮助,因为显示相机预览的视图尺寸与可用的预览尺寸不同。 - Catalin Morosan
你可以在屏幕上尝试使用片段。 - Amrendra
1
好的,为了获得最佳预览尺寸,我同意 @Amrendra 的建议,通过进行一些数学计算来获取最接近视图大小的预览尺寸。我认为那是你可以实现的最接近的东西。 - Diogo Bento
有些设备提供的预览尺寸非常少,而且没有一个尺寸非常接近我需要的尺寸。因此这不是一个选择。 - Catalin Morosan
如果您不想处理图像,可以将TextureView放置在LinearLayout中,并向您的TextureView添加layout_gravity ="center"或center_vertically。更多信息请参见:https://dev59.com/pWMl5IYBdhLWcg3w3aPj - bh_earth0
6个回答

35

之前由@Romanski提供的解决方案可以正常工作,但它会随着裁剪而缩放。如果您需要按比例缩放,则使用以下解决方案。每当表面视图更改时调用updateTextureMatrix:即在onSurfaceTextureAvailable和onSurfaceTextureSizeChanged方法中调用。还请注意,此解决方案依赖于活动忽略配置更改(即android:configChanges="orientation|screenSize|keyboardHidden"或类似内容):

private void updateTextureMatrix(int width, int height)
{
    boolean isPortrait = false;

    Display display = getWindowManager().getDefaultDisplay();
    if (display.getRotation() == Surface.ROTATION_0 || display.getRotation() == Surface.ROTATION_180) isPortrait = true;
    else if (display.getRotation() == Surface.ROTATION_90 || display.getRotation() == Surface.ROTATION_270) isPortrait = false;

    int previewWidth = orgPreviewWidth;
    int previewHeight = orgPreviewHeight;

    if (isPortrait)
    {
        previewWidth = orgPreviewHeight;
        previewHeight = orgPreviewWidth;
    }

    float ratioSurface = (float) width / height;
    float ratioPreview = (float) previewWidth / previewHeight;

    float scaleX;
    float scaleY;

    if (ratioSurface > ratioPreview)
    {
        scaleX = (float) height / previewHeight;
        scaleY = 1;
    }
    else
    {
        scaleX = 1;
        scaleY = (float) width / previewWidth;
    }

    Matrix matrix = new Matrix();

    matrix.setScale(scaleX, scaleY);
    textureView.setTransform(matrix);

    float scaledWidth = width * scaleX;
    float scaledHeight = height * scaleY;

    float dx = (width - scaledWidth) / 2;
    float dy = (height - scaledHeight) / 2;
    textureView.setTranslationX(dx);
    textureView.setTranslationY(dy);
}

您还需要以下字段:

private int orgPreviewWidth;
private int orgPreviewHeight;

在调用updateTextureMatrix方法之前,请在onSurfaceTextureAvailable方法中进行初始化:

Camera.Parameters parameters = camera.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);

Pair<Integer, Integer> size = getMaxSize(parameters.getSupportedPreviewSizes());
parameters.setPreviewSize(size.first, size.second);

orgPreviewWidth = size.first;
orgPreviewHeight = size.second;

camera.setParameters(parameters);

getMaxSize方法:

private static Pair<Integer, Integer> getMaxSize(List<Camera.Size> list)
{
    int width = 0;
    int height = 0;

    for (Camera.Size size : list) {
        if (size.width * size.height > width * height)
        {
            width = size.width;
            height = size.height;
        }
    }

    return new Pair<Integer, Integer>(width, height);
}

最后一件事 - 您需要纠正相机旋转。因此在Activity的onConfigurationChanged方法中调用setCameraDisplayOrientation方法(并且还要在onSurfaceTextureAvailable方法中进行初始调用):

而最后一件事-你需要校准照相机的旋转。所以在Activity的onConfigurationChanged方法中调用setCameraDisplayOrientation方法(同时也要在onSurfaceTextureAvailable方法中进行初始调用):

public static void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera)
{
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    int degrees = 0;
    switch (rotation)
    {
        case Surface.ROTATION_0:
            degrees = 0;
            break;
        case Surface.ROTATION_90:
            degrees = 90;
            break;
        case Surface.ROTATION_180:
            degrees = 180;
            break;
        case Surface.ROTATION_270:
            degrees = 270;
            break;
    }

    int result;
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
    {
        result = (info.orientation + degrees) % 360;
        result = (360 - result) % 360;  // compensate the mirror
    }
    else
    {  // back-facing
        result = (info.orientation - degrees + 360) % 360;
    }
    camera.setDisplayOrientation(result);

    Camera.Parameters params = camera.getParameters();
    params.setRotation(result);
    camera.setParameters(params);
}

编辑:这段代码存在一些逻辑问题,Romanski似乎已经解决了,我会尝试在找出问题所在后更新这个答案。 - Sam
嗨,感谢您发布的有用文章。这帮助我解决了一个问题,但之后又出现了另一个问题:在移动相机时,视图不流畅。似乎是糟糕的转换或类似的问题。您能帮忙吗?对于这种情况有什么想法吗? - Vardges
我对此有些困惑。我收到了“setParameters失败”的错误。我已经按照这个指南进行了操作,但我认为“并在onSurfaceTextureAvailable方法中进行初始调用”是我有点困惑的地方。这是否应该在我设置“Camera camera = Camera.open();”之前完成? - Jonas Borggren
上面的答案存在严重的逻辑问题。假设我们有一个720 * 720的视图,相机预览是1280 * 720。我得到了完全错误的缩放因子。 - user1154390
这个在 API 等级超过 20 的情况下还有效吗?我在 API 等级为 21 的 Android 设备上翻译时遇到了问题。 - Philippe Creytens
显示剩余2条评论

13
只需计算宽高比,生成缩放矩阵并将其应用于TextureView即可。基于表面的宽高比和预览图像的宽高比,预览图像会在顶部和底部或左侧和右侧进行裁剪。 我发现的另一个解决方案是,在SurfaceTexture可用之前打开相机,预览已经自动缩放。只需将mCamera = Camera.open();移动到您的onCreate函数中,在设置SurfaceTextureListener之后执行即可。这在N4上适用。如果需要支持纵向和横向,请使用缩放矩阵的解决方案!
private void initPreview(SurfaceTexture surface, int width, int height) {
    try {
        camera.setPreviewTexture(surface);
    } catch (Throwable t) {
        Log.e("CameraManager", "Exception in setPreviewTexture()", t);
    }

    Camera.Parameters parameters = camera.getParameters();
    previewSize = parameters.getSupportedPreviewSizes().get(0);

    float ratioSurface = width > height ? (float) width / height : (float) height / width;
    float ratioPreview = (float) previewSize.width / previewSize.height;

    int scaledHeight = 0;
    int scaledWidth = 0;
    float scaleX = 1f;
    float scaleY = 1f;

    boolean isPortrait = false;

    if (previewSize != null) {
        parameters.setPreviewSize(previewSize.width, previewSize.height);
        if (display.getRotation() == Surface.ROTATION_0 || display.getRotation() == Surface.ROTATION_180) {
            camera.setDisplayOrientation(display.getRotation() == Surface.ROTATION_0 ? 90 : 270);
            isPortrait = true;
        } else if (display.getRotation() == Surface.ROTATION_90 || display.getRotation() == Surface.ROTATION_270) {
            camera.setDisplayOrientation(display.getRotation() == Surface.ROTATION_90 ? 0 : 180);
            isPortrait = false;
        }
        if (isPortrait && ratioPreview > ratioSurface) {
            scaledWidth = width;
            scaledHeight = (int) (((float) previewSize.width / previewSize.height) * width);
            scaleX = 1f;
            scaleY = (float) scaledHeight / height;
        } else if (isPortrait && ratioPreview < ratioSurface) {
            scaledWidth = (int) (height / ((float) previewSize.width / previewSize.height));
            scaledHeight = height;
            scaleX = (float) scaledWidth / width;
            scaleY = 1f;
        } else if (!isPortrait && ratioPreview < ratioSurface) {
            scaledWidth = width;
            scaledHeight = (int) (width / ((float) previewSize.width / previewSize.height));
            scaleX = 1f;
            scaleY = (float) scaledHeight / height;
        } else if (!isPortrait && ratioPreview > ratioSurface) {
            scaledWidth = (int) (((float) previewSize.width / previewSize.height) * width);
            scaledHeight = height;
            scaleX = (float) scaledWidth / width;
            scaleY = 1f;
        }           
        camera.setParameters(parameters);
    }

    // calculate transformation matrix
    Matrix matrix = new Matrix();

    matrix.setScale(scaleX, scaleY);
    textureView.setTransform(matrix);
}

我无法将预览裁剪。您确定在TextureView中裁剪预览是可行的吗? - Catalin Morosan
这种方式对我来说是有效的。基本上它不是裁剪而是缩放。相机预览始终适合于TextureView内部 - 即使TextureView的比例和相机预览的比例不同。通过变换矩阵,您可以设置缩放以补偿失真。 - Romanski
我知道我来晚了,但是你如何适应Camera2 API的旋转呢?没有“setDisplayOrientation”。我正在尝试使用matrix.setRotate/postRotate/preRotate进行测试,但我从未得到期望的输出。 - Csharpest
在Camera2中,我使用另一种方法——使用setRectToRect(图像大小和表面大小)计算矩阵,然后根据当前显示位置,在矩阵上使用postScale/postRotate。很抱歉,我无法提供任何代码。 - Romanski

2

我刚刚制作了一个工作中需要展示预览的应用程序,需要以实际输入的两倍显示预览而不会出现像素化的外观。也就是说,我需要在640x360的TextureView中显示1280x720的实时预览的中心部分。

这是我所做的。

将相机预览设置为我所需的分辨率的两倍:

params.setPreviewSize(1280, 720);

然后根据比例缩放纹理视图:

this.captureView.setScaleX(2f);
this.captureView.setScaleY(2f);

这在小型设备上运行没有任何问题。


非常感谢你,你救了我。 - YeeKhin

2

您可以从onPreview()中操作byte[] data

我认为您需要:

  • 将其放入位图中
  • Bitmap中进行裁剪
  • 进行一些拉伸/调整大小
  • Bitmap传递给您的SurfaceView

这不是一种非常高效的方法。也许您可以直接操作byte[],但您必须处理像NV21这样的图片格式。


1

@SatteliteSD提供的答案是最恰当的。每个相机仅支持在HAL中设置的特定预览大小。因此,如果可用的预览大小不足以满足要求,则需要从onPreview中提取数据。


0

对于相机预览图像的实时操作,OpenCV for Android非常适合。您可以在这里找到所需的每个示例:http://opencv.org/platforms/android/opencv4android-samples.html,并且正如您所看到的,它在实时环境中运行得非常好。

免责声明:根据您对C++ / OpenCV / NDK的经验,设置Android上的OpenCV库可能会非常棘手。在所有情况下,编写OpenCV代码从来都不是简单的事情,但另一方面,它是一个非常强大的库。


我自己一直在研究JavaCameraView,它似乎是在CPU上使用本地代码进行yuv->rgb转换,而不是在GPU上进行...我认为这导致了相机帧传递到屏幕时的实际减速(延迟和低帧率)。 - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接