Uploading .stl files and reading it in streamlit

Is there any way to read the uploaded .stl because when i try to read it it says


code snippet:

file = st.file_uploader(“Please upload an STL Object file”, type=[“STL”])
st.write(file)
file = file.read()

Hey @Kabilan-n

I don’t think you are receiving this error in reading the “.stl” file.
You are receiving it while using the “st.write(file)” command.
This is because streamlit doesn’t understand how to actually write the contents of that file on the app since the write function is meant to be used with text data.

Also, I noticed you are using the “file.read()” command. If your intentions are to read the actual file with that, you don’t need to do it as the file variable represents that file from the memory and you can directly perform operations on it.

Although I don’t really know what an STL file is and would love to know more about it from you, Google says it is a CAD software generated 3D file. For rending those files in python, I found this stack overflow question that might be useful for you (matplotlib - Rendering 2D images from STL file in Python - Stack Overflow).

To print the image after performing all these steps, I guess st.image() function should work.

Hope this helps
Kanak

No, the error is occurring during “st.read()”. STL file is a 3D object file, I need to use this file and convert into meshes. I done this using python but while deploying it using streamlit, i’m getting error while reading this file.

Hey @Kabilan-n
Sorry for the confusion before.

I have understood your problem now and I was able to find a solution for it. After reading it from the user, instead of passing the file directly to the function, I saved it to the disk first and then accessed it.

This is my code for the same -

import shutil
import streamlit as st
import stl
from mpl_toolkits import mplot3d
from matplotlib import pyplot

file = st.file_uploader("Please upload an STL Object file", type=["STL"])

if file is not None:
    # save the uploaded file to disk
    with open("stlfile.stl", "wb") as buffer:
        shutil.copyfileobj(file, buffer)

    # Create a new plot
    figure = pyplot.figure()
    axes = figure.gca(projection='3d')

    # Load the STL files and add the vectors to the plot
    
    mesh = stl.mesh.Mesh.from_file("stlfile.stl")

    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
    st.pyplot(figure)

Hope this helps
Kanak

1 Like

Thanks, this helps a lot

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.