CoreGraphics - 不能用 UnsafeMutablePointer<UInt8> 替换 UnsafeMutablePointer<UInt32>

Posted

技术标签:

【中文标题】CoreGraphics - 不能用 UnsafeMutablePointer<UInt8> 替换 UnsafeMutablePointer<UInt32>【英文标题】:CoreGraphics - Can't replace UnsafeMutablePointer<UInt32> with UnsafeMutablePointer<UInt8> 【发布时间】:2017-05-21 02:33:42 【问题描述】:

我刚开始搞乱图像处理,我遇到了一些非常奇怪的问题,或者至少我认为它们是。我假设我犯了一些非常愚蠢的错误。

我打算发布另一个关于此的问题,但是,使用下面的代码,有时我也会得到随机噪声,而不是用户绘制数字的像素表示。如果有人能告诉我为什么会发生这种情况,我将不胜感激。我很难找出原因,因为我阅读的所有内容都表明该代码应该可以工作。

如果有人需要更多信息,请告诉我!提前感谢您的帮助!

目标: 首先,获取用户在屏幕上绘制的数字。然后,将图像大小调整为 28 x 28。接下来,将图像转换为灰度,并获取归一化像素值的数组。最后,将归一化的灰度像素值输入机器学习算法。

[注意:在下图中,点代表 0 值,1 代表值 > 0。]

以下代码的输出运行良好。如果用户画一个“3”,我通常会得到如下内容:

问题:

如果我将 UnsafeMutablePointer 和 Buffer 的大小更改为 UInt8,我会得到看起来像随机噪声的东西。或者如果我用[UInt32](repeating: 0, count: totalBytes) 甚至[UInt8](repeating: 0, count: totalBytes) 替换 UnsafeMutablePointer 和 Buffer,每个像素最终都为 0,我真的不明白。

如果我将 UnsafeMutablePointer 和 Buffer 的大小更改为 UInt8,这是像素的输出:

获取灰度像素的代码:

public extension UIImage

    private func grayScalePixels() -> UnsafeMutableBufferPointer<UInt32>?
    
        guard let cgImage = self.cgImage else  return nil 

        let bitsPerComponent = 8
        let width = cgImage.width
        let height = cgImage.height
        let totalBytes = (width * height)
        let colorSpace = CGColorSpaceCreateDeviceGray()
        let data = UnsafeMutablePointer<UInt32>.allocate(capacity: totalBytes)
        defer  data.deallocate(capacity: totalBytes) 

        guard let imageContext = CGContext(data: data, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: width, space: colorSpace, bitmapInfo: 0) else  return nil 
        imageContext.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: height)))

        return UnsafeMutableBufferPointer<UInt32>(start: data, count: totalBytes)
    

    public func normalizedGrayScalePixels() -> [CGFloat]?
    
        guard let cgImage = self.cgImage else  return nil 
        guard let pixels = self.grayScalePixels() else  return nil 

        let width = cgImage.width
        let height = cgImage.height
        var result = [CGFloat]()

        for y in 0..<height
        
            for x in 0..<width
            
                let index = ((width * y) + x)
                let pixel = (CGFloat(pixels[index]) / 255.0)
                result.append(pixel)
            
        

        return result
    

绘制数字的代码:

    func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint)
    
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 1)

        self.tempImageView.image?.draw(at: CGPoint.zero)

        let context = UIGraphicsGetCurrentContext()
        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)
        context?.setLineCap(.round)
        context?.setLineWidth(self.brushWidth)
        context?.setStrokeColor(gray: 0, alpha: 1)
        context?.strokePath()

        self.tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        self.tempImageView.alpha = self.opacity

        UIGraphicsEndImageContext()
    

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    
        self.swiped = false

        if let touch = touches.first 
            self.lastPoint = touch.location(in: self.view)
        
    

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
    
        self.swiped = true

        if let touch = touches.first
        
            let currentPoint = touch.location(in: self.view)
            self.drawLineFrom(fromPoint: self.lastPoint, toPoint: currentPoint)

            self.lastPoint = currentPoint
        
    

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
    
        if !swiped 
            self.drawLineFrom(fromPoint: self.lastPoint, toPoint: self.lastPoint)
        

        self.predictionLabel.text = "Predication: \(self.predict())"

        self.tempImageView.image = nil
    

预测数字的代码:

    private func printNumber(rowSize: Int, inputs: Vector)
    
        for (index, pixel) in inputs.enumerated()
        
            if index % rowSize == 0  print() 

            if (pixel > 0) 
                print("1", terminator: " ")
            
            else  print(".", terminator: " ") 
        

        print()
    

    private func predict() -> Scalar
    
        let resizedImaege = self.tempImageView.image!.resizedImage(CGSize(width: 28, height: 28), interpolationQuality: .high)
        let inputs = resizedImaege!.normalizedGrayScalePixels()!.flatMap( Scalar($0) )
        self.feedforwardResult = self.neuralNetwork!.feedForward(inputs: inputs)

        self.printNumber(rowSize: 28, inputs: inputs)

        let max = self.feedforwardResult!.activations.last!.max()!
        let prediction = self.feedforwardResult!.activations.last!.index(of: max)!
        return Scalar(prediction)
    

【问题讨论】:

【参考方案1】:

您的代码中有一个非常糟糕的地方是这一行:

    defer  data.deallocate(capacity: totalBytes) 

data.deallocate(capacity: totalBytes) 在退出方法grayScalePixels() 之前执行。所以,返回的UnsafeMutableBufferPointer 中的baseAddress 指向一个已经被释放的区域,这意味着在访问该区域时你不能期望任何可预测的结果。

如果你想使用UnsafeMutableBufferPointer,你需要在完成对它的所有访问后释放区域(下面代码中的#1):

private func grayScalePixels() -> UnsafeMutableBufferPointer<UInt8>? 
    guard let cgImage = self.cgImage else  return nil 
    
    let bitsPerComponent = 8
    let width = cgImage.width
    let height = cgImage.height
    let totalBytes = width * height
    let colorSpace = CGColorSpaceCreateDeviceGray()
    let data = UnsafeMutablePointer<UInt8>.allocate(capacity: totalBytes)
    data.initialize(to: UInt8.max, count: totalBytes)   //<- #4
    
    guard let imageContext = CGContext(data: data, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: width, space: colorSpace, bitmapInfo: 0) else  return nil 
    imageContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
    
    return UnsafeMutableBufferPointer(start: data, count: totalBytes)


public func normalizedGrayScalePixels() -> [CGFloat]? 
    guard let cgImage = self.cgImage else  return nil 
    guard let pixels = self.grayScalePixels() else  return nil 
    
    let width = cgImage.width
    let height = cgImage.height
    var result: [CGFloat] = []
    
    for y in 0..<height 
        for x in 0..<width 
            let index = width * y + x
            let pixel = CGFloat(pixels[index]) / CGFloat(UInt8.max)
            result.append(pixel)
        
    
    pixels.baseAddress!.deinitialize(count: pixels.count)   //<- #2
    pixels.baseAddress!.deallocate(capacity: pixels.count)  //<- #1
    
    return result

(#2) UInt8 在当前的 Swift 实现中可能不需要deinitialize,但推荐的顺序是:分配 - 初始化 - 取消初始化 - 解除分配。

(涉及的其他一些行只是我的偏好,并不重要。)


或者,如果你想使用 Swift Array 而不是 UnsafeMutableBufferPointer,你可以这样写:

private func grayScalePixels() -> [UInt8]? 
    guard let cgImage = self.cgImage else  return nil 
    
    let bitsPerComponent = 8
    let width = cgImage.width
    let height = cgImage.height
    let totalBytes = width * height
    let colorSpace = CGColorSpaceCreateDeviceGray()
    var byteArray: [UInt8] = Array(repeating: UInt8.max, count: totalBytes) //<- #4
    let success = byteArray.withUnsafeMutableBufferPointer (buffer)->Bool in
        guard let imageContext = CGContext(data: buffer.baseAddress!, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: width, space: colorSpace, bitmapInfo: 0) else  return false 
        imageContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        return true;
    
    return success ? byteArray : nil


public func normalizedGrayScalePixels() -> [CGFloat]? 
    guard let cgImage = self.cgImage else  return nil 
    guard let pixels = self.grayScalePixels() else  return nil 
    
    let width = cgImage.width
    let height = cgImage.height
    var result: [CGFloat] = []
    
    for y in 0..<height 
        for x in 0..<width 
            let index = width * y + x
            let pixel = CGFloat(pixels[index]) / CGFloat(UInt8.max)
            result.append(pixel)
        
    
    
    return result


您可能需要修改我上面的代码以使它们与您的代码一起使用,因为我无法使用您的UInt32 版本的grayScalePixels() 重现相同的结果。


编辑

我在我的代码中发现了一个问题。您的绘图代码绘制线条:

    context?.setStrokeColor(gray: 0, alpha: 1)

灰度 0,黑色。在我的旧代码中,我将位图初始化为:

    data.initialize(to: 0, count: totalBytes)

或:

    var byteArray: [UInt8] = Array(repeating: 0, count: totalBytes)

因此,在黑色上绘制黑色,结果:全黑,8 位灰度,全 0。 (我第一次写initialize可能不需要,但那是一个错误。带有alpha的图像将与初始位图内容混合绘制。)

我更新的代码(标有#4)用白色初始化位图(8 位灰度,255 == 0xFF == UInt8.max)。

您最好通过更新printNumber(rowSize:inputs:) 来检测非白色像素:

private func printNumber(rowSize: Int, inputs: Vector) 
    for (index, pixel) in inputs.enumerated() 
        if index % rowSize == 0  print() 
        
        if pixel < 1.0  //<- #4
            print("1", terminator: "")
        
        else  print(".", terminator: "") 
    
    
    print()

在作为浮点数的标准化灰度中,1.0 是白色的值,您最好将非白色显示为 1。 (或者,找到另一个更好的阈值。)

【讨论】:

感谢您的回复!不幸的是,我仍然收到您提供的代码的随机噪音。虽然,你提到的完全有道理,让我相信这是我绘制图像的方式。我已经编辑了我的问题以提供此代码。你介意快速看一下吗?我在 Ray Wenderlich 的网站上找到了它。 另外,如果我保留 data.initialize(to: 0, count: totalBytes) 返回的像素数组全为 0。如果我删除它,我会得到随机噪音。如果我删除它并将指针改回 UInt32,我“大部分”时间都会得到正确的输出。所以,我基本上仍然有同样的问题。对于我更喜欢​​使用的第二段代码,我也得到了全 0。 @Jonathan,我发现我的代码不适用于某些 resize d 图像。显示您的 predict() 的定义会有所帮助。 当然,没问题!我已经用代码编辑了我的问题。此外,这是我获得调整图像大小的代码的地方:vocaro.com/trevor/blog/2009/10/12/… 我尝试过不调整大小,但仍然遇到同样的问题。如果有帮助,我会为原始 CGImage 打印以下内容(不调整大小): bitsPerComponent = 8, bitsPerPixel = 32, bytesPerRow = 128, CFDataGetLength(cgImage.dataProvider!.data) = 3584

以上是关于CoreGraphics - 不能用 UnsafeMutablePointer<UInt8> 替换 UnsafeMutablePointer<UInt32>的主要内容,如果未能解决你的问题,请参考以下文章

CoreGraphics - 用笔划剪裁渐变

Java操作系统硬件的方法Unsafe

不能使用weak修饰进行声明的类

Golang学习 - unsafe 包

在 Java 7 ConcurrentHashMap 中,为啥在写的时候需要段锁?为啥我们不能再次使用 Unsafe 来保持非阻塞?

书法绘图 IOS Coregraphics