我正在生成图像直方图,将jpeg文件读入24位数组,并将其转换为32位numpy数组以进行处理数字直方图,遵循此方法:
img=imread(file,'RGB')
by=img.tobytes()
struct.iter_unpack('<3B',by)
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')
解决方案:
相关问题 更多 >
编程相关推荐