[英]Pixel manipulation with PIL.Image and ctypes
我有一個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圖像需要125ms。 當Image可能直接從數組中獲取時,迭代整個數組並執行這種荒謬的字符串連接似乎相當愚蠢。
我試圖找到將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)
產生一個倒置的圖片。 去搞清楚...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.