You can download this code by clicking the button below.
This code is now available for download.
This function loads an image from a specified path and returns a random color from it.
Technology Stack : PIL (Python Imaging Library) for image processing, random module for random selection
Code Type : The type of code
Code Difficulty :
def random_color_from_image(image_path):
"""
Load an image from a given path and return a random color from it.
"""
import random
from PIL import Image
# Load the image
img = Image.open(image_path)
img = img.convert('RGB') # Convert image to RGB mode if it's not already
# Create a list of all pixel colors
pixels = list(img.getdata())
# Select a random color from the list
random_color = random.choice(pixels)
return random_color