only detect in a section of camera preview layer, iOS, Swift

1.5k views Asked by At

I am trying to get a detection zone in a live preview on my camera preview layer.

Is it possible for this, say there is a live feed and you have face detect on and as you look around it will only put a box around the face in a certain area for example a rectangle in the centre of the screen. all other faces in the preview that are outside of the rectangle don't get detected?

Im using Vision, iOS, Swift.

1

There are 1 answers

1
Tony Merritt On

I figured this out by adding a guard before the CALayer adding

Before View did load

@IBOutlet weak var scanAreaImage: UIImageView!
var regionOfInterest: CGRect!

In View did load scanAreaImage.frame is a image view that I put in via storyboard and this would represent the area I only wanted detection in,

let someRect: CGRect = scanAreaImage.frame
        regionOfInterest = someRect

then in the vision text detection section.

func highlightLetters(box: VNRectangleObservation) {

    let xCord = box.topLeft.x * (cameraPreviewlayer?.frame.size.width)!
    let yCord = (1 - box.topLeft.y) * (cameraPreviewlayer?.frame.size.height)!
    let width = (box.topRight.x - box.bottomLeft.x) * (cameraPreviewlayer?.frame.size.width)!
    let height = (box.topLeft.y - box.bottomLeft.y) * (cameraPreviewlayer?.frame.size.height)!

// This is the section I Added for the rec of interest detection zone.
//////////////////////////////////////////////

    let wordRect = CGRect(x: xCord, y: yCord, width: width, height: height)
    guard regionOfInterest.contains(wordRect.origin) else { return } // only draw a box if the orgin of the word box is within the regionOfInterest

// regionOfInterest being the cgRect you created earlier    
   //////////////////////////////////////////////

    let outline = CALayer()
    outline.frame = CGRect(x: xCord, y: yCord, width: width, height: height)
    outline.borderWidth = 1.0
    if textColour == 1 {
        outline.borderColor = UIColor.blue.cgColor
    }else {
        outline.borderColor = UIColor.clear.cgColor
    }

    cameraPreviewlayer?.addSublayer(outline)

this will only show outlines of the things inside the rectangle you created in storyboard. (Mine being the scanAreaImage)

I hope this helps someone.