Exemple #1
0
 def _get_haishoku_palette(cls, image_path):
     from haishoku.haishoku import Haishoku  # pylint: disable=import-error
     palette = Haishoku.getPalette(image_path)
     hex_palette = [
         color_hex_from_list(color) for _percentage, color in palette
     ]
     return hex_palette
Exemple #2
0
    def update_palette_by_image(self, field_name='image'):
        def get_hex_color(rate, rgb):
            return '#' + ''.join('%02X' % i for i in rgb)

        image = getattr(self, field_name, None)
        if not image:
            return

        from haishoku.haishoku import Haishoku
        try:
            palette = Haishoku.getPalette(image.path)
        except FileNotFoundError:
            return

        palette.reverse()
        try:
            self.color0 = get_hex_color(*palette.pop())
            self.color1 = get_hex_color(*palette.pop())
            self.color2 = get_hex_color(*palette.pop())
            self.color3 = get_hex_color(*palette.pop())
            self.color4 = get_hex_color(*palette.pop())
            self.color5 = get_hex_color(*palette.pop())
            self.color6 = get_hex_color(*palette.pop())
            self.color7 = get_hex_color(*palette.pop())
        except IndexError:
            return
Exemple #3
0
 def _get_haishoku_palette(cls, image_path) -> List[HexColor]:
     from haishoku.haishoku import Haishoku  # pylint: disable=import-error,useless-suppression
     palette = Haishoku.getPalette(image_path)
     hex_palette = [
         color_hex_from_list(color) for _percentage, color in palette
     ]
     return hex_palette
Exemple #4
0
def haishokuColor(img):
    # dominant = Haishoku.getDominant(img)
    # Haishoku.showDominant(img)
    # print(dominant)
    palette = Haishoku.getPalette(img)
    x = []
    y = []
    for per, color in palette:
        x.append(per)
        y.append(color)
    print('调色盘色彩比例:\n', palette)
    Haishoku.showPalette(img)
def savePalette(image_path, path, idx):
    # get the palette first
    palette = Haishoku.getPalette(image_path)

    # getnerate colors boxes
    images = []
    for color_mean in palette:
        w = color_mean[0] * 400
        color_box = new_image('RGB', (int(w), 20), color_mean[1])
        images.append(color_box)

    # generate and save the palette
    joint_image(images, path, idx, 'Palette')
Exemple #6
0
    def get_rgb(path, file, idx):
        """获取图片的颜色信息,保存主要颜色和调色板图片,返回元组/Dataframe"""

        # 判断是否存在results/colors文件夹,如果不存在则创建为文件夹
        folder = os.path.exists(path + 'results/colors')
        if not folder:
            os.makedirs(path + 'results/colors')

        # # 获取图片主要颜色元组(R,G,B)
        # dominant = Haishoku.getDominant(file)

        # 获取图片调色板列表[(percentage, (R,G,B)), ...]
        palette = Haishoku.getPalette(file)

        dominant = palette[0]

        # # 保存主要颜色图片
        Haishoku_plus.saveDominant(file, path, idx)

        # 保存调色板图片
        Haishoku_plus.savePalette(file, path, idx)

        # 转换为DataFrame

        df_list = []
        level_dict = {
            0: 'A',
            1: 'B',
            2: 'C',
            3: 'D',
            4: 'E',
            5: 'F',
            6: 'G',
            7: 'H'
        }

        for i, c in enumerate(palette):
            df_color = pd.DataFrame(
                data={
                    'pic': [idx],
                    'level': [level_dict[i]],
                    'percentage': [c[0]],
                    'r': [c[1][0]],
                    'g': [c[1][1]],
                    'b': [c[1][2]],
                    'hex': [hexencode(c[1])]
                })
            df_list.append(df_color)
        df_palette = pd.concat(df_list, ignore_index=True)

        return dominant, df_palette
Exemple #7
0
def getPaletteOfImg(imgPath, contrast_val=1.0, color_val=1.0):
    img = Image.open(imgPath)
    pal = ImagePalette.ImagePalette()
    print(pal)
    contrast = contrast_img(img, contrast_val, color_val)
    print('contrast: {}'.format(contrast))
    pal = img.getpalette()
    print(pal)
    newPalette = []
    palette = Haishoku.getPalette(imgPath)

    for i in range(0, len(palette)):
        for j in palette[i][1]:
            newPalette.append(j)
    print('   Palette: {}'.format(newPalette))
    return newPalette
Exemple #8
0
def generate(img_path,
             palette_size,
             freq_min=None,
             debug=False,
             show_palette=False):
    """returns a list of RGB tuples representing a palette of palette_size numbers of color, by maximum use"""

    try:
        full_palette = Haishoku.getPalette(str(img_path))
        map_palette = full_palette[:palette_size]
        if show_palette:
            Haishoku.showPalette(str(img_path))
    except FileNotFoundError:
        print(
            f"File {img_path} not found, be sure this includes the full or relative path - the folders containing the file, not just the file's name."
        )
        exit()

    if debug:
        print(f' ► Full Palette (Freq,RGB) = {full_palette}')
        print(f' ► Map Reduced Palette (Freq,RGB) = {map_palette}')
        print(f' ► Autopalette threshold = {freq_min}')

    if freq_min:
        output = []
        if map_palette[0][0] < freq_min:
            # return dominant color if no colors exceed threshold
            output = [map_palette[0][1]]
            print('  =Sample Warning: ')
            print(
                f'   No color exceeds in {round(freq_min*100,1)}% sample tile. Color {output[0]} represents highest porportion of sample ({map_palette[0][0]*100}%) and will be used as result.'
            )
        else:
            # filter colors below freq_min
            for freq, rgb in map_palette:
                if freq >= freq_min:
                    output.append(rgb)
        if debug:
            print(f' ► Sample tile palette length: {len(output)}')

    else:
        # return only the RGB values
        output = dict(map_palette).values()

    return output
Exemple #9
0
def display_haishoku(art_image, art_id):

    file = f"static/images/{art_image}"

    hai = Haishoku.loadHaishoku(file)
    palette = Haishoku.getPalette(file)
    
    # palette has two pieces of data, percent used in the color and RGB code
    for pal in palette:
        load_color_palette(pal[1])

        color = Palette(c_percent=pal[0],
                        c_palette=pal[1],
                        artwork_id=art_id)

        db.session.add(color)
        db.session.commit()

    return color
Exemple #10
0
def main():
    path = "/Users/wujianming/Desktop/WechatIMG18547.jpeg"
    # path = "http://wx2.sinaimg.cn/large/89243dfbly1ffoekfainzj20dw05k0u7.jpg"

    # getPalette api
    palette = Haishoku.getPalette(path)

    # getDominant api
    dominant = Haishoku.getDominant(path)

    # showPalette api
    Haishoku.showPalette(path)

    # showDominant api
    # Haishoku.showDominant(path)

    # Haishoku object
    h = Haishoku.loadHaishoku(path)
    print(h.palette)
    print(h.dominant)
Exemple #11
0
def extract_user_palette(filename):
    """Display user image and color palette."""

    def new_image(mode, size, color):
        return Image.new(mode, size, color)

    file = f"static/user_images/{filename}"

    hai = Haishoku.loadHaishoku(file)
    palette = Haishoku.getPalette(file)

    u_color_pal = []

    for item in palette:
        c_pal = item[1]
        pal = new_image('RGB', (100, 100), c_pal)
        u_color_pal.append(c_pal)

    return render_template("user-palette.html", filename=filename,
                                                u_color_pal=u_color_pal)
Exemple #12
0
def main():
    path = "demo_01.png"

    # getPalette api
    palette = Haishoku.getPalette(path)
    print(palette)

    # getDominant api
    dominant = Haishoku.getDominant(path)
    print(dominant)

    # showPalette api
    Haishoku.showPalette(path)

    # showDominant api
    Haishoku.showDominant(path)

    # Haishoku object
    h = Haishoku.loadHaishoku(path)
    print(h.image)
    print(h.palette)
    print(h.dominant)
Exemple #13
0
def main():
    url = "https://img3.doubanio.com/lpic/s27028282.jpg"
    r = requests.get(url)
    path = BytesIO(r.content)

    # getPalette api
    palette = Haishoku.getPalette(path)
    print(palette)

    # getDominant api
    dominant = Haishoku.getDominant(path)
    print(dominant)

    # showPalette api
    Haishoku.showPalette(path)

    # showDominant api
    Haishoku.showDominant(path)

    # Haishoku object
    h = Haishoku.loadHaishoku(path)
    print(h.palette)
    print(h.dominant)
Exemple #14
0
from haishoku.haishoku import Haishoku
from PIL import Image, ImageDraw
import random
from random import randrange
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', required=True, help="url to the image")
parser.add_argument('-a',
                    '--amount',
                    required=True,
                    help="the amount of squares")
parser.add_argument('-r', '--radius', required=True, help="the max radius")
args = parser.parse_args()

palette = Haishoku.getPalette(args.url)
w, h = 800, 800

image = Image.new("RGB", (w, h), random.choice(palette)[1])
layer = ImageDraw.Draw(image)

for i in range(0, int(args.amount)):
    x = randrange(w)
    y = randrange(h)

    r, g, b = random.choice(palette)[1]

    divider = 800 - randrange(0, 600)

    if x >= divider:
        r = r + randrange(100, 200)
Exemple #15
0
authors = []
for each_date in d:
    for each_author in d[each_date]:
        authors.append(each_author[0])
        if each_author[0] not in face:
            face[each_author[0]] = each_author[2]
with open('./get_data/face.py', 'w', encoding="utf-8-sig") as f:
    f.writelines('face = ' + str(face))

for each_author in face:
    if each_author in color:
        continue
    if face[each_author][-3:] == 'gif' or each_author == '开眼视频App':
        color[each_author] = '#000000'
    else:
        color_list = Haishoku.getPalette(face[each_author])
        color_list = sorted(color_list,
                            key=lambda x: x[1][0] + x[1][1] + x[1][2])
        color[each_author] = 'rgb' + \
            str(color_list[int(len(color_list)/2)][1])

with open('./get_data/color.py', 'w', encoding="utf-8-sig") as f:
    f.writelines('color = ' + str(color))

min_fans = 99999999
for each_author in authors:
    c_fans = db['author'].find_one({'name': each_author}, {field: True})[field]
    if c_fans <= min_fans:
        min_fans = c_fans
print(min_fans)
Exemple #16
0
import os
import csv
sys.path.insert(0, "..")
from haishoku.haishoku import Haishoku

folder = "/Users/talamram/Downloads/thike/"

# Count files in selected repository
counter = 0
for file in os.listdir('..'):
    counter += 1
print(str(counter) + 'files counted!')

# Iterate through images in folder and extract dominant colour and palette
# and write them to a csv

path = "test.JPG"

# getPalette api
palette = Haishoku.getPalette(path)

# getDominant api
dominant = Haishoku.getDominant(path)

# Haishoku object
h = Haishoku.loadHaishoku(path)
print('= showpalette =')
print(h.palette)
print('= dominant =')
print(h.dominant)
Exemple #17
0
def haishokuColor(img):
    dominant = Haishoku.getDominant(img)
    print(dominant)
    palette = Haishoku.getPalette(img)
    print(palette)
Exemple #18
0
 def _get_haishoku_palette(cls, image_path):
     from haishoku.haishoku import Haishoku  # pylint: disable=import-error
     palette = Haishoku.getPalette(image_path)
     hex_palette = [color_hex_from_list(color) for _percentage, color in palette]
     return hex_palette
Exemple #19
0
# Far from perfect. Extracts a color palette from a given link to an image
# and tries to draw some rectangles. To be continued ;)

from haishoku.haishoku import Haishoku
from PIL import Image, ImageDraw
import random
from random import randrange

image = "https://image.freepik.com/free-vector/cool-colors-abstract-hand-painted-background_23-2148293333.jpg"

palette = Haishoku.getPalette(image)
w, h = 800, 800

img = Image.new("RGB", (w, h))
img1 = ImageDraw.Draw(img)

for i in range(0, 30):
    print(random.choice(palette)[1])
    r, g, b = random.choice(palette)[1]

    color = "rgb(" + str(r) + "," + str(g) + "," + str(b) + ")"

    endx = randrange(1)
    endy = randrange(1)

    r1 = randrange(w)
    r2 = randrange(h)

    shape = [(i * h, i * w), (i, 5)]

    img1.rectangle(shape, fill=color, outline=color)
Exemple #20
0
                            (screenheight - height) / 2 - 80)
    window.geometry(size)


def myNewSize(a1):
    width = a1.size[0]
    height = a1.size[1]
    while (width > 500 or height > 500):
        width = 0.9 * width
        height = 0.9 * height
    return width, height


# 窗口居中

palette = Haishoku.getPalette(fp)
palette2 = Haishoku.getPalette2(fp)
#导入

palettePic1 = Haishoku.showPalette(fp)
palettePic2 = Haishoku.showPalette2(fp)
# 配色可视化

colorF = toPalette(palette)
colorF2 = toPalette(palette2)

window = tk.Tk()
window.title('调色盘')
window.configure(background='#323232')

pic = Image.open(fp)
Exemple #21
0
def gen_colors(img):
    """Generate a colorscheme using Colorz."""
    palette = Haishoku.getPalette(img)
    return [util.rgb_to_hex(col[1]) for col in palette]
Exemple #22
0
def get_color_palette(image):
    palette = Haishoku.getPalette(image)
    return palette
def get_color_list(path):
    try:
        return Haishoku.getPalette(path)
    except Exception:
        return get_color_list(path)
Exemple #24
0
import requests
import sys
import json
import os  # want to make a new directory/folder for each set of color palettes

from haishoku.haishoku import Haishoku
from PIL import Image

img_path = "https://images.metmuseum.org/CRDImages/as/web-large/DP122117.jpg"

#returns a Haishoku instance, used to read the file
hai = Haishoku.loadHaishoku(img_path)

palette = Haishoku.getPalette(img_path)  # (percentage of color (RGB values))


def new_image(mode, size, color):
    return Image.new(mode, size, color)


def create_color_palette():
    for item in palette:
        # idx 0 is the percentage of color on the image
        c_pal = item[1]  # need to keep this as a tuple, RGB color codes
        pal = new_image('RGB', (100, 100), c_pal)

        # create a new image in in RGB mode, with 100X100 px, as the RGB color

        # trying to save all color palette images in a folder named based on the artwork's title
        # folder_name = "static/color_palette/{art_title}"
        # os.makedirs(folder_name)
Exemple #25
0
from haishoku.haishoku import Haishoku
from PIL import Image
import pprint

img_path = 'images/kershisnik.jpg'
haishoku = Haishoku.loadHaishoku(img_path)

Haishoku.showPalette(img_path)
palette = Haishoku.getPalette(img_path)
print('palette: {}'.format(palette))