Spaces:
Runtime error
Runtime error
Update app.py
Browse files3 unmodified lines45677891011121213141516171819192021227 unmodified lines303132333433343536373839394041424344454346474849475051525354558 unmodified lines646566636768693 unmodified linesfrom PIL import Imageimport tempfile
def apply_texture_to_selected(section):def apply_masked_texture(section): # Load the original mesh mesh = trimesh.load('train.glb', force='mesh') im = Image.open('rust_steel.png').convert('RGB')
# Calculate bounding box coordinates # Calculate the bounding box coordinates bounds = mesh.bounds min_bounds, max_bounds = bounds[0], bounds[1] mid_x = (max_bounds[0] + min_bounds[0]) / 2 mid_y = (max_bounds[1] + min_bounds[1]) / 2 mid_z = (max_bounds[2] + min_bounds[2]) / 2
# Define sections with indices # Define sections with relevant indices sections = { 'upper': np.where(mesh.vertices[:, 2] > mid_z)[0], 'lower': np.where(mesh.vertices[:, 2] <= mid_z)[0],7 unmodified lines # Select the indices for the specified section selected_indices = sections[section]
# Initialize the UV mapping with default or existing values if mesh.visual.kind == 'texture': # Initialize UV mapping and retain original visuals for unselected vertices if mesh.visual.kind == 'texture' and mesh.visual.uv is not None: original_uv = mesh.visual.uv else: original_uv = np.random.rand(len(mesh.vertices), 2)
# Generate new UV coordinates for the selected region only # Create new UV coordinates only for the selected region new_uv = np.copy(original_uv) new_uv[selected_indices, :] = np.random.rand(len(selected_indices), 2)
# Preserve the original colors and visuals for non-selected sections original_colors = mesh.visual.vertex_colors if mesh.visual.vertex_colors is not None else np.ones((len(mesh.vertices), 4)) * 255
# Create a new material using the texture image # Create a new material with the texture image material = trimesh.visual.texture.SimpleMaterial(image=im) new_visuals = trimesh.visual.TextureVisuals(uv=new_uv, material=material)
# Create a new mesh with the updated visual data # Create a new mesh with both original and updated visuals textured_mesh = trimesh.Trimesh(vertices=mesh.vertices, faces=mesh.faces, visual=new_visuals, validate=True, process=False) textured_mesh.visual.vertex_colors = original_colors # Retain original vertex colors
# Save the modified mesh to a temporary file for Gradio visualization temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.glb')8 unmodified lines
section_dropdown = gr.Dropdown(choices=['upper', 'lower', 'middle', 'top', 'right'], label="Select Section") button = gr.Button("Apply Texture to Section") button.click(apply_texture_to_selected, inputs=section_dropdown, outputs=modified_model) button.click(apply_masked_texture, inputs=section_dropdown, outputs=modified_model)
app.launch()app.py+13-9