如何可以轉換兩個字節(UINT8)到半精度(16位)漂浮在夫特,如閱讀CIAreaHistogram與kCIFormatRGBAh輸出時,如在下面的例子中需要:如何將字節轉換爲Swift中的半浮點數?
func areaHistogram(image : UIImage) {
let inputImage = CIImage(image: image)
let totalBytes : Int = bpp * BINS //8 * 64 for example
let bitmap : UnsafeMutablePointer<Void> = calloc(totalBytes, bpp)
let filter = CIFilter(name: "CIAreaHistogram")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
filter.setValue(CIVector(x: 0, y: 0, z: image.size.width, w: image.size.height), forKey: kCIInputExtentKey)
filter.setValue(BINS, forKey: "inputCount")
filter.setValue(1, forKey: "inputScale")
let myEAGLContext = EAGLContext(API: .OpenGLES2)
let options = [kCIContextWorkingColorSpace : kCFNull]
let context : CIContext = CIContext(EAGLContext: myEAGLContext, options: options)
context.render(filter.outputImage!, toBitmap: bitmap, rowBytes: totalBytes, bounds: filter.outputImage!.extent, format: kCIFormatRGBAh, colorSpace: CGColorSpaceCreateDeviceRGB())
let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(bitmap), count: bpp * BINS)
//HOW TO CONVERT TWO CONSECUTIVE BYTES AS 16-BIT FLOATS?
//THIS CODE DOES NOT WORK (I guess because Float in Swift is 32-bit):
for var i=0; i < self.bpp * self.BINS; i+=self.bpp {
let bitsR = UnsafePointer<Float._BitsType>(self.queryHist!)[i+0].bigEndian
let R = Float(Float._fromBitPattern(bitsR))
let bitsG = UnsafePointer<Float._BitsType>(self.queryHist!)[i+2].bigEndian
let G = Float(Float._fromBitPattern(bitsG))
let bitsB = UnsafePointer<Float._BitsType>(self.queryHist!)[i+4].bigEndian
let B = Float(Float._fromBitPattern(bitsB))
print("R/G/B = \(R) \(G) \(B)")
}
free(bitmap)
}
首先,窄下來到你的問題的最簡單可行的娛樂。第二個......你如何期望它能夠正確地形成一個32位浮點數? – nhgrif
首先,我認爲這已經是我的問題的一個非常簡單的娛樂了,因爲據我所知,iOS不會處理16位浮點數(金屬除外),但是對於CIAreaHistogram這種非常特殊的情況。其次,說實話,我不希望它能夠工作,因爲Swift中的Float是32位 - 當然需要4個字節 - 但我找不到除CGFloat之外的16位Float版本(但是,不與UnsafePointer結合使用_BitsType)。 – Klaus