首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从灰度值重建灰度图像?

如何从灰度值重建灰度图像?
EN

Stack Overflow用户
提问于 2016-01-08 12:26:26
回答 2查看 1.4K关注 0票数 2

通常需要从图像中获取像素数据或从像素数据中重建该图像。如何获取图像,将其转换为像素值数组,然后使用Swift中的像素数组使用CoreGraphics进行重建?

这个问题的答案的质量到处都是,所以我想要一个典型的答案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-08 12:26:26

获取像素值作为数组

这一功能可以很容易地扩展到彩色图像。为了简单起见,我使用的是灰度,但我已经对更改进行了注释,以获得RGB。

代码语言:javascript
复制
func pixelValuesFromImage(imageRef: CGImage?) -> (pixelValues: [UInt8]?, width: Int, height: Int)
{
    var width = 0
    var height = 0
    var pixelValues: [UInt8]?
    if let imageRef = imageRef {
        let totalBytes = imageRef.width * imageRef.height
        let colorSpace = CGColorSpaceCreateDeviceGray()
        
        pixelValues = [UInt8](repeating: 0, count: totalBytes)
        pixelValues?.withUnsafeMutableBytes({
            width = imageRef.width
            height = imageRef.height
            let contextRef = CGContext(data: $0.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, space: colorSpace, bitmapInfo: 0)
            let drawRect = CGRect(x: 0.0, y:0.0, width: CGFloat(width), height: CGFloat(height))
            contextRef?.draw(imageRef, in: drawRect)
        })
    }

    return (pixelValues, width, height)
}

从像素值获取图像

我重建一幅图像,在这种情况下,每像素8位灰度,返回到一个CGImage.

代码语言:javascript
复制
func imageFromPixelValues(pixelValues: [UInt8]?, width: Int, height: Int) ->  CGImage?
{
    var imageRef: CGImage?
    if let pixelValues = pixelValues {
        let bitsPerComponent = 8
        let bytesPerPixel = 1
        let bitsPerPixel = bytesPerPixel * bitsPerComponent
        let bytesPerRow = bytesPerPixel * width
        let totalBytes = width * height
        let unusedCallback: CGDataProviderReleaseDataCallback = { optionalPointer, pointer, valueInt in }
        let providerRef = CGDataProvider(dataInfo: nil, data: pixelValues, size: totalBytes, releaseData: unusedCallback)

        let bitmapInfo: CGBitmapInfo = [CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), CGBitmapInfo(rawValue: CGImageByteOrderInfo.orderDefault.rawValue)]
        imageRef = CGImage(width: width,
                           height: height,
                           bitsPerComponent: bitsPerComponent,
                           bitsPerPixel: bitsPerPixel,
                           bytesPerRow: bytesPerRow,
                           space: CGColorSpaceCreateDeviceGray(),
                           bitmapInfo: bitmapInfo,
                           provider: providerRef!,
                           decode: nil,
                           shouldInterpolate: false,
                           intent: .defaultIntent)
    }

    return imageRef
}

在游乐场中演示代码

您将需要将图像复制到Playground的Resources文件夹中,然后将下面的文件名和扩展名更改为匹配。最后一行的结果是从UIImage构造的CGImage。

代码语言:javascript
复制
import Foundation
import CoreGraphics
import UIKit
import PlaygroundSupport

let URL = playgroundSharedDataDirectory.appendingPathComponent("zebra.jpg")
print("URL \(URL)")

var image: UIImage? = nil
if FileManager().fileExists(atPath: URL.path) {
    do {
        try NSData(contentsOf: URL, options: .mappedIfSafe)
    } catch let error as NSError {
        print ("Error: \(error.localizedDescription)")
    }
    image = UIImage(contentsOfFile: URL.path)
} else {
    print("File not found")
}

let (intensityValues, width, height) = pixelValuesFromImage(imageRef: image?.cgImage)
let roundTrippedImage = imageFromPixelValues(pixelValues: intensityValues, width: width, height: height)
let zebra = UIImage(cgImage: roundTrippedImage!)
票数 5
EN

Stack Overflow用户

发布于 2020-12-09 01:30:19

我很难让Cameron上面的代码起作用,所以我想测试另一种方法。我找到了Vacawama's code,它依赖于ARGB像素。您可以使用该解决方案并将每个灰度值转换为ARGB值,只需对每个值进行映射:

代码语言:javascript
复制
/// Assuming grayscale pixels contains floats in the range 0...1
let grayscalePixels: [Float] = ...
let pixels = grayscalePixels.map { 
  let intensity = UInt8(round($0 / Float(UInt8.max)))
  return PixelData(a: UInt8.max, r: intensity, g: intensity, b: intensity)
}
let image = UIImage(pixels: pixels, width: width, height: height)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34677133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档