从 NSImage 获取像素和颜色
我创建了一个 NSImage 对象,理想情况下想确定它包含多少个像素颜色。这可能吗?
I have created an NSImage object, and ideally would like to determine how many of each pixels colour it contains. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
此代码将
NSImage
渲染为CGBitmapContext
:给定位图上下文,我们可以直接访问原始图像数据,并计算每个颜色通道的直方图:
我已经发布一个完整的项目,一个Cocoa示例应用程序,其中包括上述内容。
This code renders the
NSImage
into aCGBitmapContext
:Given a bitmap context, we can access the raw image data directly, and compute the histograms for each colour channel:
I've published a complete project, a Cocoa sample app, which includes the above.
我建议创建您自己的位图上下文,将其包装在图形上下文并将其设置为当前上下文,告诉图像自行绘制,然后直接访问位图上下文后面的像素数据。
这将需要更多代码,但可以节省您的 TIFF 表示和创建数千或数百万个 NSColor 对象的麻烦。如果您处理任何可观尺寸的图像,这些费用将会迅速增加。
I suggest creating your own bitmap context, wrapping it in a graphics context and setting that as the current context, telling the image to draw itself, and then accessing the pixel data behind the bitmap context directly.
This will be more code, but will save you both a trip through a TIFF representation and the creation of thousands or millions of NSColor objects. If you're working with images of any appreciable size, these expenses will add up quickly.
获取
NSBitmapImageRep< /code>
来自您的
NSImage
。然后你就可以访问像素了。Get an
NSBitmapImageRep
from yourNSImage
. Then you can get access to the pixels.在 Core Image 文档中查找“直方图”。
Look for "histogram" in the Core Image documentation.
将
colorAtX
与NSBitmapImageRep
一起使用并不总是会产生完全正确的颜色。我设法用这个简单的代码获得正确的颜色:
Using
colorAtX
withNSBitmapImageRep
does not always lead to the exact correct color.I managed to get the correct color with this simple code:
对于某些人来说,这可能是一种更简化的方法,并降低了内存管理的复杂性。
https://github.com/koher/EasyImagy
代码示例
https://github.com/koher/EasyImagyCameraSample
This maybe a more streamlined approach for some and reduce complexity of dropping into memory management.
https://github.com/koher/EasyImagy
Code sample
https://github.com/koher/EasyImagyCameraSample