def colorize_image(filename1, filename2, out_filename): pallete_size = 5 new_pallete = colorgram.extract(filename1, pallete_size) old_pallete = colorgram.extract(filename2, pallete_size) new_pallete = list(map(lambda c: Color(c.rgb), new_pallete)) old_pallete = list(map(lambda c: Color(c.rgb), old_pallete)) pallete_dict = OrderedDict() for i in range(pallete_size): pallete_dict[old_pallete[i]] = new_pallete[i] # go edit pixels now that the dict has been built image = Image.open(filename2).convert("RGBA") pixels = image.load() width, height = image.size for j in range(height): for i in range(width): alpha = pixels[i, j][3] result_color = colorize_single(pallete_dict, Color(pixels[i, j])) pixels[i, j] = result_color.rgba_tuple(alpha) image.save(out_filename, format="PNG")
def paint(cols, rows): """Takes number of columns and rows as INT and paints a dot of random color at each position.""" # extract the colors extracted_colors = colorgram.extract("image.jpg", 30) color_list = [] for col in extracted_colors: color_list.append(col.rgb) # set up the brush brush = turtle.Turtle() brush.shape("circle") # from a range of 0-10, 7 seems reasonable brush.speed(7) brush.penup() brush.hideturtle() # initial position width = screen.window_width() height = screen.window_height() # offset between the dots x_offset = int(width / cols) y_offset = int(height / rows) # the coordinates go from -300 to +300 (i.e. half the height or width) # initial offset by half of the distance between each dot x_pos = int(width / -2 + x_offset / 2) y_pos = int(height / -2 + y_offset / 2) for _ in range(0, rows): for __ in range(0, cols): brush.setx(x_pos) brush.sety(y_pos) brush.dot(30, random.choice(color_list)) x_pos += x_offset # reset the x position to the first column x_pos = int(width / -2 + x_offset / 2) y_pos += y_offset
async def create_palette(self, img: BytesIO, amount: int, show_hex: bool, sorted: bool): colors = colorgram.extract(img, amount) if sorted: colors.sort(key=lambda c: c.rgb) dimensions = (500 * len(colors), 500) if show_hex else (100 * len(colors), 100) final = Image.new("RGBA", dimensions) a = ImageDraw.Draw(final) start = 0 if show_hex: font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf" name_fnt = ImageFont.truetype(font_file, 52, encoding="utf-8") for color in colors: a.rectangle([(start, 0), (start + dimensions[1], 450 if show_hex else 100)], fill=color.rgb) if show_hex: msg = f"#{self.rgb_to_hex(color.rgb)}" a.text( (start + dimensions[1] // 2, 500), msg, font=name_fnt, fill=(255, 255, 255, 255), anchor="mb", ) start = start + dimensions[1] final = final.resize((500 * len(colors), 500), resample=Image.ANTIALIAS) fileObj = BytesIO() final.save(fileObj, "png") fileObj.name = "palette.png" fileObj.seek(0) return discord.File(fileObj)
def add_objects(self, collection): games = [Indexer.todict(game) for game in collection] for i, game in enumerate(games): if i != 0 and i % 25 == 0: print(f"Indexed {i} of {len(games)} games...") if game["image"]: response = requests.get(game["image"]) if response.status_code == 200: image = Image.open(io.BytesIO( response.content)).convert('RGBA') try_colors = 10 colors = colorgram.extract(image, try_colors) for i in range(min(try_colors, len(colors))): color_r, color_g, color_b = colors[i].rgb.r, colors[ i].rgb.g, colors[i].rgb.b # Don't return very light or dark colors luma = (0.2126 * color_r / 255.0 + 0.7152 * color_g / 255.0 + 0.0722 * color_b / 255.0) if (luma > 0.2 and # Not too dark luma < 0.8 # Not too light ): break else: # As a fallback, use the first color color_r, color_g, color_b = colors[0].rgb.r, colors[ 0].rgb.g, colors[0].rgb.b game["color"] = f"{color_r}, {color_g}, {color_b}" game["objectID"] = f"bgg{game['id']}" # Turn players tuple into a hierarchical facet game["players"] = [ self._facet_for_num_player(num, type_) for num, type_ in game["players"] ] # Algolia has a limit of 10kb per item, so remove unnessesary data from expansions attribute_map = { "id": lambda x: x, "name": lambda x: self._remove_game_name_prefix(x, game["name"]), "players": lambda x: x or None, } game["expansions"] = [{ attribute: func(expansion[attribute]) for attribute, func in attribute_map.items() if func(expansion[attribute]) } for expansion in game["expansions"]] # Make sure description is not too long game["description"] = self._prepare_description( game["description"]) self.index.save_objects(games)
def get_album_color(artist_df, album, artist): link = artist_df\ .loc[artist_df['album_name'] == album]\ .drop_duplicates(subset=['album_cover']).iloc[0]['album_cover'] img_data = requests.get(link).content Path(data_folder / '{}/covers/'.format(artist)).mkdir(parents=True, exist_ok=True) with open(data_folder / '{}/covers/{}.jpg'.format(artist, album), 'wb') as handler: handler.write(img_data) # Extract 6 colors from an image. colors = colorgram.extract( data_folder / '{}/covers/{}.jpg'.format(artist, album), 10) # Save test colors df = pd.DataFrame({'proportion': [c.proportion for c in colors], 'color': ['rgb({},{},{})'.format(c.rgb.r, c.rgb.g, c.rgb.b) for c in colors]})\ .reset_index() fig = px.bar(df, y='index', x='proportion', color='color', orientation='h', color_discrete_sequence=df['color'].values) plot(fig) return colors
def get_tweet_image_info(tweet): tweetImages = [] tweetColors = [] if 'media' in tweet.entities: for image in tweet.entities['media']: url = image['media_url'] tweetImages.append(url) # if not os.path.isfile(absolute_path_to_images + tweet.id_str + '.png'): #if the file already exists, then dont download it again, just load the old one. response = requests.get(url) img_io = BytesIO(response.content) img = Image.open(img_io) # resp = urllib.request.urlopen(url) # img = np.asarray(bytearray(resp.read()), dtype="uint8") # img = cv2.imdecode(img, cv2.IMREAD_COLOR) # print("HERE5") # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # im_pil = Image.fromarray(img) # cv2.imwrite(absolute_path_to_images + tweet.id_str + '.png',img) # cv2.imshow("Image", img) #Color Analysis: colors = colorgram.extract(img_io, 6) colors.sort(key=lambda c: c.hsl.h) colorsArray = [] for color in colors: colorTemp = {} colorTemp["r"] = color.rgb.r colorTemp["g"] = color.rgb.g colorTemp["b"] = color.rgb.b colorsArray.append(colorTemp) # print(colorsArray) return [tweetImages, colorsArray]
def generate_text_color(self): for item in self.slides: if item.category == 'text': temp_canva = self.canva.copy() temp_canva = np.array(temp_canva) temp_canva = temp_canva[item.y:item.y + item.size[1], item.x:item.x + item.size[0]] temp_canva = Image.fromarray(temp_canva) colors = colorgram.extract(temp_canva, 5) color = colors[0].rgb color_hsv = colorsys.rgb_to_hsv(color.r, color.g, color.b) new_color_hsv = [] for value in color_hsv: new_item = value + 0.5 new_item = new_item if new_item < 1. else (new_item - 1) new_color_hsv.append(new_item) new_color = colorsys.hsv_to_rgb(new_color_hsv[0], new_color_hsv[1], new_color_hsv[2]) item.color = tuple([int(c) for c in new_color])
def extract_color_palette(self, palette_size): colors = colorgram.extract(self.image_input_path, palette_size) color_set_rgb = [ (color.rgb[0], color.rgb[1], color.rgb[2]) for color in colors ] self.color_set_rgb = color_set_rgb print("color palette extracted: ", self.color_set_rgb)
def extract_color(self): clothes_picture = self.picture if clothes_picture: clothes_colors = self.colors.all() # Check if colors an user has are extracted # or selected by the user. if clothes_colors: all_are_different = all([ clothes_colors[0].code != clothes_colors[0].original, clothes_colors[1].code != clothes_colors[1].original, clothes_colors[2].code != clothes_colors[2].original, ]) # Extract 3 colors from an image an user will upload. extracted_colors = colorgram.extract(clothes_picture, 3) # colorgram.extract returns Color objects, which let you access # RGB, HSL, and what proportion of the image was that color. for i in range(3): rgb = extracted_colors[i].rgb # e.g. Rgb(r=217, g=216, b=233) # RGB and HSL are named tuples, so values can be accessed as properties. code = f"rgb({rgb[0]},{rgb[1]},{rgb[2]})" # You can get a proportion of a color # as color.proportion # e.g. 0.34 if clothes_colors: # Change only extracted colors if an user selects colors if are_all_difference: clothes_colors[i].original = code # Change both colors if an user doesn't select else: clothes_colors[i].code = code clothes_colors[i].original = code else: ClothesColor.objects.create(clothes=self, code=code, original=code)
def upload(): if request.method == 'POST': color_data = [] try: userID = str(request.cookies.get('userID')) time = str(datetime.now()) f = request.files['file'] colors = colorgram.extract(f, 6) for item in colors: actual_name, closest_name, hex_code = get_colour_name(item.rgb) proportion = str(format(item.proportion * 100, '.2f')) + '%' color_data.append({ 'name': closest_name, 'hex_approx': hex_code, 'hex_actual': webcolors.name_to_hex(closest_name), 'proportion': proportion }) except: print("error in insert operation") return render_template('index.html', data=color_data, title='Home') finally: return render_template('index.html', data=color_data, title='Home')
async def palette(self, ctx, color_count: int = 5): '''Generate a color palette (default 5 colors) based on an image''' loading_message = await ctx.send(f"{heart} Now loading... {heart}") try: attachment = await self.prev_attachedimg(ctx) if attachment.size > 3000000: await loading_message.delete() raise commands.CommandError('Image cannot be more than 3MB.') async with ClientSession() as session, session.get( attachment.url) as res: image = io.BytesIO(await res.read()) colors = colorgram.extract(image, color_count) imnew = Image.new('RGB', (100 * color_count, 100)) imdraw = ImageDraw.Draw(imnew) color_list = [] for i, color in enumerate(colors): imdraw.rectangle([(i * 100, 0), ((i + 1) * 100, 100)], fill=color.rgb) color_list.append( f"{color.rgb.r} {color.rgb.g} {color.rgb.b} #{color.rgb[0]:02x}{color.rgb[1]:02x}{color.rgb[2]:02x}" ) color_str = '\n'.join(map(str, color_list)) with io.BytesIO() as palette: imnew.save(palette, format='PNG') palette.seek(0) await ctx.send( file=discord.File(fp=palette, filename='palette.png')) await ctx.send(f"`{color_str}`") except IOError: raise commands.CommandError("The file must be an image.") finally: await loading_message.delete()
def get_rgb(image_path): rgb_colors = [] colors = colorgram.extract(image_path, 30) for color in colors: rgb_colors.append(tuple([color.rgb.r, color.rgb.g, color.rgb.b])) return rgb_colors
def extract(image, colors): colors = colorgram.extract(image, colors) result = [] for color in colors: rgb = (color.rgb[0], color.rgb[1], color.rgb[2]) result.append(rgb) return result
def get_colors_from_image(image_path, n_colors): colors_list = [] for color_object in colorgram.extract(image_path, n_colors): r, g, b = color_object.rgb colors_list.append((r, g, b)) return colors_list
def rgb_gen(): rgb_list = [] colors = colorgram.extract('Hirstdot.jpg', 30) for color in colors: rgb = [color.rgb.r, color.rgb.g, color.rgb.b] rgb_list.append(rgb) return rgb_list
def extract_colors(num_of_colors): colors = colorgram.extract("image.jpg", num_of_colors) for color in colors: r=color.rgb.r g=color.rgb.g b=color.rgb.b rgb_colors=(r,g,b) list_of_colors.append(rgb_colors)
def get_image_palette(image, count): """Returns an array of size count of the colors used in the image sorted by darkest first""" colors = colorgram.extract(image, count) colors.sort(key=lambda c: c.rgb.r+c.rgb.g+c.rgb.b) for color in colors: print(color.rgb) return colors
def extract_colors(): # used to extract colors from dot painting, then copied return tuple into color_found_list colors = colorgram.extract('dots_hirst.jpg', 30) colors_list = [] for i in range(10): entry = colors[i].rgb[0:] colors_list.append(entry)
def get_image_colors(image_path, num_colors): # returns a list of colors extracted from the requested image # ARGS: # image: path to image file # num_colors: number of colors to extract colors = colorgram.extract(image_path, num_colors) return [(colors[i].rgb.r, colors[i].rgb.g, colors[i].rgb.b) for i in range(len(colors))]
def get_colors(image, num_colors): """Gets a list of rgb values from a given image.""" colors = colorgram.extract(image, num_colors) rgbs = [] for c in range(num_colors): rgbs.append(colors[c].rgb) return rgbs
def extract_colors() -> list: image = "d18_hirst.jpg" colors = extract(image, 30) return list( map( lambda color: (color.rgb.r / GREYSCALE_COLOR_RANGE, color.rgb.g / GREYSCALE_COLOR_RANGE, color.rgb.b / GREYSCALE_COLOR_RANGE), colors))
def get_rgb_color(image, num): lst = [] for color in colorgram.extract(image, num): r = color.rgb.r g = color.rgb.g b = color.rgb.b if all(x < 245 for x in [r, g, b]): lst.append((r, g, b)) return lst
def func(): with open(extractions_path, 'r') as f: correct_colors = json.load(f)[str(num_colors)] colors = colorgram.extract(image_path, num_colors) assert len(colors) == num_colors for correct_color, color in zip(correct_colors, colors): assert tuple(correct_color[:3]) == color.rgb assert -0.01 < correct_color[3] - color.proportion < 0.01
def __init__(self, file_name, color_dict): self.file_name = file_name self.color_dict = color_dict self.im = Image.open(self.file_name) self.image_size = float( float(self.im.size[1]) * float(self.im.size[0])) self.all_image_colors = colorgram.extract(file_name, 1000) self.all_color_proportion = {} self.get_all_colors_information()
def generate_colors(number_of_colors): extracted_colors = extract("image.jpg", number_of_colors) list_of_colors = [] for color in extracted_colors: r = color.rgb.r g = color.rgb.g b = color.rgb.b list_of_colors.append((r, g, b)) return list_of_colors
def palette_from_image(image): colors = colorgram.extract(image, AMOUNT_OF_COLORS) colors_loop = cycle(colors) rgbs = [] for color in colors_loop: rgbs.append("%02x%02x%02x" % color.rgb) if len(rgbs) == AMOUNT_OF_COLORS: break return rgbs
def extract_colors_from(img: str, count: int): rgb_colors: list[tuple[int, int, int]] = [] colors = colorgram.extract(img, count) for color in colors: r = color.rgb.r g = color.rgb.g b = color.rgb.b rgb_colors.append((r, g, b)) return rgb_colors
def get_colors(): rgb_colors = [] colors = colorgram.extract('image.jpg', 30) for color in colors: r = color.rgb.r g = color.rgb.g b = color.rgb.b new_color = (r, g, b) rgb_colors.append(new_color)
def post(): data = None tags_invalid = True while tags_invalid: data = download_data() tags_invalid = False if "alt_description" in data and data["alt_description"] is not None: keywords = data["alt_description"].split(" ") for kw in disallowed_tags: if kw in keywords: tags_invalid = True print("Tags invalid!") break im_url = data["urls"]["small"] print("Downloading image...", end="") urllib.urlretrieve(im_url, "unsplash-cache.jpg") print(" Done!") print("Extracting colors...", end="") colors = colorgram.extract("unsplash-cache.jpg", 2) print(" Done!") grad_img = Image.new("RGB", (512, 512), "#FFFFFF") print("Generating gradient...", end="") gradient(grad_img, colors[0].rgb, colors[1].rgb) print(" Done!") print("Saving gradient image...", end="") grad_img.save("gradient-cache.png", "PNG") print(" Done!") tweet_text = "Image by " if "name" in data["user"] and data["user"]["name"] is not None: tweet_text += data["user"]["name"] else: tweet_text += data["user"]["username"] if "twitter_username" in data["user"] and data["user"][ "twitter_username"] is not None: tweet_text += " (@" + data["user"]["twitter_username"] + ")" tweet_text += "\n" + data["links"]["html"] tweet_text += "\n\nColors: " + ColorHex( colors[0].rgb) + " and " + ColorHex(colors[1].rgb) tweet_text += "\n\n#unsplashgradientbot" # post tweet print("Publishing Tweet...", end="") tw_api.PostUpdate(tweet_text, ["gradient-cache.png", "unsplash-cache.jpg"]) print(" Done!") print("<< Goodbye! >>")
def rgb_colors_list(image_name, num_of_col): colors = colorgram.extract(image_name, num_of_col) color_list = [] for color in colors: r = color.rgb.r g = color.rgb.g b = color.rgb.b rgb_1 = (r, g, b) color_list.append(rgb_1) return color_list
def extract_colors_from_image(path): try: image_colors = colorgram.extract(path, 6) colors = [{ 'h': color.hsl.h, 's': color.hsl.s, 'l': color.hsl.l, 'ratio': color.proportion } for color in image_colors] except IOError: colors = None return colors