Spaces:
Running
Running
import os | |
import numpy as np | |
import cv2 | |
import gradio as gr | |
from PIL import Image | |
# Paths (Adjust these paths according to your environment) | |
PCA_MODEL_PATH = "pca_texture_model.npy" | |
# Load PCA model | |
pca = np.load(PCA_MODEL_PATH, allow_pickle=True).item() | |
TEXTURE_SIZE = int(np.sqrt(pca.mean_.shape[0] // 3)) | |
# PCA attributes | |
mean_texture = pca.mean_ | |
components = pca.components_ | |
n_components = components.shape[0] | |
# Calculate slider ranges | |
slider_ranges = [3 * np.sqrt(var) for var in pca.explained_variance_] | |
def reconstruct_texture(component_values): | |
# Reconstruct the texture using the PCA components | |
new_texture = mean_texture + np.dot(component_values, components) | |
new_texture = np.clip(new_texture, 0, 255).astype(np.uint8) | |
new_texture = new_texture.reshape((TEXTURE_SIZE, TEXTURE_SIZE, 3)) | |
new_texture = cv2.cvtColor(new_texture, cv2.COLOR_BGR2RGB) | |
image = Image.fromarray(new_texture) | |
return image | |
def main(): | |
# Create a list of sliders | |
sliders = [] | |
for i in range(n_components): | |
range_limit = slider_ranges[i] | |
sliders.append(gr.Slider(minimum=-range_limit, maximum=range_limit, step=10, label=f"Component {i+1}", value=0)) | |
with gr.Blocks() as demo: | |
with gr.Row(): | |
with gr.Column(): | |
# Create sliders | |
for slider in sliders: | |
slider.render() | |
with gr.Column(): | |
image_output = gr.Image(label="Generated Texture", type="pil") | |
image_output.render() | |
randomize_button = gr.Button("Randomize") | |
randomize_button.render() | |
# Update texture when sliders change | |
def on_slider_change(*args): | |
component_values = np.array([s.value for s in sliders]) | |
image = reconstruct_texture(component_values) | |
image_output.update(value=image) | |
for slider in sliders: | |
slider.change(fn=on_slider_change, inputs=None, outputs=None) | |
# Randomize button | |
def on_randomize_click(): | |
sampled_coefficients = np.random.normal(0, np.sqrt(pca.explained_variance_), size=n_components) | |
for i, slider in enumerate(sliders): | |
slider.update(value=sampled_coefficients[i]) | |
image = reconstruct_texture(sampled_coefficients) | |
image_output.update(value=image) | |
randomize_button.click(fn=on_randomize_click, inputs=None, outputs=None) | |
demo.launch() | |
if __name__ == "__main__": | |
main() | |