2017-06-12 165 views
1

我試圖調整一個大小爲128x128的CVPixelBuffer。我正在使用750x750。我目前正在使用CVPixelBuffer創建一個新的CGImage,然後將其重新調整爲CVPixelBuffer。這裏是我的代碼:調整一個CVPixelBuffer的大小

func getImageFromSampleBuffer (buffer:CMSampleBuffer) -> UIImage? { 
    if let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) { 
     let ciImage = CIImage(cvPixelBuffer: pixelBuffer) 
     let context = CIContext() 
     let imageRect = CGRect(x: 0, y: 0, width: 128, height: 128) 

     if let image = context.createCGImage(ciImage, from: imageRect) { 
      let t = CIImage(cgImage: image) 
      let new = t.applying(transformation) 
      context.render(new, to: pixelBuffer) 

      return UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .right) 
     } 

    } 

    return nil 
} 

我也試着縮放CIImage然後將其轉換:

let t = CIImage(cgImage: image) 
let transformation = CGAffineTransform(scaleX: 1, y: 2) 
let new = t.applying(transformation) 
context.render(new, to: pixelBuffer) 

但是,這也不能工作。

任何幫助表示讚賞。謝謝!

+0

請在這裏查找'vImageScale_ARGB8888':https://stackoverflow.com/a/10063006/2567725 –

回答

0

試試這個

func getImageFromSampleBuffer (buffer:CMSampleBuffer) -> UIImage? { 
    if let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) { 
     let ciImage = CIImage(cvPixelBuffer: pixelBuffer) 
     let resizedCIImage = ciImage.applying(CGAffineTransform(scaleX: 128.0/750.0, y: 128.0/750.0)) 

     let context = CIContext() 
     if let image = context.createCGImage(resizedCIImage, from: resizedCIImage.extent) { 
      return UIImage(cgImage: image) 
     } 
    } 
    return nil 
} 

這裏我假設像素緩衝區是正方形,大小等於750x750,你可以改變它與所有寬高比工作和大小

0

沒有必要爲像素緩衝區渲染和相似。只需將原來的CIImage和裁剪變成大小。如果您的來源和目的地尺寸不成比例,則需要裁剪。

func getImageFromSampleBuffer (buffer:CMSampleBuffer) -> UIImage? { 
    if let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) { 
     let ciImage = CIImage(cvPixelBuffer: pixelBuffer) 

     let srcWidth = CGFloat(ciImage.extent.width) 
     let srcHeight = CGFloat(ciImage.extent.height) 

     let dstWidth: CGFloat = 128 
     let dstHeight: CGFloat = 128 

     let scaleX = dstWidth/srcWidth 
     let scaleY = dstHeight/srcHeight 
     let scale = min(scaleX, scaleY) 

     let transform = CGAffineTransform.init(scaleX: scale, y: scale) 
     let output = ciImage.transformed(by: transform).cropped(to: CGRect(x: 0, y: 0, width: dstWidth, height: dstHeight)) 

     return UIImage(ciImage: output) 
    } 

    return nil 
} 
相關問題