首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将python wand hdr图像转换为numpy数组并返回

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

Stack Overflow用户
提问于 2022-06-01 02:01:01
回答 1查看 236关注 0票数 2

Python支持将图像直接转换为Numpy数组,如在related questions中可以看到。

但是,当对.hdr (高动态范围)图像执行此操作时,这似乎会将图像压缩到0/255。因此,将Python图像转换为np数组并返回会大大降低文件的大小/质量。

代码语言:javascript
复制
# Without converting to a numpy array 
img = Image('image.hdr') # Open with Python Wand Image
img.save(filename='test.hdr') # Save with Python wand

运行此操作将打开图像并再次保存它,这将创建一个大小为41.512kb的文件。但是,如果我们在再次保存之前将它转换为numpy。

代码语言:javascript
复制
# 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

这将导致一个大小为5.186kb的文件。

实际上,如果我查看arr.min()arr.max(),就会发现numpy数组的min值和最大值分别为0和255。但是,如果我使用.hdr作为numpy数组打开cv2图像,则范围要高得多。

代码语言:javascript
复制
img = cv2.imread('image.hdr'), -1)
img.min() # returns 0
img.max() # returns 868352.0 

有没有一种方法可以在numpy数组和Wand图像之间来回转换而不丢失?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-01 22:24:18

根据@路德维希的评论,以下内容在this answer中起了作用。

代码语言:javascript
复制
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')

现在我们对返回的img_array进行了很大的改造。在我的例子中,我无法运行以下命令

代码语言:javascript
复制
img_array.reshape(img.shape)  

相反,对于我的img.size是(x,y)元组,应该是(x,y,z)元组。

代码语言:javascript
复制
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))

在手动计算z之后,它工作得很好。也许这也是导致使用arr = np.asarray(img, dtype='float32')进行转换时的原始错误的原因。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72455730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档