python jpeg文件24到32位转换

问题描述 投票:0回答:1

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

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

其他较慢的实现:

 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')
python jpeg bit
1个回答
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')
© www.soinside.com 2019 - 2024. All rights reserved.