简体   繁体   English

将 python wand hdr 图像转换为 numpy 数组并返回

[英]Convert python wand hdr image to numpy array and back

Python wand supports converting images directly to a Numpy arrays, such as can be seen in related questions . Python wand 支持将图像直接转换为 Numpy 数组,如相关问题中可以看到。

However, when doing this for .hdr (high dynamic range) images, this appears to compress the image to 0/255.但是,在为.hdr (高动态范围)图像执行此操作时,这似乎会将图像压缩到 0/255。 As a result, converting from a Python Wand image to a np array and back drastically reduces file size/quality.因此,从 Python Wand 图像转换为 np 数组并返回会大大减少文件大小/质量。

# Without converting to a numpy array 
img = Image('image.hdr') # Open with Python Wand Image
img.save(filename='test.hdr') # Save with Python wand

Running this opens the image and saves it again, which creates a file with a size of 41.512kb.运行它会打开图像并再次保存,这会创建一个大小为 41.512kb 的文件。 However, if we convert it to numpy before saving it again..但是,如果我们在再次保存之前将其转换为 numpy..

# With converting to a numpy array 
img = Image(filename=os.path.join(path, 'N_SYNS_89.hdr')) # Open with Python Wand Image
arr = np.asarray(img, dtype='float32') # convert to np array
img = Image.from_array(arr)            # convert back to Python Wand Image
img.save(filename='test.hdr') # Save with Python wand

This results in a file with a size of 5.186kb.这会生成一个大小为 5.186kb 的文件。

Indeed, if I look at arr.min() and arr.max() I see that the min and max values for the numpy array are 0 and 255. If I open the .hdr image with cv2 however as an numpy array, the range is much higher.事实上,如果我查看arr.min()arr.max() ,我会发现 numpy 数组的最小值和最大值分别为 0 和 255。如果我使用 cv2 打开.hdr图像作为 numpy 数组,则范围要高得多。

img = cv2.imread('image.hdr'), -1)
img.min() # returns 0
img.max() # returns 868352.0 

Is there a way to convert back and forth between numpy arrays and Wand images without this loss?有没有办法在 numpy 数组和 Wand 图像之间来回转换而不会造成这种损失?

As per the comment of @LudvigH, the following worked as in this answer .根据@LudvigH 的评论,以下内容与此答案相同。

img = Image(filename='image.hdr')) 
img.format = 'rgb' 
img.alpha_channel = False # was not required for me, including it for completion
img_array = np.asarray(bytearray(img.make_blob()), dtype='float32')

Now we much reshape the returned img_array .现在我们对返回的img_array进行了很多重塑。 In my case I could not run the following在我的情况下,我无法运行以下

img_array.reshape(img.shape)  

Instead, for my img.size was a (x,y) tuple that should have been an (x,y,z) tuple.相反,对于我的img.size是一个 (x,y) 元组,它应该是一个 (x,y,z) 元组。

n_channels = img_array.size / img.size[0] / img.size[1]
img_array = img_array.reshape(img.size[0],img.size[1],int(n_channels))

After manually calculating z as above, it worked fine.如上所述手动计算 z 后,它工作正常。 Perhaps this is also what caused the original fault in converting using arr = np.asarray(img, dtype='float32')也许这也是导致使用arr = np.asarray(img, dtype='float32')转换的原始错误的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM