如何从灰度字节缓冲区图像创建位图? [英] How to create Bitmap from grayscaled byte buffer image?
问题描述
我正在尝试使用新的Android人脸检测移动视觉api处理帧图像。
I am trying to get frame image to process while using new Android face detection mobile vision api.
因此,我创建了自定义检测器来获取Frame并尝试调用getBitmap()方法,但是它为null,因此我访问了帧的灰度数据。是否可以通过它或类似的图像持有者类来创建位图?
So I have created Custom Detector to get Frame and tried to call getBitmap() method but it is null so I accessed grayscale data of frame. Is there a way to create bitmap from it or similiar image holder class?
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);
}}
推荐答案
您有可能已经解决了这个问题,但是如果将来有人偶然发现这个问题,这就是我的解决方法:
@ pm0733464指出,从 android.hardware.Camera
出来的默认图像格式是NV21,这是 CameraSource 。
As @pm0733464 points out, the default image format coming out of android.hardware.Camera
is NV21, and that is the one used by CameraSource.
这个 stackoverflow答案提供了答案:
This stackoverflow answer provides the answer:
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);
尽管 frame.getGrayscaleImageData()
建议 bitmap
将是原始图像的灰度版本,根据我的经验,情况并非如此。实际上,该位图与本地提供给 SurfaceHolder
的位图相同。
Although frame.getGrayscaleImageData()
suggests bitmap
will be a grayscale version of the original image, this is not the case, in my experience. In fact, the bitmap is identical to the one supplied to the SurfaceHolder
natively.
这篇关于如何从灰度字节缓冲区图像创建位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!