将 UIImage 加载到浮点数组以供 DeepLearningKit 使用



我想使用iOS版的DeepLearningKit。我想使用 UIImage 对象进行分类。示例应用程序仅使用从 json 文件加载的浮点数组。因此,我必须将 UIImage 的位图表示形式创建为浮点数组,并将其用于分类方法。

有人可以帮助我吗?有没有办法为 UIImage 创建位图表示形式?此外,我必须将通道从 RGB 交换为 BGR。

谢谢

为 UIImage 添加了一个扩展,允许直接设置和获取 RGB(A) 像素 - 关键方法:

public func setPixelColorAtPoint(point:CGPoint, color: RawColorType) -> UIImage? 
func getPixelColorAtLocation(point:CGPoint)->UIColor?

其中 RawColorType 定义为

public typealias RawColorType = (newRedColor:UInt8, newgreenColor:UInt8, newblueColor:UInt8,  newalphaValue:UInt8)

这样,您应该能够在位图表示和 UIImage 之间来回转换。写了一篇博客文章,提供了更多的背景:http://deeplearningkit.org/tutorials-for-ios-os-x-and-tvos/tutorial-image-handling-in-deeplearningkit/

我编写了一个函数来在iOS平台上将图像文件转换为Caffe blob。你可以在这里找到它。我希望它能帮助你。

代码片段:

// Convert Bitmap (channels*width*height) to Matrix (width*height*channels)
// Remove alpha channel
int input_channels = input_layer->channels();
LOG(INFO) << "image_channels:" << image_channels << " input_channels:" << input_channels;
if (input_channels == 3 && image_channels != 4) {
    LOG(ERROR) << "image_channels input_channels not match.";
    return false;
} else if (input_channels == 1 && image_channels != 1) {
    LOG(ERROR) << "image_channels input_channels not match.";
    return false;
}
float *input_data = input_layer->mutable_cpu_data();
for (size_t h = 0; h < height; h++) {
    for (size_t w = 0; w < width; w++) {
        for (size_t c = 0; c < input_channels; c++) {
            // OpenCV use BGR instead of RGB
            size_t cc = c;
            if (input_channels == 3) {
                cc = 2 - c;
            }
            // Convert uint8_t to float
            input_data[c*width*height + h*width + w] = 
                static_cast<float>(result[h*width*image_channels + w*image_channels + cc]);
            if (mean.size() == input_channels) {
                input_data[c*width*height + h*width + w] -= mean[c];
            }
        }
    }
}

最新更新