如何从灰度字节缓冲区图像创建位图?

rcm*_*lli 9 android bitmap grayscale google-vision android-vision

我正在尝试使用新的Android脸部检测移动视觉API来处理帧图像.

所以我创建了自定义检测器以获取Frame并尝试调用getBitmap()方法,但它为null,因此我访问了帧的灰度数据.有没有办法从它创建位图或类似的图像持有者类?

public class CustomFaceDetector extends Detector<Face> {
private Detector<Face> mDelegate;

public CustomFaceDetector(Detector<Face> delegate) {
    mDelegate = delegate;
}

public SparseArray<Face> detect(Frame frame) {
    ByteBuffer byteBuffer = frame.getGrayscaleImageData();
    byte[] bytes = byteBuffer.array();
    int w = frame.getMetadata().getWidth();
    int h = frame.getMetadata().getHeight();
    // Byte array to Bitmap here
    return mDelegate.detect(frame);
}

public boolean isOperational() {
    return mDelegate.isOperational();
}

public boolean setFocus(int id) {
    return mDelegate.setFocus(id);
}}
Run Code Online (Sandbox Code Playgroud)

小智 12

你可能已经对此进行了整理,但如果将来有人偶然发现这个问题,我就是这样解决的:

正如@ pm0733464指出的那样,默认的图像格式android.hardware.Camera是NV21,这是CameraSource使用的格式.

这个 stackoverflow答案提供了答案:

YuvImage yuvimage=new YuvImage(byteBuffer, ImageFormat.NV21, w, h, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, w, h), 100, baos); // Where 100 is the quality of the generated jpeg
byte[] jpegArray = baos.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(jpegArray, 0, jpegArray.length);
Run Code Online (Sandbox Code Playgroud)

虽然frame.getGrayscaleImageData()建议bitmap将是原始图像的灰度版本,但根据我的经验,情况并非如此.实际上,位图与提供给本SurfaceHolder机的位图相同.