opencv - Keras 模型到 Coreml 并使用 OpenCV

标签 opencv keras coreml

我有一个 Keras 模型并已成功将其转换为 Coreml。我将 RGB 格式的彩色 50x50 图像传递给模型,一切都在我的 Python Keras 模型中工作。但是,我真的很难从 Coreml 模型中获得相同的结果。我在我的 iOS 应用程序中使用 OpenCV,需要将 cv::Mat 转换为 CVPixelBufferRef。我很肯定我的输入有问题,但我无法弄清楚它是什么。我发送到 Python 模型的输入的预处理看起来像这样

image = cv2.resize(image, (50, 50)) image = image.astype(" float ")/255.0 image = img_to_array(图像) 图像 = np.expand_dims(图像,轴=0)

如有任何帮助,我们将不胜感激。下面是从 Keras 到 Coreml 的转换及其输出,以及将 cv::Mat 转换为 CVPixelBufferRef 的函数(此处的图像已调整为 50x50)。

Keras 到 Coreml 的转换

coreml_model = coremltools.converters.keras.convert(模型,input_names='image',image_input_names='image',output_names='output',class_labels=output_labels,image_scale=1/255.0)

Output of the Keras to Coreml python script

OpenCV Mat 到 CVPixelBufferRef

int width = 50;//frame.cols;
int height = 50;//frame.rows;

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                         kCVPixelBufferCGBitmapContextCompatibilityKey,
                         [NSNumber numberWithInt:width], kCVPixelBufferWidthKey,
                         [NSNumber numberWithInt:height], kCVPixelBufferHeightKey,
                         nil];

CVPixelBufferRef imageBuffer;
CVReturn status = CVPixelBufferCreate(kCFAllocatorMalloc, width, height, kCVPixelFormatType_32BGRA, (CFDictionaryRef) CFBridgingRetain(options), &imageBuffer);

NSParameterAssert(status == kCVReturnSuccess && imageBuffer != NULL);

CVPixelBufferLockBaseAddress(imageBuffer, 0);
void *base = CVPixelBufferGetBaseAddress(imageBuffer) ;
memcpy(base, frame.data, frame.total()*4);
CVPixelBufferUnlockBaseAddress(imageBuffer, 0);

return imageBuffer;

最佳答案

如果您尝试使用 OpenCV 加载图像并将其输入 Keras 模型,则需要格外小心,因为默认情况下 Keras 在训练时使用 PIL 加载图像。问题在于 PIL 将图像加载为 RGB 格式,而 OpenCV 将图像加载为 BGR 格式。因此,如果您直接将 OpenCV 图像提供给 Keras,您不会得到任何错误,但您的结果将是完全错误的。

至于解决这个问题,在Python中你可以简单地使用

img[...,[0,2]]=img[...,[2,0]]

在 OpenCV 格式和 PIL 格式之间转换 3 channel 图像文件。

关于opencv - Keras 模型到 Coreml 并使用 OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061470/

相关文章:

c++ - 如何在 OpenCV 的 cvShowImage() 函数调用的窗口中显示中文文本?

c++ - imshow 不工作

python - 减小 Keras LSTM 模型的大小

python - Keras 数据扩充参数

swift - CoreML 图像检测

ios - ARKit 能否将特定表面检测为平面?

dll - OpenCV:链接错误,无法解析外部符号_cvResize和_cvCvtColor

c++ - GMock : error: cannot convert ‘cv::MatExpr’ to ‘bool’ in return

python - Keras - 如何根据一个实例进行预测?

ios - 在 iOS 应用程序中实现 Keras 模型转换为 CoreML 模型时出现 fatal error