【问题标题】:Accurately get a color from pixel on screen and convert its color space从屏幕上的像素中准确获取颜色并转换其颜色空间
【发布时间】:2018-04-08 06:36:29
【问题描述】:

我需要从屏幕上的像素中获取颜色并转换其颜色空间。我遇到的问题是,在将值与 Digital Color Meter 应用程序进行比较时,颜色值不一样。

// create a 1x1 image at the mouse position
if let image:CGImage = CGDisplayCreateImage(disID, rect: CGRect(x: x, y: y, width: 1, height: 1))
{
    let bitmap = NSBitmapImageRep(cgImage: image)

    // get the color from the bitmap and convert its colorspace to sRGB
    var color = bitmap.colorAt(x: 0, y: 0)!
    color     = color.usingColorSpace(.sRGB)!

    // print the RGB values
    let red = color.redComponent, green = color.greenComponent, blue = color.blueComponent
    print("r:", Int(red * 255), " g:", Int(green * 255), " b:", Int(blue * 255))
}

我的代码(转换为 sRGB):255, 38, 0
数字色度计(sRGB):255, 4, 0

如何从屏幕上的像素中获得具有正确颜色空间值的颜色?


更新:

如果您不将颜色空间转换为任何颜色空间(或将其转换为经过校准的 RGB),则当数字色度计设置为“显示原生值”时,这些值会与数字色度计的值匹配。

我的代码(未转换):255, 0, 1
数字色度计(设置为:显示原生值):255, 0, 1

那么,为什么当颜色值与 DCM 应用程序中的本机值匹配时,将颜色转换为 sRGB 并将其与 DCM 的值(在 sRGB 中)不匹配?我还尝试转换为其他色彩空间,但总是与 DCM 不同。

【问题讨论】:

  • 需要注意和尝试的事情,尽管我不知道它是否会对最终结果产生影响:有一个 AppKit 函数可以读取像素的颜色值而不创建图像。这是NSReadPixel()
  • 不幸的是,这仅适用于您自己的应用程序窗口本身,而不是整个显示。
  • 尝试比较 colour 的组件值,而不将其与 DCM 的本机值进行转换。可能由于某种原因,您的代码和 DCM 正在执行与原始像素值不同的转换。

标签: swift macos cocoa colors


【解决方案1】:

好的,我可以告诉你如何修复它/匹配 DCM,你必须确定这是否正确/错误/等等。

colorAt() 返回的颜色似乎与位图的像素具有相同的分量值,但颜色空间不同 - 而不是原始设备颜色空间,它是通用 RGB 空间。我们可以通过在位图空间中构建颜色来“纠正”这个问题:

let color = bitmap.colorAt(x: 0, y: 0)!

// need a pointer to a C-style array of CGFloat
let compCount = color.numberOfComponents
let comps = UnsafeMutablePointer<CGFloat>.allocate(capacity: compCount)
// get the components
color.getComponents(comps)
// construct a new color in the device/bitmap space with the same components
let correctedColor = NSColor(colorSpace: bitmap.colorSpace,
                             components: comps,
                             count: compCount)
// convert to sRGB
let sRGBcolor = correctedColor.usingColorSpace(.sRGB)!

我想你会发现correctedColor 的值跟踪 DCM 的原生值,而sRGBcolor 的值跟踪 DCM 的 sRGB 值。

请注意,我们是在设备空间中构造一种颜色,而不是将颜色转换到设备空间。

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多