【发布时间】:2020-10-18 04:13:51
【问题描述】:
我正在尝试使用 Xcode CoreML 对简单的单个数字或字母的图像进行分类。首先,我只是使用 .png 数字图像。使用 Create ML 工具,我构建了一个图像分类器(不包括任何视觉支持的东西),并提供了一组大约 300 个训练图像和一组单独的 50 个测试图像。当我运行这个模型时,它成功地训练和测试并生成一个模型。仍然在工具中,我访问模型并为其提供另一组 100 张图像进行分类。它可以正常工作,正确识别其中的 98 个。
然后我创建了一个 Swift 示例程序来访问模型(来自 Mac OS X 单视图模板);它被设置为接受丢弃的图像文件,然后访问模型的预测方法并打印结果。问题是模型需要一个 CVPixelBuffer 类型的对象,我不确定如何从 NSImage 正确创建它。我找到了一些参考代码并包含在内,但是当我实际将分类图像拖到应用程序时,它的准确率只有 50% 左右。所以我想知道是否有人对这种类型的模型有任何经验。如果有一种方法可以查看“Create ML”源代码,以了解它在从模型进行预测时如何处理丢弃的图像。
图像处理和调用模型预测方法的代码为:
// initialize the model
mlModel2 = MLSample() //MLSample is model generated by ML Create tool and imported to project
// prediction logic for the image
// (included in a func)
//
let fimage = NSImage.init(contentsOfFile: fname) //fname is obtained from dropped file
do {
let fcgImage = fimage.cgImage(forProposedRect: nil, context: nil, hints: nil)
let imageConstraint = mlModel2?.model.modelDescription.inputDescriptionsByName["image"]?.imageConstraint
let featureValue = try MLFeatureValue(cgImage: fcgImage!, constraint: imageConstraint!, options: nil)
let pxbuf = featureValue.imageBufferValue
let mro = try mlModel2?.prediction(image: pxbuf!)
if mro != nil {
let mroLbl = mro!.classLabel
let mroProb = mro!.classLabelProbs[mroLbl] ?? 0.0
print(String.init(format: "M2 MLFeature: %@ %5.2f", mroLbl, mroProb))
return
}
}
catch {
print(error.localizedDescription)
}
return
【问题讨论】: