在参加 Kaggle 比赛时,我遇到了一些奇怪的问题。
基本上,我正在尝试将 am 图像的矢量表示形式转换为 png 文件。它在 iPython 中完美运行,代码如下:
def drawing_to_np_prepare_data(drawing):
drawing = eval(drawing)
fig, ax = plt.subplots()
plt.close(fig)
print('[debug] ax=',ax)
for x,y in drawing:
ax.plot(x, y, marker='.')
ax.axis('off')
fig.canvas.draw()
# Convert images to numpy array
np_drawing = np.array(fig.canvas.renderer._renderer)
print('[debug] fig_size=',fig.get_size_inches())
print('[debug] dpi=',fig.dpi)
print('[debug] shape=',np_drawing.shape)
print('[debug] size=',np_drawing.size)
print('[debug] shape=',np_drawing.shape)
im = cv2.cvtColor(np_drawing.astype(np.uint8), cv2.COLOR_BGR2RGB)
# compress
compressed_array = io.BytesIO()
np.savez_compressed(compressed_array, im)
compressed_array.seek(0)
print('[debug] size=',np_drawing.shape)
return compressed_array
结果显示:
[debug] ax=AxesSubplot(0.125,0.125;0.775x0.755)
[debug] fig_size= [6. 4.]
[debug] dpi= 72.0
[debug] np_drawing.size= 497664
[debug] shape= (288, 432, 4)
[debug] size= 1880
满足我的需求:我得到压缩大小
然而,当我从 CLI 在 python 中运行这段代码时,我得到了完全不同的结果:
[debug] ax=AxesSubplot(0.125,0.11;0.775x0.77)
[debug] fig_size= [6.4 4.8]
[debug] dpi= 100.0
[debug] np_drawing.size= 1228800
[debug] shape= (480, 640, 4)
[debug] size= 13096
如您所见,图形大小、dpi、轴不同,因此最终的大小也不同。
我可以将参数传递给子图:
plt.subplots(figsize=(6.,4.), dpi=72)
它纠正除轴之外的参数(和尺寸,我猜是因为轴不同):
[debug] ax=AxesSubplot(0.125,0.11;0.775x0.77)
[debug] fig_size= [6. 4.]
[debug] dpi= 72.0
[debug] np_drawing.size= 497664
[debug] shape= (288, 432, 4)
[debug] size= 8214
注意:我检查过库版本,它们是相同的。
因此,出现了多个问题:
为什么子图给出不同的轴、形状和分辨率?
如何校正轴?
如何在 python 中获得相同的行为?
我想了解发生了什么事。谢谢!