问题
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