def index(): """ index accepts GET or POST at '/' GET parameters: url: the URL for an image POST parameters: image: an uploaded image file returns: jsonified data with 3 or 5 hex colors """ app.logger.info('Request received at /') if request.method == 'GET': app.logger.debug('GET request') url = request.args.get('url', False) if not url: raise BadRequest('Missing url parameter.') app.logger.info('Image URL: %s', url) r = requests.get(url) if r.status_code != 200: raise BadRequest('Invalid image URL: %s', url) im = colorific.load_image(data=r.content) else: # handles an image upload f = request.files['image'] im = colorific.load_image(data=f.stream) # extract colors colors = colorific.extract_colors(im) return jsonify({'colors': colors})
def get_palette(self, img_url): request = requests.get(img_url, stream=True) status = request.status_code if status == 200: img = Image.open(request.raw) palette = colorific.extract_colors(img) array_colors = [] for color in palette.colors: hex_value = colorific.rgb_to_hex(color.value) dictionary_colors = { 'r': color.value[0], 'g': color.value[1], 'b': color.value[2], 'hex': hex_value } array_colors.append(dictionary_colors) if palette.bgcolor is not None: hex_value = colorific.rgb_to_hex(palette.bgcolor.value) dictionary_colors = { 'r': palette.bgcolor.value[0], 'g': palette.bgcolor.value[1], 'b': palette.bgcolor.value[2], 'hex': hex_value } array_colors.append(dictionary_colors) else: array_colors = [] return array_colors
def colors(reader_list): for idx, row in enumerate(reader_list): if idx == 0: row.append('colors') row.append('color_palette') row.append('dominant_color') continue url = row[0] screenshot_path = 'screenshots/' + re.sub('[^A-Za-z0-9]+', '', url) + '.png' palette = colorific.extract_colors(screenshot_path, min_prominence=0.1, max_colors=50) colors = [] dominant_color = '' index = 0 for color in palette.colors: actual_name, closest_name = get_colour_name(color.value) current_color = closest_name if actual_name: current_color = actual_name if index == 0: dominant_color = current_color colors.append(current_color) index += 1 row.append(len(colors)) row.append(",".join(colors)) row.append(dominant_color)
def upload_image(): data = request.files.get('data') if data is not None: s = request.environ.get('beaker.session') colors = [colorific.rgb_to_hex(color.value) for color in colorific.extract_colors(data.file).colors] s['colors'] = colors s.save() return redirect('/result')
def fetch_and_extract_colors(file_ref, is_url): if is_url: imfile = fetch_image_as_file(file_ref) else: imfile = read_base64_as_file(file_ref) palette = colorific.extract_colors(imfile) colors = palette.colors return [{'value':color.value, 'score':color.prominence} for color in colors]
def test(): """Shows the test image palettes""" from test import TestPhotoColors, BASE_DIR images = [] for img in TestPhotoColors.TEST_PHOTOS: path = os.path.join(BASE_DIR, 'static/photos/', img) im = colorific.load_image(path=path) colors = colorific.extract_colors(im) images.append({'url': '/static/photos/%s' % img, 'colors': colors}) return render_template('test.html', images=images)
def form_valid(self, form): self.object = form.save() f = self.request.FILES.get('file') try: filename = "." + settings.MEDIA_URL + "pictures/" + f.name.replace(" ", "_") palette = extract_colors(filename) save_palette_as_image(filename, palette) output_filename = '%s_palette.png' % f.name.replace(" ", "_")[:f.name.replace(" ", "_").rfind('.')] except Exception, e: print filename, e
def parse_colors(self): palette = colorific.extract_colors(self.image) palette_dict = {} for color in palette.colors: color_hex = colorific.rgb_to_hex(color.value) palette_dict[color_hex] = color.prominence colors = sorted(palette_dict.items(), key=operator.itemgetter(1), reverse=True) return ','.join([c[0] for c in colors])
def get_primary_color(image_url): """Get the primary color of the currently playing album""" try: urllib.request.urlretrieve(image_url, "album_art.jpg") except: return int("0xffffff", 0) palette = colorific.extract_colors("album_art.jpg") primary_color_rgb = palette.colors[0].value primary_color = "0x" + colorific.rgb_to_hex(primary_color_rgb)[1:] return int(primary_color, 0)
def get_palette(self): image = Im.open(StringIO(self.image.body)) palette = colorific.extract_colors(image) palette_dict = {} for color in palette.colors: color_hex = colorific.rgb_to_hex(color.value) palette_dict[color_hex] = color.prominence colors = sorted( palette_dict.iteritems(), key=operator.itemgetter(1), reverse=True) return colors
def fetch_and_extract_colors(file_ref, is_url): if is_url: imfile = fetch_image_as_file(file_ref) else: imfile = read_base64_as_file(file_ref) palette = colorific.extract_colors(imfile) colors = palette.colors return [{ 'value': color.value, 'score': color.prominence } for color in colors]
def detect_colors(self): """ Creates a temp directory, downloads the img_url (if it exists), extracts colors and generates RGB aggregating all colors :param dirName: directory name store temporary images for processing :return: """ dirname = 'temp' if not os.path.exists(dirname): os.mkdir(dirname) filepath = dirname + '\\' + self.id + '.jpg' urllib.urlretrieve(self.img_url, filepath) palette = colorific.extract_colors(filepath) self.rgb_colors = colors_to_score_string(palette.colors)
def detect_colors(self): """ Creates a temp directory, downloads the img_url (if it exists), extracts colors and generates RGB aggregating all colors :param dirName: directory name store temporary images for processing :return: """ dirname = 'temp' if not os.path.exists(dirname): os.mkdir(dirname) filepath = dirname + '\\' + self.id + '.jpg' urllib.urlretrieve(self.img_url, filepath) palette = colorific.extract_colors(filepath) self.palette = palette self.rgb_colors = colors_to_score_string(palette.colors)
def process_file(input_file, filename): palette = colorific.extract_colors(filename, min_saturation=0.05, min_prominence=0.01, min_distance=10.0, max_colors=5, n_quantized=100) data = { 'filename': filename, 'colours': [rgb_to_hex(c.value) for c in palette.colors], 'background': palette.bgcolor and rgb_to_hex(palette.bgcolor.value) or '' } out_file = os.path.join(settings.OUTPUT_FILE_QUEUE, input_file + '_data.json') with open(out_file, 'wt') as out_file: out_file.write(json.dumps(data)) shutil.move(filename, os.path.join(settings.PROCESSED_FILE_QUEUE, input_file)) return data
def colorific_palette(fname, k=5): """ Extract a color palette using colorific. """ result = np.asarray(colorific.extract_colors(fname, max_colors=k)[0]) maincolors = np.asarray([list(c) for c in result[:, 0]]) / 255. percent = result[:, 1] / np.sum(result[:, 1]) return Palette(maincolors, percent)
def test_extract_colors(self): for p in self.TEST_PHOTOS: im = colorific.load_image(path=self._imgpath(p)) colors = colorific.extract_colors(im) self.assertTrue(colors)
def palette(image_path, min_saturation=0.05, min_prominence=0.01, min_distance=10.0, max_colors=5, n_quantized=100): colorp = colorific.extract_colors(image_path, min_saturation=min_saturation, min_prominence=min_prominence, min_distance=min_distance, max_colors=max_colors, n_quantized=n_quantized) return [colorific.rgb_to_hex(c.value) for c in colorp.colors]
import colorific import glob html = open("index.html", "w") for filename in glob.glob('../src/wallpapers/*'): html.write("<div>") html.write("<img width=\"150px\" src=\"" + filename + "\">") print(filename) palette = colorific.extract_colors(filename) print(palette) for color in palette.colors: print(color) hex_value = colorific.rgb_to_hex(color.value) html.write(""" <div style="background: {color}; width: 500px; height: 50px; color: white;"> {prominence} {color} </div> """.format(color=hex_value, prominence=color.prominence)) html.write("</div>") if palette.bgcolor != None: hex_value = colorific.rgb_to_hex(palette.bgcolor.value) html.write(""" <div style="background: {color}; width: 500px; height: 50px; color: white;"> <span>BG:</span>{prominence} {color} </div> """.format(color=hex_value, prominence=palette.bgcolor.prominence)) html.write("</div>")
def find_color(image, rargs): palette = colorific.extract_colors(image) out_colors = [rgb_to_hex(c.value) for c in palette.colors] return out_colors