目前正在尝试使用C完成以前在python(pypy)中完成的任务。我想我应该试着用C语言写它(以获得最佳的速度),然后使用C类型进行通信。
现在我要做的是从位图(bmp文件)中获取pixelbuffer,将其发送到C函数,该函数将原始缓冲区转换为R、G、B值的平面数组,并将其返回给python。但是当我试图把“缓冲区”转换成R,G,B值时,我就卡住了。
在python中,我只需要使用“struct”模块:B,G,R = struct.unpack('<BBB', buffer[i:i+3])
在C语言中我应该怎么做?
蟒蛇:

from bmplib import Bitmap
import ctypes
lib = ctypes.CDLL('_bitmap.dll')

bmp = Bitmap()
bmp.open('4x4.bmp')
buf = bmp._rawAsArray() #Returns a array.array() of char (raw pixel-data)

addr, count = buf.buffer_info()
lib.getData.argtypes = []

arr = ctypes.cast(addr, ctypes.POINTER(ctypes.c_char))
lib.getData(arr, count) #Does not return anything yet..

C尝试转换像素失败:
#include <stdio.h>

void getData(char *, const int);
void getData(char * array, const int length) {
  int i = 0;
  while(i < length) {
    /* ----- Clearly wrong as i got some HUGE number----- */
    printf("%d, ", ((int *) array)[i]   << 8); //B
    printf("%d, ", ((int *) array)[i+1] << 8); //G
    printf("%d\n", ((int *) array)[i+2] << 8); //R
    i += 3;
  }
  //return total;
}

最佳答案

您正在执行array[i] << 8操作,这与向左移动array[i]8位或将array[i]乘以256相同。这就是为什么你会得到这么大的数字。去掉<< 8你应该没事的。
另外,在取消对数组的引用后,将类型转换为int。应该是(int)array[i]

关于python - 在C中解压缩(r,g,b)原始像素缓冲区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15955226/

10-09 02:13
查看更多