在 Android Vision API 中切换到 Camera2

Switching to Camera2 in Android Vision API

我看到 android vision api(示例在这里:https://github.com/googlesamples/android-vision)相机 (camera1) 现在已弃用,建议使用 camera2。

你们知道如何重写 CameraSource 以在 android 视觉上使用 camera2 吗?

提前致谢,

请看

camera2 with mobile vision? #65

好的,我找到了这个

There are no near term plans for a camera2 version of the CameraSource class in the official API. However, given how the API is structured, an alternate version of CameraSource could be written by the developer community that uses camera2. All of the existing APIs for working with frames and detectors are sufficient to support a camera2 implementation as well.

可以将 Camera2 API 与 Google Vision API 一起使用。

首先,Google 视觉 API 人脸检测器接收一个 Frame 对象,用于分析(检测人脸及其标志)。

Camera1 API提供了NV21图像格式的预览帧,非常适合我们。 Google Vision Frame.Builder 支持 setImageData (ByteBuffer in NV16, NV21 or YV12 image format) and setBitmap 使用位图作为预览帧进行处理。

您的问题是 Camera2 API 提供不同格式的预览帧。是YUV_420_888。要使一切正常,您必须将预览帧转换为支持的格式之一。

ImageReader as Image 获得 Camera2 预览帧后,您可以使用此功能将其转换为支持的格式(在本例中为 NV21)。

private byte[] convertYUV420888ToNV21(Image imgYUV420) {
    // Converting YUV_420_888 data to YUV_420_SP (NV21).
    byte[] data;
    ByteBuffer buffer0 = imgYUV420.getPlanes()[0].getBuffer();
    ByteBuffer buffer2 = imgYUV420.getPlanes()[2].getBuffer();
    int buffer0_size = buffer0.remaining();
    int buffer2_size = buffer2.remaining();
    data = new byte[buffer0_size + buffer2_size];
    buffer0.get(data, 0, buffer0_size);
    buffer2.get(data, buffer0_size, buffer2_size);
    return data;
}

然后你可以使用返回的byte[]创建一个Google Vision Frame:

outputFrame = new Frame.Builder()
    .setImageData(nv21bytes, mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.NV21)
    .setId(mPendingFrameId)
    .setTimestampMillis(mPendingTimeMillis)
    .setRotation(mSensorOrientation)
    .build();

最后,您使用创建的帧调用检测器:

mDetector.receiveFrame(outputFrame);

无论如何,如果您想了解更多相关信息,可以在 GitHub: Camera2Vision 上免费测试我的工作示例。希望对您有所帮助:)

我没有尝试下面的 link 因为我停止了 Google Android 愿景的工作,但我认为它对那些想要的人有好处:

https://medium.com/@mt1729/an-android-journey-barcode-scanning-with-mobile-vision-api-and-camera2-part-1-8a97cc0d6747