reysarms commited on
Commit
75ba4bf
·
1 Parent(s): caefe2a

updated app.py

Browse files
Files changed (2) hide show
  1. app.py +83 -8
  2. requirements.txt +3 -0
app.py CHANGED
@@ -2,16 +2,21 @@ import cv2
2
  import numpy as np
3
  import streamlit as st
4
  from sklearn.cluster import KMeans
 
5
 
6
- def get_dominant_color(image, k=1):
7
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
8
  image = image.reshape((-1, 3))
9
 
10
  kmeans = KMeans(n_clusters=k, random_state=0, n_init=10)
11
  kmeans.fit(image)
12
 
13
- dominant_color = kmeans.cluster_centers_[0].astype(int)
14
- return tuple(dominant_color)
 
 
 
 
15
 
16
  def is_warm_or_cool(color):
17
  r, g, b = color
@@ -19,20 +24,90 @@ def is_warm_or_cool(color):
19
  return "Warm" if warm else "Cool"
20
 
21
  def complementary_color(color):
22
- r, g, b = color
23
  return (255 - r, 255 - g, 255 - b)
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  st.title("VQA for Colors and Color Theory")
 
 
 
 
 
 
26
  uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
27
 
28
  if uploaded_file is not None:
 
 
29
  file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
30
  image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
31
 
32
- dominant = get_dominant_color(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  comp_color = complementary_color(dominant)
34
 
35
- st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), caption="Uploaded Image", use_column_width=True)
36
- st.write(f"**Dominant Color:** {dominant}")
37
  st.write(f"**Temperature:** This is a {is_warm_or_cool(dominant)} color.")
38
- st.write(f"**Complementary Color:** {comp_color}")
 
 
 
 
 
 
 
 
 
 
 
2
  import numpy as np
3
  import streamlit as st
4
  from sklearn.cluster import KMeans
5
+ import matplotlib.pyplot as plt
6
 
7
+ def get_dominant_colors(image, k=8):
8
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
9
  image = image.reshape((-1, 3))
10
 
11
  kmeans = KMeans(n_clusters=k, random_state=0, n_init=10)
12
  kmeans.fit(image)
13
 
14
+ colors = kmeans.cluster_centers_.astype(int)
15
+ labels = kmeans.labels_
16
+ counts = np.bincount(labels)
17
+ percentages = counts / sum(counts) * 100
18
+
19
+ return list(zip(colors, percentages))
20
 
21
  def is_warm_or_cool(color):
22
  r, g, b = color
 
24
  return "Warm" if warm else "Cool"
25
 
26
  def complementary_color(color):
27
+ r, g, b = map(int, color)
28
  return (255 - r, 255 - g, 255 - b)
29
 
30
+ def plot_color_palette(colors):
31
+ fig, ax = plt.subplots(figsize=(8, 1))
32
+ ax.imshow([colors], extent=[0, len(colors), 0, 1])
33
+ ax.set_xticks([])
34
+ ax.set_yticks([])
35
+ ax.spines[:].set_visible(False)
36
+ st.pyplot(fig)
37
+
38
+ def rgb_to_hex(color):
39
+ return "#" + "".join(f"{c:02x}" for c in color)
40
+
41
+ def get_color_name(rgb):
42
+ color_names = {
43
+ (255, 0, 0): "Red", (0, 255, 0): "Green", (0, 0, 255): "Blue",
44
+ (255, 255, 0): "Yellow", (0, 255, 255): "Cyan", (255, 0, 255): "Magenta",
45
+ (128, 0, 0): "Maroon", (128, 128, 0): "Olive", (0, 128, 0): "Dark Green",
46
+ (128, 0, 128): "Purple", (0, 128, 128): "Teal", (0, 0, 128): "Navy",
47
+ (255, 165, 0): "Orange", (139, 69, 19): "Brown", (255, 192, 203): "Pink",
48
+ (192, 192, 192): "Silver", (128, 128, 128): "Gray", (0, 0, 0): "Black",
49
+ (255, 255, 255): "White"
50
+ }
51
+ closest_color = min(color_names.keys(), key=lambda x: np.linalg.norm(np.array(x) - np.array(rgb)))
52
+ return color_names[closest_color]
53
+
54
+ def answer_question(question, colors, percentages):
55
+ if "dominant" in question.lower():
56
+ return f"The dominant color is {get_color_name(colors[0])} with {percentages[0]:.2f}% presence."
57
+ elif "complementary" in question.lower():
58
+ comp_color = complementary_color(colors[0])
59
+ return f"The complementary color is {comp_color}."
60
+ elif "warm or cool" in question.lower():
61
+ return f"The dominant color is a {is_warm_or_cool(colors[0])} color."
62
+ else:
63
+ return "I can answer questions related to dominant color, complementary color, or warm/cool classification."
64
+
65
  st.title("VQA for Colors and Color Theory")
66
+
67
+ st.markdown("""
68
+ ### 🎨 Welcome to Color Explorer!
69
+ Upload an image and let the magic begin! Our app analyzes the dominant colors, identifies complementary colors, and even determines if the hues are warm or cool. Perfect for designers, artists, and color enthusiasts!
70
+ """)
71
+
72
  uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
73
 
74
  if uploaded_file is not None:
75
+ st.image(uploaded_file, caption=f"Uploaded Image: {uploaded_file.name}", use_container_width=True)
76
+
77
  file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
78
  image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
79
 
80
+ color_data = get_dominant_colors(image)
81
+ colors, percentages = zip(*color_data)
82
+ color_names = [get_color_name(color) for color in colors]
83
+
84
+ st.subheader("Color Analysis")
85
+
86
+ for name, color, percent in zip(color_names, colors, percentages):
87
+ st.markdown(
88
+ f'<div style="display: flex; align-items: center; gap: 15px; margin-bottom: 10px;">'
89
+ f'<div style="width: 50px; height: 50px; background-color: {rgb_to_hex(color)}; border-radius: 5px;"></div>'
90
+ f'<div><strong>{name}</strong></div>'
91
+ f'<div>HEX: {rgb_to_hex(color)}</div>'
92
+ f'<div>RGB: {tuple(map(int, color))}</div>'
93
+ f'<div>Percentage: {percent:.2f}%</div>'
94
+ f'</div>',
95
+ unsafe_allow_html=True
96
+ )
97
+
98
+ dominant = colors[0]
99
  comp_color = complementary_color(dominant)
100
 
101
+ st.subheader("Additional Info")
 
102
  st.write(f"**Temperature:** This is a {is_warm_or_cool(dominant)} color.")
103
+ st.write(f"**Complementary Color:** {get_color_name(comp_color)} (HEX: {rgb_to_hex(comp_color)}, RGB: {comp_color})")
104
+
105
+ st.subheader("Generated Color Palette")
106
+ plot_color_palette(colors)
107
+
108
+ # VQA Section
109
+ st.subheader("Ask a Question About the Image")
110
+ user_question = st.text_input("Enter your question:")
111
+ if user_question:
112
+ answer = answer_question(user_question, colors, percentages)
113
+ st.write("**Answer:**", answer)
requirements.txt CHANGED
@@ -2,3 +2,6 @@ streamlit
2
  opencv-python
3
  numpy
4
  scikit-learn
 
 
 
 
2
  opencv-python
3
  numpy
4
  scikit-learn
5
+ matplotlib
6
+ colorthief
7
+