Python支持将图像直接转换为Numpy数组,如在related questions中可以看到。
但是,当对.hdr (高动态范围)图像执行此操作时,这似乎会将图像压缩到0/255。因此,将Python图像转换为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运行此操作将打开图像并再次保存它,这将创建一个大小为41.512kb的文件。但是,如果我们在再次保存之前将它转换为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这将导致一个大小为5.186kb的文件。
实际上,如果我查看arr.min()和arr.max(),就会发现numpy数组的min值和最大值分别为0和255。但是,如果我使用.hdr作为numpy数组打开cv2图像,则范围要高得多。
img = cv2.imread('image.hdr'), -1)
img.min() # returns 0
img.max() # returns 868352.0 有没有一种方法可以在numpy数组和Wand图像之间来回转换而不丢失?
发布于 2022-06-01 22:24:18
根据@路德维希的评论,以下内容在this answer中起了作用。
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进行了很大的改造。在我的例子中,我无法运行以下命令
img_array.reshape(img.shape) 相反,对于我的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))在手动计算z之后,它工作得很好。也许这也是导致使用arr = np.asarray(img, dtype='float32')进行转换时的原始错误的原因。
https://stackoverflow.com/questions/72455730
复制相似问题