我正在尝试使用Brad Larson出色的GPUImage
框架,并且正在努力处理GPUImageHarrisCornerDetectionFilter
返回的cornerArray。
角作为UnsafeMutablePointer
中的GLFloat
数组返回 - 我想将其转换为CGPoint
数组
我试过为内存分配空间
var cornerPointer = UnsafeMutablePointer<GLfloat>.alloc(Int(cornersDetected) * 2)
但数据似乎没有任何意义——零或 1E-32
我找到了如何在 Swift 中循环遍历<不安全可变指针>数组元素的完美答案并尝试了不安全可变指针>
filter.cornersDetectedBlock = {(cornerArray:UnsafeMutablePointer<GLfloat>, cornersDetected:UInt, frameTime:CMTime) in
crosshairGenerator.renderCrosshairsFromArray(cornerArray, count:cornersDetected, frameTime:frameTime)
for floatData in UnsafeBufferPointer(start: cornerArray, count: cornersDetected)
{
println("(floatData)")
}
但是编译器不喜欢UnsafeBufferPointer
- 所以我将其更改为 UnsafeMutablePointer
,但它不喜欢参数列表。
我敢肯定这很好,很简单,听起来像是其他人必须做的事情 - 那么解决方案是什么?
从 C 翻译而来的 UnsafeMutablePointer<GLfloat>
类型可以通过下标访问其元素,就像普通数组一样。为了实现将这些转换为 CGPoints 的目标,我将使用以下代码:
filter.cornersDetectedBlock = { (cornerArray:UnsafeMutablePointer<GLfloat>, cornersDetected:UInt, frameTime:CMTime) in
var points = [CGPoint]()
for index in 0..<Int(cornersDetected) {
points.append(CGPoint(x:CGFloat(cornerArray[index * 2]), y:CGFloat(cornerArray[(index * 2) + 1])))
}
// Do something with these points
}
内存支持cornerArray
在触发回调之前立即分配,并在回调之后立即释放。除非你像我上面所做的那样将这些值复制到块的中间,否则恐怕你会让自己受到一些讨厌的错误的影响。无论如何,在这一点上转换为正确的格式也更容易。
我找到了一个解决方案 - 而且很简单。 答案就在这里 https://gist.github.com/kirsteins/6d6e96380db677169831
var dataArray = Array(UnsafeBufferPointer(start: cornerArray, count: Int(cornersDetected) * 2))
试试这个:
var cornerPointer = UnsafeMutablePointer<GLfloat>.alloc(Int(cornersDetected) * 2)
filter.cornersDetectedBlock = {(cornerArray:UnsafeMutablePointer<GLfloat>, cornersDetected:UInt, frameTime:CMTime) in
crosshairGenerator.renderCrosshairsFromArray(cornerArray, count:cornersDetected, frameTime:frameTime)
for i in 0...cornersDetected
{
print("(cornerPointer[i])")
}