Rendering 2D images from STL file in Python - python

I would like to load an STL file and produce a set of 2D images in different rotations.
I got the basics working with numpy-stl based on this example, ended up with this code -
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
filename = '3001.stl'
# Create a new plot
figure = pyplot.figure()
axes = figure.gca(projection='3d')
# Load the STL files and add the vectors to the plot
mesh = mesh.Mesh.from_file(filename)
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(mesh.vectors, color='lightgrey'))
#axes.plot_surface(mesh.x,mesh.y,mesh.z)
# Auto scale to the mesh size
scale = mesh.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)
#turn off grid and axis from display
pyplot.axis('off')
#set viewing angle
axes.view_init(azim=120)
# Show the plot to the screen
pyplot.show()
This works well only that I end up with a silhouette of the component, lacking a lot of the detail. the picture below is a lego brick...
I tried to highlight the edges. but that is sensitive to how the model was created, which is not great for me.
I was hoping that by adding lighting, the shadows could help add the missing detail but I can't find a way to do that.
Any idea how to add lightsource to the code below to create shadows ?

After getting tired with Mayavi's install disasters I ended up writing my own library for this.
https://github.com/bwoodsend/vtkplotlib
Your code would be something like
import vtkplotlib as vpl
from stl.mesh import Mesh
path = "your path here.stl"
# Read the STL using numpy-stl
mesh = Mesh.from_file(path)
# Plot the mesh
vpl.mesh_plot(mesh)
# Show the figure
vpl.show()
If you want the brick to be blue you can replace the mesh_plot with
vpl.mesh_plot(mesh, color="blue")

If you don't find Mayavi helpful, you could try Panda3D which is intended for graphics/3D rendering applications. I find it quite straightforward for doing simple stuff like this.

Related

PyVista plotter unable to produce background image for multiple subplots

I am trying to render a mesh in Python using pyvista.Plotter() while trying to show images alongside the rendered mesh. The code is currently in the form of
import pyvista as pv
from pyvista import examples
filenames = (['filename1.jpg','filename2.jpg','filename3.jpg',])
mesh = pv.PolyData('meshfile.ply')
p = pv.Plotter(shape='1|3')
p.subplot(0)
p.add_mesh(mesh)
t=1
for i in filenames:
p.subplot(t)
p.add_background_image(i)
#p.add_mesh(examples.load_airplane(), show_edges=False)
t +=1
where I thought the Plotter.add_background_image() would be the most convenient way to plot images using PyVista. The commented out line in the for loop actually produces the right arrangement but I would like the smaller plots to have background images rather than another mesh. However, only the final image file is actually shown and it is the background image of p.subplot(0) which should not have a background image. Would there be a more convenient way of displaying images alongside a pyvista 3d-rendered window?
Looking at the documentation of Plotter.add_background_image():
add_background_image(image_path, scale=1, auto_resize=True, as_global=True)
as_global (bool, optional) – When multiple render windows are present, setting as_global=False will cause the background to only appear in one window.
So you might just have to call the method as
p.add_background_image(i, as_global=False)

Issue with plotting shapefiles on an orthographic projection in Basemap

I have been trying to plot Exclusive Economic Zone (EEZ) shapefiles on an orthographic projection from the basemap package. However, the shapefile file has EEZs from around the world, and so when I try to plot the shapefiles there are always some that are not visible in the projection at that particular angle. This results in the shapes being smeared out, which is not quite the effect that I am going for. Ultimately I wish to only plot select shapefiles, but then this same issue will likely pop up so for now I'd be happy to solve this more basic case where I try to plot all of them.
Here in the code I try a simple case where I plot the shapefiles with the readshapefile command from basemap. I have also tried plotting the various shapes as polygons (figured that would give me more flexibility in changing the appearances of the individual shapefiles) but then I could not get the polygons to appear on the map in the right spot and I would see similar smearing behavior (so likely the issue has the same or a similar root cause).
I have attached the code from the simple case below. If I run this, I get the projection to appear as a I want, but with the smearing of the shapefiles. The shapefiles can be found at http://www.marineregions.org/downloads.php#unioneezcountry where I use version 2 of Marine and land zones: the union of world country boundaries and EEZ's.
#Here is the figure
fig=plt.figure(figsize=(20,12))
ax=fig.add_subplot(111)
#create the map projection
Map=Basemap(projection='ortho',lon_0=0,lat_0=0,resolution='l')
Map.drawcoastlines(zorder=10)
Map.drawcountries(zorder=10)
Map.drawmapboundary()
#Reading in the shapefile and plotting it
Map.readshapefile('~/EEZ_Boundaries/EEZ_land_v2_201410','countries')
Here is a link to the image I get when I run the code
Ok, so after more time of trying to get this to work, I have pretty much given up with Basemap and made a (long overdue) switch to cartopy. In that case, the problem does solved by Cartopy already, so the code that creates the figure I was trying to get is:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cpf
from cartopy.io.shapereader import Reader
#Set the projection
projection=ccrs.Orthographic(central_longitude=0,central_latitude=0)
fig=plt.figure(figsize=(20,12))
axMap=fig.add_subplot(1,1,1,projection=projection)
#resolution of the coastlines
resolution='10m'
axMap.coastlines(resolution=resolution,edgecolor='black',zorder=10)
#Add the shapefiles
shape_feature = cpf.ShapelyFeature(Reader(direc_shp+file_shp).geometries(),
ccrs.PlateCarree(), edgecolor='black')
axMap.add_feature(shape_feature,zorder=1)

plot image with interpolation in Python Bokeh like matplotlib?

Is there any way to plot 2D array as an image using Bokeh with interpolation like in Matplotlib? I am able to plot using an example: https://docs.bokeh.org/en/latest/docs/gallery/image.html
However, the image is to coarse. I like the way interpolation work in Matplotlib: https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html
I tried to perform interpolation beforehand but the matrix size now is to big.
I had the same issue and I've found the answer in pyviz's Gitter.
The solution combines Holoviews and Datashader:
import holoviews as hv
from holoviews import opts
from holoviews.operation.datashader import regrid
img = hv.Image(data)
regrid(img, upsample=True, interpolation='bilinear')
If you are working with a large dataset then you could try Bokeh in combination with Datashader/HoloViews like in this example. When zooming in, Datashader can dynamically create new high quality images from your data that could be displayed in your Bokeh plot.
Not an answer but an observation - I've noticed that plotting an image via an image_url source it appears interpolated when zoomed in whilst if you read in the same image and display it from a columndatasource via 'image' it then appears blocky when zoomed. I'd love to know how to make it appear interpolated too when zoomed, eg like the raw png image appears. Holoview/datashader would be a great solution but in my case I need it to work offline/as a standalone html file.

Vector graphics + matplotlib pcolorfast

To keep it short: Is there a way to export plots created with methods like
pcolorfast which basically draw pixels as "real" vector graphics?
I tried to do just that using savefig and saving to a PDF but what would happen is that the plot was actually a vector graphic but the parts drawn by pcolorfast(so basically, what is inside the axes) something like a bitmap. - I checked this using Inkscape.
This resulted in really low resolution plots even though the arrays drawn with pcolorfast where about 3000x4000. I achieved higher resolution by increasing the dpi when exporting, but I'd really appreciate a conversion to a real vector graphic.
Edit: I updated my original code by the piece of code below that should serve to illustrate what exactly I am doing. I tried to involucrate the rasterized tip, but it has had no effect. I still end up with a supersmall PDF-file where the plots are acually raster images (png). I am going to provide you with the data I used and the resulting PDF.
http://www.megafileupload.com/k5ku/test_array1.txt
http://www.megafileupload.com/k5kv/test_array2.txt
http://www.megafileupload.com/k5kw/test.pdf
import numpy as np
import matplotlib.pyplot as plt
arr1= np.loadtxt("test_array1.txt")
arr2= np.loadtxt("test_array2.txt")
fig, (ax1, ax2)=plt.subplots(1, 2)
ax1.set_rasterized(False)
ax1.pcolorfast(arr1)
ax2.pcolorfast(arr2, rasterized=False)
plt.show()
fig.set_rasterized(False)
fig.savefig("test.pdf")

Saving images in Python at a very high quality

How can I save Python plots at very high quality?
That is, when I keep zooming in on the object saved in a PDF file, why isn't there any blurring?
Also, what would be the best mode to save it in?
png, eps? Or some other? I can't do pdf, because there is a hidden number that happens that mess with Latexmk compilation.
If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:
plt.savefig('destination_path.eps', format='eps')
I have found that EPS files work best and the dpi parameter is what really makes them look good in a document.
To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax):
ax.view_init(elev=elevation_angle, azim=azimuthal_angle)
Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis).
I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.
Just to add my results, also using Matplotlib.
.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)
I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.
Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".
You can save to a figure that is 1920x1080 (or 1080p) using:
fig = plt.figure(figsize=(19.20,10.80))
You can also go much higher or lower. The above solutions work well for printing, but these days you want the created image to go into a PNG/JPG or appear in a wide screen format.
Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:
beingsaved = plt.figure()
# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)
beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)
In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:
Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:
import seaborn as sb
image = sb.heatmap(matrix) # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png") # This saves it
This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.
Another way I like is this. I set the size of the next image as follows:
plt.subplots(figsize=(15,15))
And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

Categories

Resources