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

标签 android bitmap grayscale google-vision android-vision

我正在尝试在使用新的 Android 人脸检测移动视觉 API 时获取要处理的帧图像。

所以我创建了 Custom Detector 来获取 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);
}}

最佳答案

您可能已经解决了这个问题,但如果将来有人偶然发现这个问题,我是这样解决的:

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

This stackoverflow 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 的位图相同。

关于android - 如何从灰度字节缓冲区图像创建位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32412197/

相关文章:

Android 位图图像大小

c# - 灰度图像的 MSE 计算

Java 灰度缓冲图像

c++ - OpenCV cv::findcontours StackOverflow 异常

android - 如何解决更新/刷新时的问题 - 显示动画?

java - SQLite 数据库到数据类

Delphi 10 TImage,移动图像宽度

java - 是否可以将 BitmapDescriptor 转换为位图?

android - 如何将 json 序列化对象传递给 android 中的 Intent?

android - 此 TableRow 布局或其 TableLayout 父布局可能无用