我想在 CoreML 中使用样式迁移(example)。由于 CoreML 支持转换 Keras,我的第一个想法是转换他们的一个示例,如 one 或 this one,但基于 this 线程的这种方法似乎没有什么问题。
如何在 CoreML 中使用样式迁移?任何例子都会有所帮助。
编辑:
感谢link@twrdster,我能够测试它并且它对我有用。
此外,我还发现了 Prisma 的这个 (torch2coreml) 存储库。
您可以使用 Apple 的
Create ML
应用程序来制作您自己的样式。它非常容易使用。我在几个小时内就学会了。你需要:
进行风格转换的代码 (
allSabilandStylesParameterIn
== "image"
, allSabilandStylesParameterOut
== "stylizedImage"
):
private static func makeCreateNextMLSabilandStyle(
input: UIImage,
style: String
) -> UIImage
{
guard let filepath = Bundle.main.path(forResource: style, ofType: "mlmodelc")
else { return input }
let u = URL(fileURLWithPath: filepath)
// 1
guard
let mlModel = try? MLModel(contentsOf: u)
else {
return input
}
// 2
let imageOptions: [MLFeatureValue.ImageOption: Any] = [
.cropAndScale: VNImageCropAndScaleOption.scaleFill.rawValue
]
guard
let cgImage = input.cgImage,
let imageConstraint = mlModel.modelDescription.inputDescriptionsByName[allSabilandStylesParameterIn[style]!]?.imageConstraint,
let inputImg = try? MLFeatureValue(cgImage: cgImage, constraint: imageConstraint, options: imageOptions),
let inputImage = try? MLDictionaryFeatureProvider(dictionary: [allSabilandStylesParameterIn[style]!: inputImg])
else {
return input
}
// 3
guard
let stylizedImage = try? mlModel.prediction(from: inputImage),
let imgBuffer = stylizedImage.featureValue(for: allSabilandStylesParameterOut[style]!)?.imageBufferValue
else {
return input
}
if let stylized = UIImage(withCVImageBuffer: imgBuffer)
{
return stylized
}
else
{
return input
}
}
和
UIImage
扩展名:
// https://www.jianshu.com/p/d068cdf37d03
convenience init?(withCVImageBuffer cvImageBuffer: CVImageBuffer) {
let ciImage = CIImage(cvImageBuffer: cvImageBuffer)
let context = CIContext.init(options: nil)
guard
let cgImage = context.createCGImage(ciImage, from: ciImage.extent)
else {
return nil
}
self.init(cgImage: cgImage)
}