Skip to content

Instantly share code, notes, and snippets.

@mikesurowiec
Last active February 14, 2024 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesurowiec/f557f7803d63030991a8425b9a119d35 to your computer and use it in GitHub Desktop.
Save mikesurowiec/f557f7803d63030991a8425b9a119d35 to your computer and use it in GitHub Desktop.
# pip install opencv-python numpy
import cv2
import numpy as np
import sys
def color_percentage(image_path, target_color):
# Read the image
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) # Use cv2.IMREAD_UNCHANGED to keep the alpha channel
# Convert BGR to RGBA (if necessary)
if image.shape[2] == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)
# Convert image to numpy array
image_array = np.array(image)
# Flatten the array
flattened_array = image_array.reshape(-1, 4)
# Count pixels matching the target color
matching_pixels = (flattened_array[:, :3] == target_color).all(axis=1).sum()
# Count transparent pixels
transparent_pixels = (flattened_array[:, 3] == 0).sum()
# Calculate total pixels excluding transparent ones
total_pixels = flattened_array.shape[0] - transparent_pixels
# Calculate percentage
percentage = (matching_pixels / total_pixels) * 100 if total_pixels > 0 else 0
return [percentage, matching_pixels, total_pixels, transparent_pixels]
def pixels_to_inches(area_pixels, ppi):
# Convert area from square pixels to square inches
area_inches = area_pixels / (ppi ** 2)
return area_inches
def get_image_path():
if len(sys.argv) > 1:
return sys.argv[1]
else:
print("Please provide the image path as a command line argument.")
sys.exit()
image_path = get_image_path()
target_color = [255, 255, 255]
image = cv2.imread(image_path)
# Get the height and width of the image
height, width, _ = image.shape
# Print the height and width
print(f"Image Size: Width: {width}, Height: {height}")
percentage, matching_pixels, total_pixels, transparent_pixels = color_percentage(image_path, target_color)
print(f"Matching pixels: {matching_pixels}, Total pixels: {total_pixels}, Transparent pixels: {transparent_pixels}")
print(f"Target color percentage (excl transparent px): {percentage}%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment