VNDetectRectanglesRequest 仅检测具有两个矩形的图像中的一个矩形 - 视觉,Swift

VNDetectRectanglesRequest Only Detects One Rectangle In Image With Two Rectangles - Vision, Swift

我正在使用以下方法检测此图像中的矩形: 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 框架不能高精度地识别另一个,只是我的代码中遗漏了一些东西。谢谢。

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

例如:

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

    request.maximumObservations = 2