gpt4 book ai didi

ios - CVPixelBuffer 使用 UIImage.draw() 编写太慢

转载 作者:行者123 更新时间:2023-11-28 15:18:17 25 4
gpt4 key购买 nike

我是一名本科生,我现在正在使用 CoreML 框架在 iPhone 上做一些视频 HumanSeg 应用程序,但正如标题所示,我遇到了一个 huuuuuge 问题。

我有一个 UIImage,我必须调整它的大小并对其进行填充,然后将它绘制到一个 CVPixelBuffer 中以提供给 MobileNet 模型,但这样的过程太慢了,耗时大约 30 毫秒,这是 Not Acceptable 。

具体来说,在我的代码中,方法 UIImage.draw(in: CGRect(x: Int, y: Int, width: Int, height: Int)) 太慢了,花了我 20 多毫秒,这是主要问题。

我的代码如下:

func dealRawImage(image : UIImage, dstshape : [Int], pad : UIImage) -> CVPixelBuffer?
{
// decide whether to shrink in height or width
let height = image.size.height
let width = image.size.width
let ratio = width / height
let dst_width = Int(min(CGFloat(dstshape[1]) * ratio, CGFloat(dstshape[0])))
let dst_height = Int(min(CGFloat(dstshape[0]) / ratio, CGFloat(dstshape[1])))
let origin = [Int((dstshape[0] - dst_height) / 2), Int((dstshape[1] - dst_width) / 2)]

// init a pixelBuffer to store the resized & padded image
var pixelBuffer: CVPixelBuffer?
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue,
kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue]
CVPixelBufferCreate(kCFAllocatorDefault,
dstshape[1],
dstshape[0],
kCVPixelFormatType_32ARGB,
attrs as CFDictionary,
&pixelBuffer)

// get the pointer of this pixelBuffer
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!)

// init a context that contains this pixelBuffer to draw in
let context = CGContext(data: pixelData,
width: dstshape[1],
height: dstshape[0],
bitsPerComponent: 8,
bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue)!

// push context
UIGraphicsPushContext(context)
context.translateBy(x: 0, y: CGFloat(dstshape[0]))
context.scaleBy(x: 1, y: -1)

pad.draw(in:CGRect(x: 0, y: 0, width: dstshape[1], height: dstshape[0]))
// THIS SINGLE FUNCTION COSTS ME 20+ ms AND IS THE MAJOR ISSUE !
image.draw(in: CGRect(x: origin[1], y: origin[0], width: dst_width, height: dst_height))

UIGraphicsPopContext()

// unlock
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))

return pixelBuffer
}

我只是这样调用这个函数:

let input = dealRawImage(image: raw_input_image, dstshape: [224, 224], pad: black_image)

其中 raw_input_image 是我从内存中读取的 UIImage,dstshape 是我想要将此图像调整为的形状,而 black_image 是用于填充的全黑 UIImage。

我在该网站上进行了搜索,但没有发现任何熟悉的问题。

有什么方法可以加快这个过程并保存这个项目?我只是不想放弃我 2 周的工作。

最佳答案

自从我处理 CVPixelBuffer 以来已经有一段时间了,而且我还没有使用过 CoreML

当我确实使用CVPixelBuffer时,我发现通过以目标大小创建单个像素缓冲区并将其保持在周围,我获得了最佳性能。我从相机中获取像素,将它们作为纹理传递给 OpenGL,对其进行操作,并将输出映射到同一个 CVPixelBuffer 中。我能够为所有这些使用相同的内存结构。我建议采用这种方法。

关于ios - CVPixelBuffer 使用 UIImage.draw() 编写太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com