rotate CIImage around center with CIFilter

别说谁变了你拦得住时间么 提交于 2020-03-28 04:15:13

问题


I'm trying to rotate the pixel data of a CMSampleBuffer (coming from the camera) and display it in a UIImageView. I Don't want to rotate the view itself. It has to be the actual pixel data.

I grab the feed, convert it to a CIImage and with a CIFilter I rotate it. I'm having trouble with setting the point around which it has to rotate. Right now it rotates around the lower left point. I want to rotate it around its center.

 func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {

            //create pixelbuffer

            let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
            let context = CIContext.init(options: nil)

            // calculating the radians to rotate the ciimage by
            let radians : Float = atan2f(Float(boxView!.transform.b), Float(boxView!.transform.a));
            //create ciimage from the pixelbuffer

            let options = [kCVPixelBufferCGImageCompatibilityKey as String: true,
                kCVPixelBufferCGBitmapContextCompatibilityKey as String: true,]
            let ci = CIImage.init(cvPixelBuffer: pixelBuffer, options: options)
            //transform filter
            let filter = CIFilter.init(name: "CIAffineTransform")
            //set translation point to center
            var transform = CGAffineTransform(translationX: self.view.frame.midX, y: self.view.frame.midY)
            //rotate
            transform = CGAffineTransform(rotationAngle:CGFloat(radians))
            // set translation point back again to normal
            var transformBack = CGAffineTransform(translationX: -self.view.frame.midX, y: -self.view.frame.midY)
            //applying the transform
            transform.concatenating(transformBack)

            filter!.setValue(transform, forKey: kCIInputTransformKey)
            filter!.setValue(ci, forKey: kCIInputImageKey)
            let output = filter?.outputImage
            let img = context.createCGImage(output!, from: imageView!.frame)
            // send image to be displayed
            self.imageView!.image = UIImage(cgImage: img!)

}

回答1:


found it. I have to apply transformations to the transformation variable itself.

let transform = CGAffineTransform(translationX: self.view.frame.midX, y: self.view.frame.midY).rotate(angle: CGFloat(radians)).translatedBy(x: -self.view.frame.midX, y: -self.view.frame.midY)



回答2:


Swift 5:

let image = CIImage(cvPixelBuffer: yourBuffer)
let rotatedImage = image.oriented(forExifOrientation: Int32(CGImagePropertyOrientation.right.rawValue))

There is an explicit API for this: Docs



来源:https://stackoverflow.com/questions/44500622/rotate-ciimage-around-center-with-cifilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!