ADITYA KUMAR
commited on
Commit
·
ac42b1d
1
Parent(s):
97f8925
Create model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sklearn.cluster import KMeans
|
| 2 |
+
from collections import Counter
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
from transformers import pipeline, BasePipeline
|
| 6 |
+
|
| 7 |
+
class ColorExtractionPipeline(BasePipeline):
|
| 8 |
+
def __init__(self, *args, **kwargs):
|
| 9 |
+
super().__init__(*args, **kwargs)
|
| 10 |
+
self.image_pipeline = pipeline("image-classification")
|
| 11 |
+
|
| 12 |
+
def get_image(self, pil_image):
|
| 13 |
+
nimg = np.array(pil_image)
|
| 14 |
+
image = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
|
| 15 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 16 |
+
return image
|
| 17 |
+
|
| 18 |
+
def get_labels(self, rimg):
|
| 19 |
+
clf = KMeans(n_clusters=5)
|
| 20 |
+
labels = clf.fit_predict(rimg)
|
| 21 |
+
return labels, clf
|
| 22 |
+
|
| 23 |
+
def RGB2HEX(self, color):
|
| 24 |
+
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
|
| 25 |
+
|
| 26 |
+
def extract_colors(self, pimg):
|
| 27 |
+
img = self.get_image(pimg)
|
| 28 |
+
reshaped_img = img.reshape(img.shape[0] * img.shape[1], img.shape[2])
|
| 29 |
+
labels, clf = self.get_labels(reshaped_img)
|
| 30 |
+
counts = Counter(labels)
|
| 31 |
+
center_colors = clf.cluster_centers_
|
| 32 |
+
ordered_colors = [center_colors[i] for i in counts.keys()]
|
| 33 |
+
hex_colors = [self.RGB2HEX(ordered_colors[i]) for i in counts.keys()]
|
| 34 |
+
closest_color_to_white = min(center_colors, key=lambda c: np.linalg.norm(c - [255, 255, 255]))
|
| 35 |
+
hex_closest_color_to_white = self.RGB2HEX(closest_color_to_white)
|
| 36 |
+
return hex_colors, hex_closest_color_to_white
|
| 37 |
+
|
| 38 |
+
def __call__(self, pimg):
|
| 39 |
+
return self.extract_colors(pimg)
|
| 40 |
+
|
| 41 |
+
color_extraction = ColorExtractionPipeline(task="image-classification")
|