将CGImageRef转换为PIL

时间:2015-02-28 06:40:15

标签: python macos python-imaging-library cgimage python-mss

如何在不将图像保存到osx上的磁盘的情况下将CGImageRef转换为PIL?

我虽然从CGImageRef获取原始像素数据并使用Image.fromstring()通过执行

来制作PIL图像
import mss
import Quartz.CoreGraphics as CG
from PIL import Image

mss = mss.MSSMac()
for i, monitor in enumerate(mss.enum_display_monitors(0)):
    imageRef = mss.get_pixels(monitor)
    pixeldata = CG.CGDataProviderCopyData(CG.CGImageGetDataProvider(imageRef))
    img = Image.fromstring("RGB", (monitor[b'width'], monitor[b'height']), pixeldata)
    img.show()

但这并没有给我正确的图像。

这是我期待的图像:

enter image description here

这是我在PIL中获得的图片:

enter image description here

2 个答案:

答案 0 :(得分:0)

来自CG的屏幕捕获不一定使用RGB色彩空间。它可能使用RGBA或其他东西。尝试更改:

img = Image.fromstring("RGB", (monitor[b'width'], monitor[b'height']), pixeldata)

img = Image.fromstring("RGBA", (monitor[b'width'], monitor[b'height']), pixeldata)

以下是我如何检测实际捕获的色彩空间:

bpp = CG.CGImageGetBitsPerPixel(imageRef)
info = CG.CGImageGetBitmapInfo(imageRef)
pixeldata = CG.CGDataProviderCopyData(CG.CGImageGetDataProvider(imageRef))

img = None
if bpp == 32:
    alphaInfo = info & CG.kCGBitmapAlphaInfoMask
    if alphaInfo == CG.kCGImageAlphaPremultipliedFirst or alphaInfo == CG.kCGImageAlphaFirst or alphaInfo == CG.kCGImageAlphaNoneSkipFirst:
        img = Image.fromstring("RGBA", (CG.CGImageGetWidth(imageRef), CG.CGImageGetHeight(imageRef)), pixeldata, "raw", "BGRA")
    else:
        img = Image.fromstring("RGBA", (CG.CGImageGetWidth(imageRef), CG.CGImageGetHeight(imageRef)), pixeldata)
elif bpp == 24:
    img = Image.fromstring("RGB", (CG.CGImageGetWidth(imageRef), CG.CGImageGetHeight(imageRef)), pixeldata)

答案 1 :(得分:0)

这是我前一段时间修复的错误。以下是如何使用最新的from mss.darwin import MSS from PIL import Image with MSS() as mss: for monitor in mss.enum_display_monitors(0): pixeldata = mss.get_pixels(monitor) img = Image.frombytes('RGB', (mss.width, mss.height), pixeldata) img.show() 版本(2.0.22)实现您的目标:

pixeldata

请注意,mss.image只是对minHeight的引用,您可以直接使用它。