Ejemplo n.º 1
0
    def extract(self, img):
        if isinstance(img, np.ndarray):
            img = Image.fromarray(img, 'RGBA')

        self.colors, pixel_count = extcolors.extract_from_image(img)

        return self.colors
Ejemplo n.º 2
0
def padding_ratio(image, total):
    colors, pixel = extcolors.extract_from_image(image)
    i = 0
    total_percent = 0
    percentage = 0
    for color in colors:
        percentage = color[1] / total * 100
        if i < 3:
            total_percent += percentage
            i += 1
    return total_percent
Ejemplo n.º 3
0
def rgb_avg_pics():
    #change path ending depending on which small pictures are wanted
    new_path = Path("PATH TO FOLDER WHERE YOUR IMAGE SET IS", 'resized_pics')
    try:
        new_dir = os.listdir(new_path)
        colour_dict = {}
        for item in new_dir:
            fullpath = os.path.join(new_path, item)
            if os.path.isfile(fullpath):
                img = Image.open(fullpath)
                colours, pixel_count = extcolors.extract_from_image(img)
                percentage_dom_colour = colours[0][1] / pixel_count
                if percentage_dom_colour > dom_factor_dict[image_dataset]:
                    colour_dict[item] = colours[0][0]
        return colour_dict, new_path
    except FileExistsError:
        print("Error: that folder doesn't exist.")
Ejemplo n.º 4
0
    def get_colors_from_image(self, image):
        """
        Extracts the colors and their percentage in a given image. The white color (255, 255, 255) is not taken into acount.
        :return: dictionary where the keys are the color RGB representation and the values are thei percentage in the image.
        """
        try:
            colors_img, pixel_count = extcolors.extract_from_image(image)
            if len(colors_img) > 1:
                if colors_img[0][0] == (
                        255, 255, 255
                ) and colors_img[0][1] / pixel_count > cfg.white_threshold:
                    total_not_white_pixels = int(pixel_count *
                                                 (1 - cfg.white_threshold))
                else:
                    white_pixels = [
                        x[1] for x in colors_img if x[0] == (255, 255, 255)
                    ][0]
                    total_not_white_pixels = pixel_count - white_pixels
                dict_image_colors = {
                    "_".join([str(c) for c in k]):
                    np.round(v / total_not_white_pixels, 2)
                    for k, v in colors_img
                    if (k != (255, 255, 255) and np.round(
                        v / total_not_white_pixels, 2) >= cfg.threshold_min_pct
                        )
                }
                sum_pct = sum(dict_image_colors.values())
                if sum_pct < 1:
                    dict_image_colors["255_255_255"] = np.round(1 - sum_pct, 2)
            else:
                dict_image_colors = {"255_255_255": 1}

            return {
                k: v
                for k, v in sorted(dict_image_colors.items(),
                                   key=lambda x: x[1],
                                   reverse=True)
            }
        except:
            logger.log("There has been an error removing the background.")
            return None
Ejemplo n.º 5
0
def nbColor_daltonisme(image, total):
    protanopie = []  # Ne voit pas le rouge
    deutéranopie = []  # Ne voit pas le vert
    tritanopie = []  # Ne voit pas le bleu
    color_tab = []
    colors, pixel_count = extcolors.extract_from_image(image)
    above = 0
    for color in colors:
        percentage = color[1] / total * 100
        if percentage > 15:
            above += 1
        if percentage > 5 and color[0][2] > 200 and color[0][
                0] < 200 and color[0][1] < 200:
            tritanopie.append(color)
        if percentage > 5 and color[0][1] > 200 and color[0][
                0] < 200 and color[0][2] < 200:
            deutéranopie.append(color)
        if percentage > 5 and color[0][0] > 200 and color[0][
                1] < 200 and color[0][2] < 200:
            protanopie.append(color)
        color_tuple = (color[0][0], color[0][1], color[0][2], percentage)
        color_tab.append(color_tuple)
    return above, (len(protanopie) + len(deutéranopie) +
                   len(tritanopie)) / len(colors), color_tab
Ejemplo n.º 6
0
def extract_unq_colors(img):
    colors, pixel_count = extcolors.extract_from_image(Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)))

    return colors
Ejemplo n.º 7
0
                                fontFace=0,
                                fontScale=2)
                    contact_point_counter = contact_point_counter + 1
            print("distance_contact:", distance_contact)
            x = x + diameter - distance_contact

            if column == COUNT:
                if row % 2 == 0:
                    x = -radius
                    y = y + math.sqrt(pow(diameter, 2) -
                                      pow(radius, 2)) - distance_contact
                else:
                    x = -diameter
                    y = y + math.sqrt(pow(diameter, 2) -
                                      pow(radius, 2)) - distance_contact

    img = Image.fromarray(blank_image)
    colors, pixel_count = extcolors.extract_from_image(img)
    print("colors:\n", colors)
    print("pixel_count:\n", pixel_count)

    rate_mian_kong = (pixel_count - colors[0][1]) / pixel_count
    print("rate_mian_kong:", rate_mian_kong)

    cv2.imwrite('image/c500_median_line&point.png', blank_image)

    effective_circle = colors[0][1] / (math.pi * pow(radius, 2))
    print("effective_circle:", effective_circle)
    print("contact_line_counter:", contact_line_counter)
    print("contact_point_counter:", contact_point_counter)
Ejemplo n.º 8
0
def create_graph(min, max, values, background = None):
    graph = Image.new('RGB', (1280, 720), (255,255,255))
    graphdraw = ImageDraw.Draw(graph)
    
    if background:
        back = Image.open(background)
        mask = Image.new('L', (IWIDTH, IHEIGHT), 76)
        width = back.size[0]
        back = back.crop((0, int(back.size[1]/2) - int((width/1.777)/2) , width, int(back.size[1]/2)+int( (width/1.777)/2)))
        back = back.resize((IWIDTH,IHEIGHT))
        graph.paste(back, None, mask=mask)
    
    #Draw side lines
    graphdraw.line((40,40,40,680), fill=LINE_COLOR, width = LINE_WIDTH)
    graphdraw.line((40,680,1240,680), fill=LINE_COLOR, width = LINE_WIDTH)
    
    #Draw text on graphic
    graphdraw.text((10,40), str(max), fill = LINE_COLOR)
    graphdraw.text((10,680), str(min), fill = LINE_COLOR)
    
    line_width = round(GRAPH_LINES_WIDTH / len(values))
    line_distance = round(((1200+round(line_width/2)) / len(values)))
    if line_distance < 40: line_distance = 40
    
    
    for index, item in enumerate(values):
        colord = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
        if len(item) == 2:
            value, text = item
            image = None
        elif len(item) == 3:
            value, text, image = item
        else:
            value, text, image = item[0], None, None
        
        if image:
            try:
                img = Image.open(image)
                img.filter(ImageFilter.GaussianBlur(5))
                colors, pixels = extcolors.extract_from_image(img.copy())
                colord = colors[0][1]
            except:
                print('colorpick')
        
        graphdraw.line((80+(line_distance*index), 680, 80+(line_distance*index), round(680-(640*(value/max)))), fill = colord, width=line_width)
        
        if text:
            txt = Image.new('RGB',graphdraw.textsize(text), colord)
            textdraw = ImageDraw.Draw(txt)
            textdraw.text((0,0), text, fill = (255,255,255))
            txt = txt.transpose(Image.ROTATE_90)
            graph.paste(txt, (80+(line_distance*index)-txt.size[0], 680-txt.size[1]) )
        if image:
            try:
                img = Image.open(image)
                if img.size[0] > img.size[1]: rect_side = img.size[1]
                else: rect_side = img.size[0]
                img = img.crop((0,0,rect_side, rect_side))
                img = img.convert('RGBA')
                mask = Image.new('L', img.size, 0)
                maskdraw = ImageDraw.Draw(mask)
                maskdraw.ellipse((0,0) + img.size, fill=255)
                img = img.resize((line_width-1,line_width-1))
                mask = mask.resize((line_width-1,line_width-1))
                graph.paste(img, (80+(line_distance*index)-round(line_width/2)+1, round(680-(640*(value/max)))), mask=mask)
            except:
                print('imagepaste')

            
        
    try:
        graphobj = io.BytesIO()
        graph.save(graphobj, 'PNG')
        graphobj.seek(0)
    except:
        graph.save('graph.png')
    return graphobj
def image_color_extractor(cv_mat,k=5):

    img = Image.fromarray(cv2.cvtColor(cv_mat,cv2.COLOR_BGR2RGB))#### 错误,传入原图cv_mat是rgb_img[y1:y2, x1:x2]
    img = Image.fromarray(cv_mat)#### 错误,传入原图cv_mat是rgb_img[y1:y2, x1:x2]
    colors, pixel_count = extcolors.extract_from_image(img)

    def get_map_color(colors):
        sorted_rgb = [ele[0] for i,ele in enumerate(colors)]
        annoy_map = [color_map(list(c)) for c in sorted_rgb]
        annoy_map = [[tuple(ele[0]), ele[1], ele[2], ele[3]] for i,ele in enumerate(annoy_map)]

        color_fre = dict([i,ele[1]/sum([x[1] for x in colors])] for i,ele in enumerate(colors))
        #print(color_fre)

        tmp_list = []
        indx = []
        tmp_rgb_fre = {}
        for i,ele in enumerate(annoy_map):
            #print(ele)
            ix = annoy_map.index(ele)
            indx.append(ix)
            fre = color_fre.get(i)
            if ele not in tmp_list:
                tmp_list.append(ele)
                tmp_rgb_fre[ix] = fre
            else:
                tmp_rgb_fre[ix] = tmp_rgb_fre[ix] + fre

        annoy_map = tmp_list
        #print(tmp_rgb_fre)

        rgb_fre = [tmp_rgb_fre.get(i) for i in tmp_rgb_fre]
        rgb_standard = [ele[0] for ele in annoy_map] ### rgb list
        hex_standard = [ele[1] for ele in annoy_map]
        name_en = [ele[2] for ele in annoy_map]
        name_cn = [ele[3] for ele in annoy_map]

        return rgb_standard, hex_standard, name_en, name_cn, rgb_fre

    def warm_cold(colors):
        warm_colors = []
        cold_colors = []
        for c in colors:
            r, g, b = c[0]
            if b > r:#color = 'cold'
                cold_colors.append(c)
            else:#color = 'warm'
                warm_colors.append(c)
        warm_colors_sorted = sorted(warm_colors, key=lambda x: x[1], reverse=True)
        cold_colors_sorted = sorted(cold_colors, key=lambda x: x[1], reverse=True)
        return warm_colors_sorted, cold_colors_sorted


    # warms,colds = warm_cold(colors)
    # warm_rgbs,warm_hexs, warm_ne,warm_nc = get_map_color(warms)
    # cold_rgbs, cold_hexs, cold_ne, cold_nc = get_map_color(colds)


    rgb_list, hex_list, names_en, names_cn,rgb_fre = get_map_color(colors)


    Result = {
        "rgbs": rgb_list[:k] if len(rgb_list)>k else rgb_list,
        "hexs": hex_list[:k] if len(rgb_list)>k else hex_list,
        'names_en': names_en[:k] if len(rgb_list)>k else names_en,
        "names_cn": names_cn[:k] if len(rgb_list)>k else names_cn,
        "rgb_fre": rgb_fre[:k] if len(rgb_list)>k else rgb_fre
    }

    return Result