我有一个 C 函数,它对 8 位 RGB 值的原始二维数组进行一些像素操作。我在 c_ubyte
数组中得到响应。我的代码大致如下所示:
from ctypes import cdll, CDLL, Structure, byref, c_utype, c_uint
# get a reference to the C shared library
cdll.loadLibrary(path_to_my_c_lib)
myclib = CDLL(path_to_my_c_lib)
# define the ctypes version of the C image that would look something like:
# struct img {
# unsigned char data[MAX_IMAGE_SIZE];
# unsigned int width;
# unsigned int height;
# }
class Img(Structure): _fiels_ = [
('data', c_ubyte * MAX_IMAGE_SIZE),
('width', c_uint),
('height', c_uint),
]
# create a blank image, all pixels are black
img = Image()
img.width = WIDTH
img.height = HEIGHT
# call the C function which would look like this:
# void my_pixel_manipulation_function(struct img *)
# and would now work its magic on the data
myclib.my_pixel_manipulation_function(byref(img))
此时我想使用 PIL 将图像写入文件。我目前使用以下代码将字节数据转换为图像数据:
from PIL import Image
s = ''.join([chr(c) for c in img.data[:(img.width*img.height*3)]])
im = Image.fromstring('RGB', (img.width, img.height), s)
# now I can...
im.save(filename)
这行得通,但对我来说似乎效率很低。在 2.2GHz Core i7 上拍摄 592x336 图像需要 125 毫秒。当图像可能直接从数组中获取时,遍历整个数组并执行这种荒谬的字符串连接似乎相当愚蠢。
我尝试寻找将 c_ubyte
数组转换为字符串的方法,或者可能使用 Image.frombuffer
而不是 Image.fromstring
但无法'让这个工作。
最佳答案
我不是 PIL 用户,但通常,frombuffer 方法是为这种工作设计的:
你测试过 Image.frombuffer 了吗?
http://effbot.org/imagingbook/image.htm
编辑:
显然有时解决方案就在我们眼皮底下:
im = Image.frombuffer('RGB', (img.width, img.height), buff, 'raw', 'RGB', 0, 1)
im.save(filename)
顺便说一句,使用frombuffer
的简写形式:
im = Image.frombuffer('RGB', (img.width, img.height), buff)
生成上下颠倒的图片。去图...
关于python - 使用 PIL.Image 和 ctypes 进行像素操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6368645/