matplotlib只绘制具有所需分辨率和dpi的图像
问题描述:
我已阅读关于此主题的所有关于计算器的问题,但没有成功。 上面的代码是我可以在没有坐标轴和边框的情况下获得图像的最接近的代码。 我无法控制图像分辨率,因为当我用gimp打开图像时它的dpi与我选择的不同。 我想要使用72 dpi的7158 x 16392最终图像,无任何边框或边框。matplotlib只绘制具有所需分辨率和dpi的图像
from stl import mesh
from matplotlib import collections
from matplotlib import pyplot
figure, axes = pyplot.subplots(frameon=False)
figure.set_size_inches(99.5,228)
# Read the STL file
your_mesh = mesh.Mesh.from_file('2d_35MeshTest.STL')
axes.set_xlim(your_mesh.min_[0], your_mesh.max_[0])
axes.set_ylim(your_mesh.min_[1], your_mesh.max_[1])
axes.add_collection(collections.PolyCollection(your_mesh.vectors[:, :, :2], linewidth=1,
facecolors=(1,1,1),alpha=1, edgecolors=(1,0,0)))
print your_mesh.vectors.shape
pyplot.gca().set_aspect('equal')
pyplot.axis('off')
ax = pyplot.Axes(figure, [0., 0., 1., 1.],)
figure.set_dpi(72)
figure.subplots_adjust(bottom = 0)
figure.subplots_adjust(top = 1)
figure.subplots_adjust(right = 1)
figure.subplots_adjust(left = 0)
figure.savefig('image_refined8.png', format='png', transparent=True, bbox_inches='tight', pad_inches = 0.001)
STL文件是在这里stl file 图像输出为image output
答
您的编辑后:
from stl import mesh
from matplotlib import collections
from matplotlib import pyplot
figure, axes = pyplot.subplots(frameon=False)
pixel_width = 7158 # ADDED
pixel_height = 16392 # ADDED
req_dpi = 72 # ADDED
figure.set_size_inches(pixel_width/float(req_dpi), # MODIFIED
pixel_height/float(req_dpi)) # MODIFIED
# Read the STL file
your_mesh = mesh.Mesh.from_file('2d_35MeshTest.STL')
axes.set_xlim(your_mesh.min_[0], your_mesh.max_[0])
axes.set_ylim(your_mesh.min_[1], your_mesh.max_[1])
axes.add_collection(collections.PolyCollection(your_mesh.vectors[:, :, :2],
linewidth=1,
facecolors=(1,1,1),alpha=1,
edgecolors=(1,0,0)))
print your_mesh.vectors.shape
pyplot.gca().set_aspect('equal')
pyplot.axis('off')
ax = pyplot.Axes(figure, [0., 0., 1., 1.],)
figure.set_dpi(72)
figure.subplots_adjust(bottom = 0)
figure.subplots_adjust(top = 1)
figure.subplots_adjust(right = 1)
figure.subplots_adjust(left = 0)
figure.savefig('image_refined7.png', format='png',
transparent=True, dpi=req_dpi) # MODIFIED
这将产生一个巴纽与准确7158x16392像素对我来说,没有轴和(据我所知),没有缺失或额外的数据。 正如我前面所说的,您需要在savefig-dialog(或其他地方的savefig.dpi)中定义dpi
,如果您想要像素精确的数字,则不能使用bbox='tight'
。如果运行Python3或from __future__ import division
,则不需要浮点数req_dpi
。
+0
我希望能够选择分辨率。 我希望最终的图像有72 dpi的7158 x 16392,没有任何边框或框架。如果你看图像,你会看到一串我不想要的透明像素。 – marco
我误解了你的主要意图。 dpi问题不存在,只要该数字是7158 x 16392像素。如果你想要发生这种情况,你不应该使用bbox_inches ='tight',因为这会调整数字。关闭它们之后,您还添加了坐标轴。顺便说一句,除了轴和透明边框(可能是pad_inches)之外,图像对我来说是完全白色的。我似乎也无法运行你的代码。 'stl'从哪里来? – StefanS
我更新了代码和文件。当我使用“紧”时,它不适合。 – marco