VNDetectRectanglesRequest仅在图像中检测到具有两个矩形的一个矩形-视觉,快速

时间:2019-03-14 20:36:06

标签: ios swift computer-vision vision

我正在使用以下方法检测此图像中的矩形: https://richardzhaodesign.files.wordpress.com/2015/02/order-final.jpg?w=300&h=300

import UIKit
import Vision

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    guard let image = UIImage(named: "sample2") else { return }

    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    let scaledHeight = view.frame.width / image.size.width * image.size.height
    imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: scaledHeight)
    imageView.backgroundColor = .blue

    view.addSubview(imageView)

    let request = VNDetectRectanglesRequest { (req, err) in

        if let err = err {
            print("Failed to detect faces:", err)
            return
        }

        req.results?.forEach({ (res) in
            print("one")
            DispatchQueue.main.async {
                guard let rectangleObservation = res as? VNRectangleObservation else { return }

                let x = self.view.frame.width * rectangleObservation.boundingBox.origin.x
                let height = scaledHeight * rectangleObservation.boundingBox.height
                let y = scaledHeight * (1 -  rectangleObservation.boundingBox.origin.y) - height
                let width = self.view.frame.width * rectangleObservation.boundingBox.width

                let redView = UIView()
                redView.layer.borderColor = UIColor.red.cgColor
                redView.layer.borderWidth = 5
                redView.frame = CGRect(x: x, y: y, width: width, height: height)
                self.view.addSubview(redView)

            }
        })
    }

    guard let cgImage = image.cgImage else { return }

    DispatchQueue.global(qos: .background).async {
        let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
        do {
            try handler.perform([request])
        } catch let reqErr {
            print("Failed to perform request:", reqErr)
        }
    }

}
}

我的问题是为什么这不能识别两个正方形。我看到其他代码可以识别多个矩形,但是我的代码始终只能识别一个矩形。我确信这并不是Vision框架无法高精度地识别另一个框架,只是我在代码中丢失了一些东西。谢谢。

1 个答案:

答案 0 :(得分:0)

您必须设置VNDetectRectanglesRequest的{​​{3}}属性。默认值为1,这就是为什么您只得到1个结果的原因。

例如:

    let request = VNDetectRectanglesRequest { (req, err) in
        // Your completion handler code
    }

    request.maximumObservations = 2