topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • Thursday June 20, 2024, 3:14 am
  • Proudly celebrating 15+ years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

Author Topic: [Pre-Release] Image Colour Info Extractor  (Read 2928 times)

KynloStephen66515

  • Animated Giffer in Chief
  • Honorary Member
  • Joined in 2010
  • **
  • Posts: 3,742
    • View Profile
    • Donate to Member
[Pre-Release] Image Colour Info Extractor
« on: May 31, 2023, 08:52 PM »
NANY 2024 Entry Information

Application Name [Python] Image Colour Information Extractor
Version 0.1
Short Description Extract color information, analyze color composition, and generate color palettes from images with the Color Extractor and Analysis Tool.
Supported OSes Anything with Python
Web Page Here
Download LinkDownload Here
System Requirements
  • pip install Pillow colormath webcolors tqdm
Author Clicky my name


Description
The Color Extractor and Analysis Tool is a powerful software solution that allows you to extract color information from images and analyze various aspects of their color composition. With this tool, you can gain insights into the colors present in an image, identify dominant colors, calculate color distribution, find closest color names and HEX codes, and generate color palette images.

Using advanced algorithms, the tool processes your selected image and extracts color information by analyzing each pixel. It identifies unique colors, counts their occurrences, and calculates the average color of the image in both RGB and HSV color spaces. The dominant color, which appears most frequently, is also determined.

The tool provides detailed color analysis by presenting the color distribution in the image. You can see the percentage representation of each color, allowing you to understand the overall color composition. Additionally, the tool identifies color names and their corresponding HEX codes for the colors present in the image. This feature enables you to precisely identify and communicate specific colors.

To further enhance your color analysis, the tool finds similar colors for each unique color present in the image. By comparing the colors with a predefined set of colors, it identifies the closest matches based on color similarity. This capability is valuable for tasks such as color matching and color coordination.

Once the color analysis is complete, the tool saves the extracted color information to a text file for easy reference. The saved file includes the image name, dimensions, number of unique colors, average color values, dominant color, color distribution percentages, color names, HEX codes, and similar colors.

In addition to the color analysis report, the tool generates a visually appealing color palette image. The color palette showcases a collection of colors extracted from the image, allowing you to visualize the overall color scheme. The palette image can be saved separately for further use and sharing.

The Color Extractor and Analysis Tool offers a user-friendly interface that allows you to select image files easily. Whether you choose to provide the image file path as a command-line argument or use the graphical file selection dialog, the tool seamlessly processes the image and provides comprehensive color analysis results.

Whether you are a designer, artist, marketer, or simply interested in understanding the color composition of an image, the Color Extractor and Analysis Tool is a valuable asset. Gain valuable insights into colors, explore their distribution, and create stunning color palettes with ease using this powerful tool.

Features
• Color Information Extraction: Extracts color information from images by analyzing each pixel.
• Dominant Color Identification: Identifies the dominant color in the image based on frequency.
• Average Color Calculation: Calculates the average color of the image in both RGB and HSV color spaces.
• Color Distribution Analysis: Determines the percentage representation of each color, providing insights into color composition.
• Color Name and HEX Code Identification: Finds closest color names and corresponding HEX codes for colors in the image.
• Similar Color Detection: Identifies similar colors by comparing them with a predefined set of colors.
• Color Analysis Report: Generates a comprehensive report with image details, unique colors, dominant color, color distribution, color names, and HEX codes.
• Color Palette Generation: Creates a visually appealing color palette image showcasing the extracted colors.
• Image File Selection: Allows easy selection of image files either through command-line arguments or a graphical file selection dialog.
• Error Logging: Logs any errors that occur during the color extraction process for troubleshooting purposes.

Planned Features
No idea yet



Usage
Installation
Drop an image file on top of the python script
[OR]
run with args: python ceaat.py path/to/img.jpeg

Using the Application
It will do it's thing and spit out a text file and palette file

Uninstallation
Delete it

Example Output
Spoiler
Image: C:/Users/steph/Desktop/FW/fg/1scripts/0a528585-00ca-4a92-9248-0da6edb7e067.jpeg
Size: 540x239
Number of unique colors: 41992
Average color (RGB): (136, 142, 152)
Average color (HSV): (0.6041666666666666, 0.10526315789473684, 152)
Dominant color: (117, 131, 132)
Color Distribution:
(121, 144, 188): 0.00%
(120, 143, 187): 0.01%
(117, 141, 185): 0.01%
(116, 140, 184): 0.00%
(117, 144, 187): 0.02%
(118, 145, 188): 0.01%
(115, 142, 185): 0.01%
(114, 143, 185): 0.01%
(117, 146, 188): 0.01%
(116, 145, 187): 0.02%
(113, 142, 184): 0.00%
(111, 140, 182): 0.00%
(115, 142, 187): 0.01%
(112, 139, 184): 0.00%
(114, 141, 186): 0.00%
(114, 141, 188): 0.00%
[this continues but it's way too much to paste)


Palette Output:
0e5dbcc8-3d9b-4915-8617-df131aa7d378_palette.png[Pre-Release] Image Colour Info Extractor


Mint Green Pink Entertainment Pixel Art Discord Profile Banner.gif
« Last Edit: June 02, 2023, 01:12 PM by KynloStephen66515 »

KynloStephen66515

  • Animated Giffer in Chief
  • Honorary Member
  • Joined in 2010
  • **
  • Posts: 3,742
    • View Profile
    • Donate to Member
Re: [Pre-Release] Image Colour Info Extractor
« Reply #1 on: January 04, 2024, 08:35 PM »
Updated code + detailed documentation [in comments]:

Code: Python [Select]
  1. import sys
  2. import colorsys
  3. from PIL import Image, ImageDraw
  4. import webcolors
  5. from colormath.color_objects import sRGBColor
  6. from datetime import datetime
  7. from tkinter import Tk, filedialog
  8. from tqdm import tqdm
  9.  
  10.  
  11. def calculate_color_difference(color1, color2):
  12.     """
  13.    Calculates the perceptual difference between two color objects
  14.    using the Euclidean distance between their RGB value tuples.
  15.    
  16.    This works by:
  17.    1. Extracting the RGB value tuples for each color object
  18.    2. Calculating the difference between the R, G, and B values
  19.    3. Squaring the differences
  20.    4. Summing the squared differences
  21.    5. Taking the square root of the sum
  22.    
  23.    This gives a measure of the total geometric distance between the
  24.    two colors in RGB space, which corresponds to their visual difference.
  25.    
  26.    Args:
  27.      color1: First color object
  28.      color2: Second color object
  29.      
  30.    Returns:
  31.      Float value representing the perceptual distance between the colors
  32.    """
  33.    
  34.     r1, g1, b1 = color1.get_value_tuple()
  35.     r2, g2, b2 = color2.get_value_tuple()
  36.  
  37.     r_diff = r1 - r2
  38.     g_diff = g1 - g2
  39.     b_diff = b1 - b2
  40.  
  41.     return ((r_diff ** 2) + (g_diff ** 2) + (b_diff ** 2)) ** 0.5
  42.  
  43.  
  44.  
  45. def generate_color_palette(colors, palette_size):
  46.     # Generates a color palette image from a list of RGB color tuples.
  47.     #
  48.     # Args:
  49.     #   colors: List of RGB color tuples.
  50.     #   palette_size: Number of colors to include in the palette.
  51.     #
  52.     # Returns:
  53.     #   Image object containing the generated color palette.
  54.     swatch_size = 100
  55.     palette_width = palette_size * swatch_size
  56.     palette_height = swatch_size
  57.     palette_image = Image.new("RGB", (palette_width, palette_height))
  58.     draw = ImageDraw.Draw(palette_image)
  59.  
  60.     x = 0
  61.     for color in colors:
  62.         draw.rectangle([(x, 0), (x + swatch_size, palette_height)], fill=color, outline="black")
  63.         x += swatch_size
  64.  
  65.     return palette_image
  66.  
  67.  
  68. # Extracts detailed color information from the given image file
  69. # and saves it to a text file and color palette image.
  70. #
  71. # Args:
  72. #   image_path: Path to image file to extract colors from.
  73. #  
  74. # The function opens the image, loops through pixels to collect
  75. # color data, calculates averages and distributions, finds closest  
  76. # CSS color names, generates a color palette image, and saves the
  77. # output to a text file and image file.
  78. def extract_color_information(image_path):
  79.     """Extracts detailed color information from the given image file and saves it to a text file and color palette image.
  80.    
  81.    Args:
  82.      image_path: Path to image file to extract colors from.
  83.      
  84.    The function opens the image, loops through pixels to collect color data, calculates averages and distributions, finds closest CSS color names, generates a color palette image, and saves the output to a text file and image file.
  85.    """
  86.     try:
  87.         # Open and convert the image
  88.         image = Image.open(image_path).convert("RGB")
  89.         width, height = image.size
  90.  
  91.         # Extract color information
  92.         colors, color_counts = set(), {}
  93.         for x in tqdm(range(width), desc="Extracting colors", unit="column"):
  94.             for y in range(height):
  95.                 r, g, b = image.getpixel((x, y))
  96.                 color = (r, g, b)
  97.                 colors.add(color)
  98.                 color_counts[color] = color_counts.get(color, 0) + 1
  99.  
  100.         # Calculate average color and convert to HSV
  101.         average_color = image.resize((1, 1)).getpixel((0, 0))
  102.         average_color_hsv = colorsys.rgb_to_hsv(*average_color)
  103.  
  104.         # Extract dominant color
  105.         dominant_color = max(color_counts, key=color_counts.get)
  106.  
  107.         # Calculate color distribution
  108.         total_pixels = width * height
  109.         color_distribution = {color: count / total_pixels * 100 for color, count in color_counts.items()}
  110.  
  111.         # Find color names and HEX codes
  112.         # Loops through each extracted color from the image
  113.         # Uses webcolors module to find the closest CSS color name and HEX code
  114.         # Appends the name and code to separate lists
  115.         # Catches any errors and skips invalid colors
  116.         color_names, color_hex_codes = [], []
  117.         for color in tqdm(colors, desc="Finding color names", unit="color"):
  118.             try:
  119.                 name = webcolors.rgb_to_name(color)
  120.                 hex_code = webcolors.rgb_to_hex(color)
  121.                 color_names.append(name)
  122.                 color_hex_codes.append(hex_code)
  123.             except ValueError:
  124.                 pass
  125.  
  126.         # Find similar colors
  127.         # Looks up the closest predefined CSS color for each extracted color
  128.         # and stores the result in a dictionary mapping colors to their
  129.         # closest predefined CSS color name
  130.         predefined_colors = webcolors.CSS3_NAMES_TO_HEX.values()
  131.         similar_colors = {min(predefined_colors, key=lambda x: calculate_color_difference(
  132.             sRGBColor(color[0] / 255, color[1] / 255, color[2] / 255),
  133.             sRGBColor.new_from_rgb_hex(x)
  134.         )) for color in tqdm(colors, desc="Finding similar colors", unit="color")}
  135.  
  136.         # Save color information to a text file
  137.         output_file = f"{image_path.rsplit('.', 1)[0]}.txt"
  138.         """Writes extracted color information to output text file.
  139.        
  140.        The output file path is generated from the input image path.
  141.        The file contains the following information:
  142.        
  143.        - Image path
  144.        - Image dimensions
  145.        - Number of unique colors
  146.        - Average color in RGB and HSV
  147.        - Dominant color
  148.        - Color distribution percentages
  149.        - Color names and hex codes
  150.        - Similar colors mapped to closest CSS color names
  151.        """
  152.         with open(output_file, "w") as f:
  153.             f.write(f"Image: {image_path}\n")
  154.             f.write(f"Size: {width}x{height}\n")
  155.             f.write(f"Number of unique colors: {len(colors)}\n")
  156.             f.write(f"Average color (RGB): {average_color}\n")
  157.             f.write(f"Average color (HSV): {average_color_hsv}\n")
  158.             f.write(f"Dominant color: {dominant_color}\n")
  159.             f.write("Color Distribution:\n")
  160.             for color, percentage in color_distribution.items():
  161.                 f.write(f"{color}: {percentage:.2f}%\n")
  162.             f.write("Color Names and HEX Codes:\n")
  163.             for name, hex_code in zip(color_names, color_hex_codes):
  164.                 f.write(f"{name} (HEX: {hex_code})\n")
  165.             f.write("Similar Colors:\n")
  166.             for color in similar_colors:
  167.                 f.write(color + "\n")
  168.  
  169.         # Generate color palette image
  170.         # Saves the generated color palette image to disk and prints completion messages.
  171.         # The color palette image path is generated from the input image path with a _palette suffix.  
  172.         # Completion messages indicate where the color information text file and palette image were saved.
  173.         palette_image = generate_color_palette(list(colors), palette_size=10)
  174.         palette_image_path = f"{image_path.rsplit('.', 1)[0]}_palette.png"
  175.         palette_image.save(palette_image_path)
  176.  
  177.         # Print completion message
  178.         print(f"Color information saved to {output_file}")
  179.         print(f"Color palette image saved to {palette_image_path}")
  180.  
  181.     except Exception as e:
  182.         # Logs error details to a log file when an exception occurs.
  183.         #
  184.         # The current timestamp, error message, and stack trace are written
  185.         # to the error.log file. This allows errors to be tracked over time
  186.         # for debugging.
  187.         timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  188.         error_message = str(e)
  189.         with open("error.log", "a") as error_file:
  190.             error_file.write(f"[{timestamp}] An error occurred: {error_message}\n")
  191.  
  192.  
  193. def prompt_for_image():
  194.     # Prompts the user to select an image file using a file dialog,
  195.     # then extracts color information from the selected image.
  196.     #
  197.     # Opens a file dialog for the user to select an image file. The
  198.     # allowed file types are PNG, JPG, and JPEG images.
  199.     #
  200.     # If an image is selected, calls extract_color_information() on
  201.     # the path to extract colors.
  202.     #
  203.     # If no image is selected, prints a message indicating no image
  204.     # was chosen.
  205.     #
  206.     # No return value. Prompts the user and processes the selected
  207.     # image file if one is chosen.
  208.     Tk().withdraw()
  209.     image_path = filedialog.askopenfilename(title="Select an image file",
  210.                                             filetypes=(("Image files", "*.png *.jpg *.jpeg"), ("All files", "*.*")))
  211.     if image_path:
  212.         extract_color_information(image_path)
  213.     else:
  214.         print("No image file selected.")
  215.  
  216.  
  217. if __name__ == "__main__":
  218.     # If run as a script, check command line arguments for an image path.  
  219.     # If provided, extract colors from that image.
  220.     # Otherwise, prompt the user to select an image file with a dialog.
  221.     if len(sys.argv) > 1:
  222.         image_path = sys.argv[1]
  223.         extract_color_information(image_path)
  224.     else:
  225.         prompt_for_image()