Skip to main content
 首页 » 编程设计

python之matplotlib 仅绘制具有所需分辨率和 dpi 的图像

2024年10月17日652php

我已经阅读了 stackoverflow 关于这个主题的所有问题,但没有成功。 上面的代码是我能得到的最接近没有轴和边框的图像的代码。 我无法控制图像分辨率,因为当我在 gimp 中打开图像时,它的 dpi 与我选择的不同。 我想要一张 7158 x 16392、72 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 

这会为我生成一个 .png 像素正好为 7158x16392 的文件,没有坐标轴,并且(据我所知)没有丢失或额外的数据。 正如我之前所说,您需要在 savefig-dialog(或其他地方的 savefig.dpi)中定义 dpi,如果您想要像素,则不能使用 bbox='tight' -精确的数字。如果您运行 Python3 或 from __future__ import division,则不需要 req_dpi 周围的 float 。