使用PIL.Image和ctypes进行像素处理

编程入门 行业动态 更新时间:2024-10-25 02:28:32
本文介绍了使用PIL.Image和ctypes进行像素处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个C函数,可以对8位RGB值的原始2D数组进行一些像素处理.我在c_ubyte数组中得到响应.我的代码大致如下:

I have a C function that does some pixel manipulation on a raw 2D array of 8 bit RGB values. I get the response in a c_ubyte array. My code looks roughly like this:

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将图像写入文件.我目前使用以下代码将字节数据转换为图像数据:

At this point I'd like to use PIL to write the image to file. I currently use the following code to convert the byte data to image data:

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可能直接从数组中获取数据时,遍历整个数组并执行此荒谬的字符串联接似乎很愚蠢.

This works but seems awfully inefficient to me. It takes 125ms for a 592x336 image on a 2.2GHz Core i7. It seems rather silly to iterate over the entire array and do this ridiculous string join when Image could probably grab directly from the array.

我尝试寻找将c_ubyte数组转换为字符串的方法,或者可能使用Image.frombuffer而不是Image.fromstring,但是无法实现此目的.

I tried looking for ways to cast the c_ubyte array to a string or maybe use Image.frombuffer instead of Image.fromstring but couldn't make this work.

推荐答案

我不是PIL用户,但是通常,frombuffer方法是为此类工作而设计的:

I am not a PIL user, but usually, the frombuffer methods are designed for this kind of job:

您是否已经测试过Image.frombuffer?

Have you tested Image.frombuffer?

effbot/imagingbook/image.htm

显然,有时候解决方案就在我们的鼻子下面:

Apparently sometime the solution is right under our noses:

im = Image.frombuffer('RGB', (img.width, img.height), buff, 'raw', 'RGB', 0, 1) im.save(filename)

顺便说一下,使用frombuffer的简写形式:

By the way, using the shorthand form of frombuffer:

im = Image.frombuffer('RGB', (img.width, img.height), buff)

生成一张颠倒的图片.走吧...

generates an upside-down picture. Go figure...

更多推荐

使用PIL.Image和ctypes进行像素处理

本文发布于:2023-06-08 06:33:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/576178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:像素   PIL   Image   ctypes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!