Untitled

 avatar
unknown
plain_text
5 months ago
1.5 kB
2
Indexable
import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

def pixelate_image(image, pixel_size):
    # Resize the image to a smaller version (100x100 grid in this case)
    small_image = cv2.resize(image, (100, 100), interpolation=cv2.INTER_LINEAR)
    
    # Scale it back to original size for better visual representation
    pixelated_image = cv2.resize(small_image, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
    
    return pixelated_image

def quantize_image(image, n_colors=10):
    # Reshape the image to a 2D array of pixels
    pixels = image.reshape(-1, 3)

    # Use K-means clustering to find the most common colors
    kmeans = KMeans(n_clusters=n_colors)
    kmeans.fit(pixels)

    # Replace each pixel by its closest color
    new_colors = kmeans.cluster_centers_[kmeans.predict(pixels)]
    quantized_image = new_colors.reshape(image.shape).astype(np.uint8)
    
    return quantized_image

# Load image (you'll replace this with the uploaded image path)
image = cv2.imread('path_to_your_image.jpg')

# Step 1: Quantize the image to 10 colors
quantized_image = quantize_image(image, n_colors=10)

# Step 2: Pixelate the image to fit the grid
pixelated_image = pixelate_image(quantized_image, pixel_size=3)  # Each pixel piece is 3mm

# Display or save the result
cv2.imwrite('output_mosaic_image.jpg', pixelated_image)
plt.imshow(cv2.cvtColor(pixelated_image, cv2.COLOR_BGR2RGB))
plt.show()
Editor is loading...
Leave a Comment