Applying k-mean algorithm to image patches

Viewed 33

I want to apply k-mean algorithm to image patches, is it possible ? Think I have an image and splitted into 9 patches. Then I applied k-mean algorithm to all of them by seperately and joined them. Is it possible ? I tried to sum of 9 centroid pixel values and divide into 9 so patches length but it does not give same answer when I apply it directly image and there is so difference.

Here my code:

import cv2
import numpy
import matplotlib.pyplot as plt
import patchify


image = cv2.imread(r"image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#image = numpy.resize(image,(2000,2500,3)) if it is needed
patched_image = patchify.patchify(image, (250,250,3),step = 250)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.000000000000000000000002)
k = 3
all_centers = []
all_indexes = []


for i in range(0,patched_image.shape[0]):
    for j in range(0,patched_image.shape[1]):
        img = patched_image[i,j][0]
        pixel_values = img.reshape((-1, 3))
        pixel_values = numpy.float32(pixel_values)
        
        _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
        centers = numpy.uint8(centers)
        all_centers.append(centers)
        indexes = centers.argsort(axis = 0)[:,0]
        all_indexes.append(indexes)
        
        labels = labels.flatten()

        segmented_image = centers[labels]

        patched_image[i,j][0]= segmented_image.reshape(img.shape)
all_centers = numpy.array(all_centers)
all_indexes = numpy.array(all_indexes)
c = numpy.where(all_indexes == 0)
t = all_centers[c]
# t is centroid values of label 0 

unpatched_image = patchify.unpatchify(patched_image, image.shape)

Here an image to use as sample.

enter image description here

0 Answers
Related