SWIFT: Limit size of CMSampleBufferGetImageBuffer for CGRect in Barcode scanner

I have a SwiftUI app that I want to limit the size of a barcode scanner to a AVCaptureVideoPreviewLayer with a size of CGRect(x: 0, y: 0, width: 335, height: 150). (see image) I am using Apple Vision to detect the barcode. However barcodes that are out of the CGRect are also getting picked up and I would like to limit the area to my preview layer. I notice the pixel buffer is using the entire screen of width=1920 height=1080 as my device is an iPhone 11 Pro. Can I limit the buffer size before passing to Vision?

extension CameraViewController: AVCaptureVideoDataOutputSampleBufferDelegate {

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

    guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
        return
        
    }
    
    print("output \(output)")
    print("sampleBuffer \(sampleBuffer)")
    print("connection \(connection)")
    print("pixelBuffer \(pixelBuffer)")
    
    let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .up)
    
    
    do {
        try imageRequestHandler.perform([detectBarcodeRequest])
    } catch {
        print(error)
    }
}//captureOutput

}//extension

You can set a regionOfInterest on your barcode detection request to specify that Vision should only look at that particular region of an image.

Thanks @gchiste, how do I "convert" the CGRect of CGRect(x: 0, y: 0, width: 335, height: 150) to normalized to the dimensions of the processed image?

You can use this helper method to normalize your image space rect: VNNormalizedRectForImageRect(::_:)

SWIFT: Limit size of CMSampleBufferGetImageBuffer for CGRect in Barcode scanner
 
 
Q