简体   繁体   English

如何在SwiftUI中将VNRectangleObservation项转换为UIImage

[英]How to convert VNRectangleObservation item to UIImage in SwiftUI

I was able to identify squares from a images using VNDetectRectanglesRequest .我能够使用VNDetectRectanglesRequest从图像中识别正方形。 Now I want those rectangles to store as separate images (UIImage or cgImage).现在我希望这些矩形存储为单独的图像(UIImage 或 cgImage)。 Below is what I tried.以下是我尝试过的。

        let rectanglesDetection = VNDetectRectanglesRequest { request, error in
            rectangles = request.results as! [VNRectangleObservation]
            rectangles.sort{$0.boundingBox.origin.y > $1.boundingBox.origin.y}
            
            for rectangle in rectangles {

                let rect = rectangle.boundingBox
                let imageRef = cgImage.cropping(to: rect)
                let image = UIImage(cgImage: imageRef!, scale: image!.scale, orientation: image!.imageOrientation)

                checkBoxImages.append(image)
            }

Can anybody point out what's wrong or what should be the best approach?任何人都可以指出什么是错的或最好的方法是什么?


Update更新

At this stage, I'm testing with an image that I added to the assets.在此阶段,我正在使用添加到资产中的图像进行测试。

我正在测试的图像

With this image I get 7 rectangles as observations as each for each cell and one for the table margin.有了这张图片,我得到了 7 个矩形作为每个单元格的观察值,一个用于表格边距。

My task is to identify the text inside in each rectangle and my approach is to send VNRecognizeTextRequest for each rectangle that has been identified.我的任务是识别每个矩形中的文本,我的方法是为每个已识别的矩形发送VNRecognizeTextRequest My real scenario is little complicated than this but I want to at least achieve this before going forward.我的真实情况比这复杂一点,但我想至少在继续之前实现这一点。

This is just a guess since you didn't state what the actual problem is, but probably you're getting a zero-sized image for each VNRectangleObservation.这只是一个猜测,因为您没有 state 实际问题是什么,但您可能会为每个 VNRectangleObservation 获得一个大小为零的图像。

The reason is: Vision uses a normalized coordinate space from 0.0 to 1.0 with lower left origin.原因是: Vision 使用从 0.0 到 1.0 的归一化坐标空间,原点在左下角。

So in order to get the correct rectangle of your original image, you need to convert the rect from Normalized Space to Image Space.因此,为了获得原始图像的正确矩形,您需要将矩形从规范化空间转换为图像空间。 Luckily there is VNImageRectForNormalizedRect( : :_:) to do just that.幸运的是,有VNImageRectForNormalizedRect( : :_:)可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM