我想将图像转换为模型图像尺寸。我正在使用API获取图像。这是代码。
let model = GoogLeNetPlaces()
var selectImage: BaseModel!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: selectImage.fullURL)
let imageData = NSData(contentsOf: url!)
detailImageView.image = UIImage(data: imageData! as Data)
if let imageToAnalyze = detailImageView.image {
if let data = sceneLabel(forImage: imageToAnalyze) {
imageLabel.text = data
}
}
}
func sceneLabel(forImage image:UIImage) -> String? {
if let pixel = ImageProcessor.pixelBuffer(forImage: image.cgImage!){
guard let scene = try? model.prediction(sceneImage: pixel) else { fatalError("error")}
return scene.sceneLabel
}
return nil
}
这是我用于图像尺寸转换的代码。
struct ImageProcessor {
static func pixelBuffer (forImage image:CGImage) -> CVPixelBuffer? {
let frameSize = CGSize(width: image.width, height: image.height)
var pixelBuffer:CVPixelBuffer? = nil
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(frameSize.width), Int(frameSize.height), kCVPixelFormatType_32BGRA , nil, &pixelBuffer)
if status != kCVReturnSuccess {
return nil
}
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags.init(rawValue: 0))
let data = CVPixelBufferGetBaseAddress(pixelBuffer!)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
let context = CGContext(data: data, width: Int(frameSize.width), height: Int(frameSize.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: bitmapInfo.rawValue)
context?.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
return pixelBuffer
}
}
我的尺寸有误。
图像尺寸未转换为模型图像尺寸。
有人可以帮我吗?
这是我遇到的错误
[coreml]错误Domain = com.apple.CoreML代码= 1“输入图像特征sceneImage与模型描述不匹配” UserInfo = {NSLocalizedDescription =输入图像特征sceneImage与模型描述不匹配,NSUnderlyingError = 0x6000006a1d40 {Error Domain = com.apple.CoreML代码= 0“图像尺寸3829 x 2411不在允许的图像尺寸组中” UserInfo = {NSLocalizedDescription =图像尺寸3829 x 2411在未允许的图像尺寸组中}}}