python jpeg文件24到32位的转换

2024-09-29 21:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在生成图像直方图,将jpeg文件读入24位数组,并将其转换为32位numpy数组以进行处理数字直方图,遵循此方法:

  • 将文件读入numpy数组形状:(w,h,3)->>; img=imread(file,'RGB')
  • 转换为字节块大小:w*h*3->;by=img.tobytes()
  • 使用结构迭代器解压->;struct.iter_unpack('<3B',by)
  • 转换为int->;int.from_bytes(c, byteorder='big')

这种方法和我尝试过的其他方法(重塑为w*h,3等)的问题在于迭代器延迟,我的问题是:

在python中是否有一种不使用迭代器的直接方法来实现这一点,或者我应该编写一个简单的C函数来实现这一点?在

 def jpeg2colors(fnme):
    return np.asarray(
        [int.from_bytes(c, byteorder='big')
         for c in struct.iter_unpack('<3B', imread(fnme).tobytes())])

其他较慢的实现:

^{2}$

编辑1:

找到了一个创建(w,h,4)numpy数组并复制读映像的解决方案,rest简单而快速(x40比最快的迭代解决方案改进)

 def fromJPG2_2int32_stbyst(fnme): # step by step
    img = imread(fnme)
    # create a (w,h,4) array and copy original
    re = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint8) 
    re[:, :, :-1] = img
    # lineup to a byte structure ready for ' frombuffer'
    re1 = re.reshape(img.shape[0] * img.shape[1] * 4)
    by = re1.tobytes()
    # got it just convert to int
    cols = np.frombuffer(by, 'I')
    return cols

def fromJPG2_2int32_v0(fnme): # more compact & efficient
    img = imread(fnme)
    re = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint8)
    re[:, :, :-1] = img
    return np.frombuffer(re.reshape(img.shape[0] * img.shape[1] * 4).tobytes(), 'I')

def fromJPG2_2int32(fnme): # even better using numpy.c_[]
    img = imread(fnme)
    img = np.c_[img, np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)]
    return np.frombuffer(img.reshape(img.shape[0] * img.shape[1] * 4).tobytes(), 'I')

Tags: 方法gtrenumpyimgbyreturndef
1条回答
网友
1楼 · 发布于 2024-09-29 21:36:47

解决方案:

    def fromjpg2int32(fnme):  # convert jpg 2 int color array
    img = imread(fnme)
    return np.frombuffer(
        np.insert(img, 3, values=0, axis=2).
            reshape(img.shape[0] * img.shape[1] * 4).tobytes(), 'I')

相关问题 更多 >

    热门问题