我有一个 C 函数,可以对 8 位 RGB 值的原始 2D 数组进行一些像素操作。我得到的答复是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 毫秒。当 Image 可以直接从数组中获取时,迭代整个数组并执行这种荒谬的字符串连接似乎相当愚蠢。
我尝试寻找方法来投射c_ubyte
数组到字符串或者可能使用Image.frombuffer
代替Image.fromstring
但无法完成这项工作。