首页 > 解决方案 > 保持数组的原始形状为图像

问题描述

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

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)

标签: pythonnumpymatplotlibcv2

解决方案


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

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

此外,您正在尝试将图像写入二维数组,但在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)

推荐阅读