python jpeg文件24到32位转换

时间:2017-12-24 08:13:53

标签: python jpeg bit

生成图像直方图,将jpeg文件读入24位数组并将其转换为32位numpy文件,以便使用numpy.histogram进行处理,遵循以下方法:

  • 将文件读成numpy数组形状:(w,h,3) - > img=imread(file,'RGB')
  • 转换为字节块大小:w * h * 3 - > by=img.tobytes()
  • 使用struct iterator解压缩 - &gt; struct.iter_unpack('<3B',by)
  • 转换为int - &gt; 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())])

其他较慢的实现:

 def conversionSLOW(fnme):  # reshape to (w*h,3)
    img = imread(fnme, mode='RGB')
    return np.array([int.from_bytes(c, byteorder='big')
                     for c in img.reshape((img.shape[0] * img.shape[1], 3))])

def conversionbyte01(fnme): # int iteration -> closer to fastests
    by = imread(fnme, mode='RGB').tobytes()
    return np.asanyarray([int.from_bytes(by[c:c + 3], byteorder='big')
                          for c in range(0, len(by) - 3, 3)],
                         dtype=np.int32)

def conversionbyte02(fnme):
    img = imread(fnme)
    return np.array([int.from_bytes(c, byteorder='big') for c in img.reshape(img.shape[0] * img.shape[1], 3)])

def conversionbyte03(fnme):
    img = imread(fnme)
    return np.array([int.from_bytes(img.reshape(img.shape[0] * img.shape[1], 3), byteorder='big')])

EDIT1:

找到一个解决方案,创建一个(w,h,4)numpy数组并复制读取图像,休息简单快速( 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')

1 个答案:

答案 0 :(得分:1)

溶液:

    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')