python - 保持数组的原始形状为图像
问题描述
我有一些数据。我可视化然后将其保存为图像。
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
也是特定于您的显示器屏幕的,因此不推荐使用。有关更多信息,请参阅此处的答案。
此外,您正在尝试将图像写入二维数组,但在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)
推荐阅读
- python - 如何避免使用“eval”函数循环遍历属性列表
- curl - 使用curl post将slurm sacct命令的终端输出写入influxdb?
- powershell - 我如何根据有输出文件的时间来衡量完成百分比?
- go - Why is a float64 type number throwing int related error in Go
- java - Android 得到 html 响应而不是 json 响应 | 价值
嗨,我很难弄清楚导致此错误的原因。直到我尝试使用调试并发现我得到的是 html 响应而不是 json 响应。请帮我解决这个问题。
检查这个java代码:
从这一点开始,错误被触发
- python - 修复了 Django 提供的默认值问题
- reactjs - Material-DataTable 禁用内置搜索
- xslt - Firefox Quantum v67 不呈现 XSLT (xsl:call-template & xsl:with-param)
- kubernetes - 在 Kubernetes (GKE) 上部署 Strapi
- go - 去 XML 抑制自动生成的标签?