Как получить текстовое поле NSImage of Vision

Я работаю над проектом macOS Vision, включающим обнаружение текста, и моя цель - получить NSImage каждого обнаруженного символа для дальнейшей обработки. У меня проблемы. В частности, следующий код возвращает изображение с размером 0 на 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.

Я связал полный проект на Github.

0 ответов

Другие вопросы по тегам