colormixer / app.py
matrixglitch's picture
Update app.py
722954d verified
import gradio as gr
import numpy as np
# Density of paint in g/ml (this is an approximation, actual density may vary)
PAINT_DENSITY = 1.5
def rgb_to_primary(r, g, b, total_amount, unit):
# Convert RGB to range 0-1
r, g, b = r/255.0, g/255.0, b/255.0
# Calculate CMY
c = 1 - r
m = 1 - g
y = 1 - b
# Calculate K (black)
k = min(c, m, y)
# Calculate true CMY
if k < 1:
c = (c - k) / (1 - k)
m = (m - k) / (1 - k)
y = (y - k) / (1 - k)
else:
c = m = y = 0
# Calculate white
w = 1 - max(c, m, y, k)
# Normalize to ensure sum is 1
total = c + m + y + k + w
c, m, y, k, w = c/total, m/total, y/total, k/total, w/total
# Convert to selected unit
yellow = y * total_amount
blue = c * total_amount
red = m * total_amount
black = k * total_amount
white = w * total_amount
return {
f"Yellow ({unit})": round(yellow, 2),
f"Blue ({unit})": round(blue, 2),
f"Red ({unit})": round(red, 2),
f"Black ({unit})": round(black, 2),
f"White ({unit})": round(white, 2)
}
def calculate_colors(color, total_amount, input_unit, output_unit):
r, g, b = [int(color[i:i+2], 16) for i in (1, 3, 5)]
# Convert input to ml if necessary
if input_unit == "mg":
total_amount = total_amount / (PAINT_DENSITY * 1000)
# Calculate color amounts in ml
color_amounts_ml = rgb_to_primary(r, g, b, total_amount, "ml")
# Convert to mg if necessary
if output_unit == "mg":
color_amounts = {k: v * PAINT_DENSITY * 1000 for k, v in color_amounts_ml.items()}
color_amounts = {k.replace("ml", "mg"): round(v, 2) for k, v in color_amounts.items()}
else:
color_amounts = color_amounts_ml
# Create color preview
color_preview = np.full((50, 50, 3), [r, g, b], dtype=np.uint8)
return color_amounts, color_preview
# Create Gradio interface
iface = gr.Interface(
fn=calculate_colors,
inputs=[
gr.ColorPicker(label="Select Color"),
gr.Number(label="Total Paint Amount", value=100),
gr.Radio(["ml", "mg"], label="Input Unit", value="ml"),
gr.Radio(["ml", "mg"], label="Output Unit", value="ml")
],
outputs=[
gr.JSON(label="Color Amounts"),
gr.Image(label="Color Preview", type="numpy")
],
title="Paint Color Mixer Calculator",
description="Select a color and specify the total amount of paint to calculate the required amounts of primary colors. Choose between ml and mg for input and output units."
)
# Launch the interface
iface.launch()