2

I have the following code to crop CIImage and render to CVPixelBuffer which unfortunately isn't working. Some portion of the image on the left side is black or green. What am I doing wrong I wonder?

    _ciContext = CIContext(mtlDevice: metalDevice, options: [CIContextOption.useSoftwareRenderer: false])



        let dstWidth = CVPixelBufferGetWidth(dstPixelBuffer!)
        let dstHeight = CVPixelBufferGetHeight(dstPixelBuffer!)
        
        let srcWidth = CVPixelBufferGetWidth(pixelBuffer)
        let srcHeight = CVPixelBufferGetHeight(pixelBuffer)
        
        let cropRect = CGRect(x: (srcWidth - dstWidth)/2, y: (srcHeight - dstHeight)/2, width: dstWidth, height: dstHeight)
        let dstImage = srcImage.cropped(to: cropRect)
        
        NSLog("Src image \(srcImage.extent), \(dstImage.extent)")
        var dstBounds = CGRect.zero
        dstBounds.size = dstImage.extent.size
        _ciContext.render(dstImage, to: dstPixelBuffer!, bounds: dstBounds, colorSpace: srcImage.colorSpace )

EDIT: I had to apply a translate transform to the dstImage by amount -cropRect.minX and -cropRect.minY to get it working. No idea why. Can someone comment the right way to crop CIImage and render to CVPixelBuffer?

Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • In the event you're converting to a CGImage later on anyway, the CGImage.cropping() method gives the expected results. As you found, CIImage.cropped() doesn't translate the result to the origin. – Nestor Feb 04 '21 at 14:37

0 Answers0