I am trying to save an image which is supposed to have the dimension (230, 256) in pixels. However, since the calculations are within inches I'm trying to find a way to convert the following image into that dimension:
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)
I also tried to adapt the dpi but it was not outputing the expected dimension. Can anybody explain how to convert from dpi to pixel values in matplotlib?
CodePudding user response:
Your DPI is directly related to figsize (which is defined in inches). DPI (dots per inch) multiplied by your width/height from figsize will let you calculate the size in terms of pixels. The snipper below would generate a figure with your required dimensions. Please note, the aspect ratio is NOT the same between what you had in your figsize and 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)