Split Image In N Images, Where N Is The Number Of Colors Appearing On It
I'm trying to split an image depending on the colors it contains. My previous steps have been to simplify it to just 3 colors using the KMeans algorithm that Sklearn offers and I g
Solution 1:
You can find the unique colours in your image with np.unique()
and then iterate over them setting each pixel to either white or black depending whether it is equal to that colour or not:
#!/usr/bin/env python3import cv2
import numpy as np
# Load image
im = cv2.imread('cheese.png')
# Reshape into a tall column of pixels, each with 3 RGB pixels and get unique rows (colours)
colours = np.unique(im.reshape(-1,3), axis=0)
# Iterate over the colours we foundfor i,colour inenumerate(colours):
print(f'DEBUG: colour {i}: {colour}')
res = np.where((im==colour).all(axis=-1),255,0)
cv2.imwrite(f'colour-{i}.png', res)
Sample Output
DEBUG: colour 0: [0 0 0]DEBUG: colour 1: [0 141 196]DEBUG: colour 2: [1 102 133]
Solution 2:
color1 = (0,0,160)
color2 = (0,160,160)
color3 = (160,160,160)
img = np.zeros((640,480,3),np.uint8)
img[100:200,100:200] = color1img[150:250,150:250] = color2img[200:300,200:300] = color3
first_color_indices = np.where(np.all(img == color1,axis=-1))
second_color_indices = np.where(np.all(img == color2,axis=-1))
third_color_indices = np.where(np.all(img == color3,axis=-1))
img1 = np.zeros_like(img)
img1[first_color_indices]=color1
img2 = np.zeros_like(img)
img2[second_color_indices]=color2
img3 = np.zeros_like(img)
img3[third_color_indices]=color3
cv2.imshow('origin', img)
cv2.imshow('img1', img1)
cv2.imshow('img2', img2)
cv2.imshow('img3', img3)
cv2.waitKey(0)
Post a Comment for "Split Image In N Images, Where N Is The Number Of Colors Appearing On It"