- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我刚开始弄乱图像处理,我遇到了几个非常奇怪的问题,或者至少我认为是这样。我假设我犯了一些非常愚蠢的错误。
我本来打算就此发布另一个问题,但是使用下面的代码有时我也会得到随机噪声,而不是用户抽取数字的像素表示。如果有人能告诉我为什么会发生这种情况,我将不胜感激。我很难找出原因,因为我阅读的所有内容都表明这段代码应该有效。
如果有人需要更多信息,请告诉我!提前感谢您的帮助!
目标:
首先,获取用户在屏幕上绘制的数字。然后,将图像大小调整为 28 x 28。接下来,将图像转换为灰度并获得归一化像素值数组。最后,将归一化的灰度像素值输入机器学习算法。
[注意:在下图中,点代表 0 值,1 代表值 > 0。]
下面代码的输出效果很好。如果用户画了一个“3”,我通常会得到如下结果:
问题:
如果我将 UnsafeMutablePointer 和 Buffer 的大小更改为 UInt8,我会得到看起来像随机噪声的东西。或者,如果我用 [UInt32](repeating: 0, count: totalBytes)
甚至 [UInt8](repeating: 0, count: totalBytes)
替换 UnsafeMutablePointer 和 Buffer pixel最后变成了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)
}
最佳答案
您的代码中有一件非常糟糕的事情是这一行:
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) 在当前的 Swift 实现中,UInt8
可能不需要 deinitialize
,但顺序:allocate - initialize - deinitilize - deallocate 是推荐的方式.
(其他一些行只是我的偏好,并不重要。)
否则,如果你想使用 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()
}
在归一化灰度为 float 时,1.0
是白色的值,您最好将非白色显示为 1
。 (或者,找到另一个更好的阈值。)
关于ios - CoreGraphics - 无法将 UnsafeMutablePointer<UInt32> 替换为 UnsafeMutablePointer<UInt8>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092616/
Xcode 10 更改了搜索头文件的方法。具体来说,它给出了警告: Traditional headermap style is no longer supported; please migrate
我的基于 Objective-C 的项目中有一些 swift 代码文件。 我可以编译它,它们相互配合得很好。 swift 代码可以 导入 CoreGraphics.CGBase 然而,当我在调试swi
我的形状周围有这条线: 问题是,它的厚度显然从 1px 变成了 2px。这是我正在使用的代码: CGContextRef context = UIGraphicsGetCurrentContext()
我有以下代码,似乎唯一使用整行的最后一种颜色......我希望颜色在整个过程中不断变化。有什么想法吗? CGContextSetLineWidth(ctx, 1.0);
我试图在 CG 中获得透明背景,但它总是显示为黑色。 我有以下代码: - (id)initWithFrame:(CGRect)frame { if ((self = [super initWi
我使用以下代码对加载的图像执行一些操作,但我发现在视网膜显示屏上时显示变得模糊 - (UIImage*)createImageSection:(UIImage*)image section:(CGRe
我正在尝试绘制具有2px透明边框的图像: CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(
我已经使用CoreGraphics绘制了两个四边形(4面)形状的路径。总共有6个点,path1使用前4个点,path2使用后4个点,因此都共享2个点。 代码如下 - (void)drawRect:(C
我正在编写一个左侧有图例的 ViewController(标签和彩色框的垂直列表:Category1:黄色,Category2:gree,Category 3:蓝色,等等......) 用户可以点击列
我的形状周围有这条线: 问题是,它的厚度显然从 1px 变成了 2px。这是我正在使用的代码: CGContextRef context = UIGraphicsGetCurrentContext()
我有一个名为 myView 的 UIView @interface MyView : UIView { UIImage *myPic; NSMutableArray *myDra
我需要帮助来绘制这样的东西: 有人告诉我,灰色背景条和紫色条应该绘制在不同的图层上。然后,表示一本书章节(此 slider 所涉及的内容)的点将位于这两层之上的一层上。 我已经完成了在事件栏上创建渐变
有人可以帮我用 CoreGraphics 绘制一个特定的渐变吗?只要给出线索就足够了。示例代码值得我致以最深的敬意。我需要这个形状: 我尝试了以下代码: -(UIImage *)imageWithGr
我的 CGContext 有一个路径和一个线宽,这在我的 UIView 中绘制了一个漂亮的黑色路径轮廓。 .伟大的。现在我试着给这个笔划上色,虽然 CGContextSetStrokeColorWit
我有一个UIBezierPath,它是一个弧线。我只想在图形上下文中绘制笔划(即圆弧的笔划,不包括连接圆弧终点和起点的线) 完成此操作后,我可以向上下文添加线性渐变,从而有效地在圆弧笔划上绘制渐变。
我正在尝试使用核心图形创建两个矩形路径。当我尝试使用颜色填充路径时,重叠的路径不会填充颜色。 使用的代码是 - (void)drawRect:(CGRect)rect { CGPoint to
编辑:我认为最好的是将代码转换为 CoreAnimation。该代码将如何转换为该方法?我认为问题在于设备 FPS 存在差异。 我一直在为 iOS 搜索自定义进度圈并遇到这个库:https://git
我肯定遗漏了 Core Graphics 上下文的某些部分,无法自行清除。这是我在 Xcode Playground 中的代码 import UIKit class MyView08 : UIView
我不确定是否可以提高图像质量,但以下代码在 PDF 中显示的图像质量非常差。我知道它用于从 View 生成图像的标准代码,但我可以做些什么来指定图像质量或改进它吗? - (void)renderVie
此代码来自 Apple 的 WWDC 2011 session 318 - 深入了解 iOS 性能并使用 CoreGraphics 从服务器托管图像创建缩略图。 CGImageSourceRef sr
我是一名优秀的程序员,十分优秀!