我正在从事涉及文本检测的macOS Vision项目,我的目标是获取每个检测到的字符的NSImage
以便进一步处理。我有麻烦了。具体来说,以下代码返回尺寸为0 x 0的图像。
func character(from targetImage: NSImage, with targetBox: VNRectangleObservation) -> NSImage {
// let xCord = targetBox.topLeft.x * imageDisplayWell.frame.size.width
// let yCord = (1 - targetBox.topLeft.y) * imageDisplayWell.frame.size.height
/*let xCoord = box.topLeft.x * previewView.frame.size.width
let yCoord = (1 - box.topLeft.y) * previewView.frame.size.height
let width = (box.topRight.x - box.bottomLeft.x) * previewView.frame.size.width
let height = (box.topLeft.y - box.bottomLeft.y) * previewView.frame.size.height*/
let cropRect = CGRect(x: targetBox.bottomLeft.x * (imageDisplayWell.image?.size.width)!, y: targetBox.bottomLeft.y * (imageDisplayWell.image?.size.height)!, width: (targetBox.topRight.x - targetBox.bottomLeft.x) * (imageDisplayWell.image?.size.height)!, height: (targetBox.topLeft.y - targetBox.bottomLeft.y) * (imageDisplayWell.image?.size.height)!)
let imageData = mainImage.tiffRepresentation
let sourceData = CGImageSourceCreateWithData(imageData as! CFData, nil)
// let croppedImage = CGImageSourceCreateImageAtIndex(sourceData!, 0, nil)?.cropping(to: cropRect)
let croppedImage = targetImage.cgImage(forProposedRect: nil, context: nil, hints: nil)?.cropping(to: cropRect)
print(croppedImage)
return NSImage(cgImage: croppedImage!, size: CGSize(width: (croppedImage?.width)!, height: croppedImage!.height))
}
此代码返回错误CGImageCreateWithImageProvider: invalid image size: 0 x 0.
我已经链接了整个项目on Github。