我正在嘗試保存一個影像,該影像應該具有以像素為單位的尺寸 (230, 256)。但是,由于計算在英寸內,我試圖找到一種方法將以下影像轉換為該尺寸:
label = np.zeros((230,256))
my_dpi = 96
# Create a figure. Equal aspect so circles look circular
fig,ax = plt.subplots(1, figsize=(4.5, 3.27))
ax.set_aspect('equal')
ax.set_axis_off()
# Show the image
ax.imshow(label)
circ1 = Circle((28,64),10, color='white')
circ1 = Circle((26,65),13, color='white')
circ2 = Circle((100,65),13, color='white')
circ3 = Circle((172,65),11, color='white')
circ4 = Circle((247,65),11, color='white')
circ5 = Circle((315,65),10, color='white')
ax.add_patch(circ1)
ax.add_patch(circ2)
ax.add_patch(circ3)
ax.add_patch(circ4)
ax.add_patch(circ5)
# Show the image
plt.show()
fig.savefig(nimage[23].split('.')[0] '_gt.jpg', bbox_inches='tight', dpi=my_dpi)
我也嘗試調整 dpi,但它沒有輸出預期的尺寸。有人能解釋一下如何在 matplotlib 中從 dpi 轉換為像素值嗎?
uj5u.com熱心網友回復:
您的 DPI 與 figsize(以英寸為單位定義)直接相關。DPI(每英寸點數)乘以 figsize 的寬度/高度將讓您以像素為單位計算大小。下面的 snipper 將生成一個具有您所需尺寸的圖形。請注意,您在 figsize 和 label 中的縱橫比不同。
label = np.zeros((230,256))
my_dpi = 96
w = 230./my_dpi
h = 256./my_dpi
# Create a figure. Equal aspect so circles look circular
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.set_axis_off()
# Show the image
ax.imshow(label)
circ1 = Circle((28,64),10, color='white')
circ1 = Circle((26,65),13, color='white')
circ2 = Circle((100,65),13, color='white')
circ3 = Circle((172,65),11, color='white')
circ4 = Circle((247,65),11, color='white')
circ5 = Circle((315,65),10, color='white')
ax.add_patch(circ1)
ax.add_patch(circ2)
ax.add_patch(circ3)
ax.add_patch(circ4)
ax.add_patch(circ5)
# Show the image
plt.show()
fig.set_size_inches(w, h, forward=True)
fig.tight_layout()
fig.savefig(nimage[23].split('.')[0] '_gt.jpg', dpi=my_dpi)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357824.html
標籤:Python matplotlib
上一篇:如何使用plt繪制拋物線和點?
