【问题标题】:Keep the original shape of the array as the image保持数组的原始形状为图像
【发布时间】:2021-11-16 23:52:35
【问题描述】:

我有一些数据。我将其可视化,然后将其另存为图像。

import cv2
import numpy as np
import matplotlib.pyplot as plt

data = np.array([
[1,2,0,1],
[0,1,2,1],
[0,0,2,1]])

fig, ax = plt.subplots()
ax.imshow(data)
ax.axis('off')
fig.savefig("test.png", bbox_inches='tight', pad_inches=0)

接下来,我加载图像并读取形状:

img = cv2.imread('test.png')
print(img.shape)

输出:

(217, 289, 3)

但我想保持原来的分辨率和我的预期输出:

(3, 4, 3)

有什么办法吗?

更新:

使用 dpi=1:

data = np.array([
    [1,2,0,1],
    [0,1,2,1],
    [0,0,2,1],
    [1,0,2,1],
    [4,1,0,2],
])
fig, ax = plt.subplots()
ax.imshow(data)
ax.axis('off')
fig.savefig("test.png", bbox_inches='tight', pad_inches=0, dpi = 1) 

img = cv2.imread('test.png')
img.shape

print(data.shape, img.shape)

输出:

(5, 4) 
(3, 2, 3)

【问题讨论】:

  • 看起来你想在保存图窗时设置dpi。我想你想要dpi=1

标签: python numpy matplotlib cv2


【解决方案1】:

由于您使用两个不同的库来创建图像和读取图像,因此很难保留数组大小,因为图像中没有存储此类信息。

dpi 也特定于您的显示器屏幕,因此不推荐使用。有关更多信息,请参阅答案here

另外,您正在尝试将图像写入二维数组,但是当cv2.imread() 读取它时,它还会考虑颜色通道并添加第三维。为避免这种情况,您需要将图像读取为灰度图像。

我建议您使用cv2.imwrite() 生成图像(类似于plt.savefig()),然后使用cv2.imshow() 作为灰度图像读取图像。

import cv2
import numpy as np

data = np.array([
[1,2,0,1],
[0,1,2,1],
[0,0,2,1]])


cv2.imwrite("test.png", data)


img = cv2.imread("test.png", 0) #Using 0 to read in grayscale mode
print(data.shape, img.shape)

输出:

(3, 4) (3, 4)

【讨论】:

    【解决方案2】:

    完全不需要使用imshow 创建图像,您可以简单地计算您感兴趣的 RGBA 值矩阵

    import numpy as np
    import matplotlib as mp
    
    data = np.array([ [1,2,0,1],[0,1,2,1],[0,0,2,1]])
    n = mp.colors.Normalize(data.min(), data.max())
    c = mp.cm.viridis(n(data))[:,:,:-1] # [...,:-1] disregards the alpha values
    

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 2019-08-28
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      相关资源
      最近更新 更多