将 Android 图像转换为 MATLAB 可以读取的文件

Convert Android image into a file that MATLAB can read

我正在使用 MATLAB 进行与图像识别相关的项目,目前我正在使用 Android 应用程序来帮助完成一些预处理步骤。我认为使用矩阵而不是位图会很容易。我终于设法完成我的算法并将其导入 Eclipse。问题是我意识到我不知道如何将 Bitmap 图像转换成 MATLAB 可以为我的算法读取的图像。

你对我如何做到这一点有什么想法吗?

如果我对你的问题的解释是正确的,你有一张图像存储在 Bitmap class 中,你想将其保存到 Android 设备上的本地文件中。然后您想要将此图像加载到 MATLAB 中以用于您的图像识别算法。

鉴于您的图像通过 Android 在内存中,您可以使用方法 compresshttp://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream

然后您将使用它并将图像保存到文件中,然后您可以将其加载到 MATLAB 中,例如使用 imread

这是您可以为 Android 应用程序编写的一些示例代码。假设您的 Bitmap 实例存储在一个名为 bmp 的变量中,请执行:

FileOutputStream out = null; // For writing to the device
String filename = "out.png"; // Output file name

// Full path to save
// This accesses the pictures directory of your device and saves the file there
String output = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), filename);

try {
    out = new FileOutputStream(filename); // Open up a new file stream
    // Save the Bitmap instance to file
    // First param - type of image
    // Second param - Compression factor
    // Third param - The full path to the file
    // Note: PNG is lossless, so the compression factor (100) is ignored
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out); 
}
// Catch any exceptions that happen 
catch (Exception e) {
    e.printStackTrace();
} 
// Execute this code even if exception happens
finally {
    try {
        // Close the file if it was open to write
        if (out != null)
            out.close();
    } 
    // Catch any exceptions with the closing here
    catch (IOException e) {
        e.printStackTrace();
    }
}

以上代码会将图像保存到设备上的默认图片目录中。拉出该图像后,您可以使用 imread:

将图像读入 MATLAB
im = imread('out.png');
因此,

im 将是您现在可以用于图像识别算法的图像的原始 RGB 像素。