Skip to content

Instantly share code, notes, and snippets.

@zidniryi
Created September 12, 2023 04:29
Show Gist options
  • Save zidniryi/dbd8a18449f2e429e329e4fe98f4ddab to your computer and use it in GitHub Desktop.
Save zidniryi/dbd8a18449f2e429e329e4fe98f4ddab to your computer and use it in GitHub Desktop.
konsepkoding opencv
import cv2
import numpy as np
import requests
from urllib.request import urlopen
from io import BytesIO
from IPython.display import Image, display
# Function to detect dominant colors in an image
def detect_colors(image_url, num_colors=5):
# Download the image from the URL
response = urlopen(image_url)
image_data = BytesIO(response.read())
image = cv2.imdecode(np.asarray(bytearray(image_data.read()), dtype=np.uint8), -1)
# Convert image to RGB
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Reshape the image to a list of pixels
pixels = image_rgb.reshape((-1, 3))
# Perform k-means clustering to find dominant colors
k = num_colors
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, 0.2)
_, labels, centers = cv2.kmeans(pixels.astype(np.float32), k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Convert the color centers to uint8
centers = np.uint8(centers)
# Sort the colors by frequency
unique_labels, counts = np.unique(labels, return_counts=True)
color_counts = list(zip(unique_labels, counts, centers))
color_counts.sort(key=lambda x: x[1], reverse=True)
# Extract the dominant colors
dominant_colors = [tuple(color[2]) for color in color_counts]
return dominant_colors
# Input image URL
image_url = input("Enter the image URL: ")
# Detect dominant colors
num_colors = 5 # You can adjust this number as needed
dominant_colors = detect_colors(image_url, num_colors)
# Display the dominant colors
print("Dominant Colors:")
for i, color in enumerate(dominant_colors, start=1):
print(f"Color {i}: RGB {color}")
# Display the image
display(Image(url=image_url))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment