Exemplo n.º 1
0
 def extract_colors(self):
     # Get file name of image to process
     print("Extracting colors from: ", self.filename)
     image_name = self.filename
     # Open the specified image and get its dimensions
     my_image = PIL.Image.open(image_name)
     width, height = my_image.size
     pixels = width * height
     # Extract image colors with relevant number of pixels
     colors, pixel_count = extcolors.extract_from_path(
         image_name)  # second argument fo assignment IS required
     # Display image color palette
     self.colors_list = []
     for color in colors:
         self.colors_list.append(
             (rgb_to_hex(color[0]), "{0:.00%}".format(color[1] / pixels)))
     return
Exemplo n.º 2
0
def mask_border() -> str:                                                      # Masks the Image and returns Color of the Border
    img= cv2.imread('new.png')
    cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    w ,h = int(img.shape[0]) , int(img.shape[1])
    min_ori = min(w,h)
    bw = round(0.03 * min_ori)                                                 # Width of border in pixels to be masked
    mask = np.ones(img.shape[:2], dtype = "uint8")
    cv2.rectangle(mask, (bw,bw),(img.shape[1]-bw,img.shape[0]-bw), 0, -1)
    output = cv2.bitwise_and(img, img, mask = mask)
    cv2.imwrite('output.png',output)
    colors, pixel_count = extcolors.extract_from_path("output.png")

    try : 
        col_str = get_hex_value(colors[1][0])
    except :
        col_str = get_hex_value(colors[0][0])
    return col_str
Exemplo n.º 3
0
def apiView(request):
    image_url = request.GET['src']
    colors, pixel_count = extcolors.extract_from_path(
        requests.get(image_url, stream=True).raw)
    border_avg = find_avg_border(image_url)
    border_color = (0, 0, 0)
    dominant_color = (0, 0, 0)
    for color in colors:
        if euclid_dist(border_avg, color[0]) < 20:
            border_color = (color[0])
            break
    for color in colors:
        if color[0] != border_color:
            dominant_color = (color[0])
            break

    data = {
        "logo_border": rgbToHex(border_color),
        "dominant_color": rgbToHex(dominant_color)
    }
    result = apiSerailizer(data).data
    return Response(result)
Exemplo n.º 4
0
    async def extract_colors(self,
                             image_path: str,
                             tolerance: int = None,
                             limit: int = None) -> list:
        """Extrait les X couleurs les plus dominantes de l'image

        Renvoie une liste des couleurs (en hexidécimal) extraites avec le pourcentage arrondi qu'ils représentent sur l'image"""
        tolerance = tolerance if tolerance else await self.config.extcolors_tolerance(
        )
        limit = limit if limit else await self.config.extcolors_limit()

        try:
            colors, pixel_count = extcolors.extract_from_path(image_path,
                                                              tolerance,
                                                              limit=limit)
        except:
            raise ColorExtractError(
                "Erreur dans l'extraction des couleurs de l'image")
        else:
            colors = [(f"#{''.join(f'{hex(c)[2:].upper():0>2}' for c in clr)}",
                       round(pixnb / pixel_count * 100, 2))
                      for clr, pixnb in (k for k in colors)]
            return colors
Exemplo n.º 5
0
def image_extcolor(imgFile, k=5):

    colors, pixel_count = extcolors.extract_from_path(imgFile)

    def RGB2HEX(color):  ##### 颜色转化
        return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]),
                                            int(color[2]))

    sorted_hex = [RGB2HEX(ele[0]) for ele in colors]
    sorted_counts = [(i, ele[1]) for i, ele in enumerate(colors)]
    sorted_rgb = [ele[0] for i, ele in enumerate(colors)]
    sorted_names = [(colour_name_mapping(i)[:2]) for i in sorted_rgb]
    rgb_percentage = [(ele[1] / pixel_count) for ele in sorted_counts]
    cluster_collocation = [Color2Collocation[ele[-1]]
                           for ele in sorted_names]  ### 颜色色系,映射到居其家居
    cluster_collocation = [(i, COLOR_COLLOCATION[i])
                           for i in cluster_collocation]

    Result = {
        "k":
        k if len(colors) >= k else len(colors),
        "sorted_counts":
        sorted_counts[:k] if len(colors) > k else sorted_counts,
        "sorted_rgb":
        sorted_rgb[:k] if len(colors) > k else sorted_rgb,
        "sorted_hex":
        sorted_hex[:k] if len(colors) > k else sorted_hex,
        "sorted_names":
        sorted_names[:k] if len(colors) > k else sorted_names,
        "rgb_percentage":
        rgb_percentage[:k] if len(colors) > k else rgb_percentage,
        "color_collocation":
        cluster_collocation[:k] if len(colors) > k else cluster_collocation
    }

    return Result, colors
Exemplo n.º 6
0
def get_color() -> str:                                                        # Returns the Dominant Color from the Image
    colors, pixel_count = extcolors.extract_from_path("new.png")
    col_str = get_hex_value(colors[0][0])
    return col_str
Exemplo n.º 7
0
def test_extraction_white_with_transparency():
    data_path = _get_data_path("16x16_8x8_white_square_transparent_border.png")
    colors, pixel_count = extcolors.extract_from_path(data_path)
    expected = [((255, 255, 255), 64)]
    assert colors == expected
Author = "__ABHISHEK MISHRA__"
print(Author)
output_form = "PLEASE NOTE THAT OUTPUT IS IN FORM OF\n hex-code, \n rgb-ratio, \n hsl-ratio, \n hsv-ratio, \n color-name, \n cmyk-ratio, \n XYZ-value, \n svg-url, \n base-value \n"
print(output_form)
import extcolors  #pip install extcolor
from selenium import webdriver  #pip install selenium
from bs4 import BeautifulSoup  #pip install bs4
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(options=options)
colors, pixel_count = extcolors.extract_from_path("medium.jpg")  #image path
akm = ""
for i in colors:
    for j in range(3):
        #a+hex(list(i[0])[j])
        if (list(i[0])[j] in range(0, 16)):
            akm = akm + "0" + hex(list(i[0])[j])[2:4]
        else:
            akm = akm + hex(list(i[0])[j])[2:4]
    #print(a)
    url = (f"https://www.thecolorapi.com/id?hex={akm}&format=html"
           )  #thecolorapi.com
    driver.get(url)
    content = driver.page_source
    soup = BeautifulSoup(content, 'html.parser')  #web scrapping
    for a in soup.findAll('table', attrs={'pure-table'}):
        s = a.find('td')
        print(s.text)
    print("\n")
    akm = ""
Exemplo n.º 9
0
def main():
    parser = argparse.ArgumentParser(
        description="Extract colors from a specified image. "
        "Colors are grouped based on visual similarities using the CIE76 formula."
    )
    parser.add_argument("--version",
                        action="version",
                        version=f"%(prog)s {__version__}")
    parser.add_argument("path", nargs=1, metavar="PATH")
    parser.add_argument(
        "-t",
        "--tolerance",
        nargs="?",
        type=parse_tolerance,
        default=DEFAULT_TOLERANCE,
        const=DEFAULT_TOLERANCE,
        metavar="N",
        help=
        "Group colors to limit the output and give a better visual representation. "
        "Based on a scale from 0 to 100. Where 0 won't group any color and 100 will group all colors into one. "
        "Tolerance 0 will bypass all conversion. "
        "Defaults to {}.".format(DEFAULT_TOLERANCE))
    parser.add_argument(
        "-l",
        "--limit",
        nargs="?",
        type=parse_limit,
        metavar="N",
        help=
        "Upper limit to the number of extracted colors presented in the output."
    )
    parser.add_argument("-s",
                        "--silence",
                        action="store_true",
                        help="Silences the default output. "
                        "Doesn't effect any other output option.")
    parser.add_argument("-i",
                        "--image",
                        nargs="?",
                        default=None,
                        const=True,
                        metavar="NAME",
                        help="Output the result to an image palette. "
                        "A name for the file can be supplied.")
    parser.add_argument(
        "-g",
        "--gpl",
        nargs="?",
        default=None,
        const=True,
        metavar="NAME",
        help="Output the result to a GIMP color palette (GPL). "
        "A name for the palette can be supplied.")
    args = parser.parse_args()

    path = args.path[0]
    original_filename = os.path.splitext(os.path.basename(path))[0]
    colors, total = extract_from_path(path, args.tolerance, args.limit)
    timestamp = time.strftime("%Y-%m-%d %H%M%S", time.localtime())

    if not args.silence:
        print_result(colors, total)
    if args.image:
        filename = construct_filename(original_filename, args.image, timestamp,
                                      ".png")
        image_result(colors, 150, filename)
    if args.gpl:
        palette = args.gpl if isinstance(args.gpl, str) else original_filename
        filename = construct_filename(original_filename, args.gpl, timestamp,
                                      ".gpl")
        gimp_color_palette_result(colors, filename, palette)