3

我正在尝试将 CVPixelBuffer 的大小调整为 128x128。我正在使用 750x750 的。我目前正在使用 CVPixelBuffer 创建一个新的 CGImage,我调整它的大小然后转换回 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)

但这也没有用。

任何帮助表示赞赏。谢谢!

4

2 回答 2

4

不需要像素缓冲区渲染等。只需转换原件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
}
于 2018-03-01T14:41:25.987 回答
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,您可以将其更改为适用于所有纵横比和大小

于 2017-06-21T18:29:25.117 回答