def BasicAgent(img): vectorized = img.reshape((-1, 3)) vectorized = np.float32(vectorized) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 5 attempts = 10 # Running k means, with k = 5 ret, label, center = cv2.kmeans(vectorized, K, None, criteria, attempts, cv2.KMEANS_PP_CENTERS) center = np.uint8(center) res = center[label.flatten()] # Array of 5 representative RGB Values repColors = center print(repColors) result_image = res.reshape((img.shape)) figure_size = 15 plt.figure(figsize=(figure_size / 2, figure_size / 2)) plt.subplot(1, 2, 1), plt.imshow(img) plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(1, 2, 2), plt.imshow(result_image) plt.title('Segmented Image when K = %i' % K), plt.xticks([]), plt.yticks( []) plt.show()
def s1(img): #segmentacionColor image = img num_clusters = 100 # Creamos una copia para poderla manipular a nuestro antojo. image_copy = np.copy(image) pixel_values = image_copy.reshape((-1, 3)) pixel_values = np.float32(pixel_values) stop_criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) number_of_attempts = 10 centroid_initialization_strategy = cv2.KMEANS_RANDOM_CENTERS # Ejecutamos K-Means con los siguientes parámetros: # - El arreglo de pixeles. # - K o el número de clusters a hallar. # - None indicando que no pasaremos un arreglo opcional de las mejores etiquetas. # - Condición de parada. # - Número de ejecuciones. # - Estrategia de inicialización. # # El algoritmo retorna las siguientes salidas: # - Un arreglo con la distancia de cada punto a su centroide. Aquí lo ignoramos. # - Arreglo de etiquetas. # - Arreglo de centroides. _, labels, centers = cv2.kmeans(pixel_values, num_clusters, None, stop_criteria, number_of_attempts, centroid_initialization_strategy) # Aplicamos las etiquetas a los centroides para segmentar los pixeles en su grupo correspondiente. centers = np.uint8(centers) segmented_data = centers[labels.flatten()] # Debemos reestructurar el arreglo de datos segmentados con las dimensiones de la imagen original. segmented_image = segmented_data.reshape(image_copy.shape) return segmented_image
def get_dominent_colors(img, cluster_num=5, cluster='kmeans', if_show=False, name=None): pixels = img.reshape(-1, 3).astype(np.float32) if cluster == 'kmeans': criteria = (cv.TERM_CRITERIA_MAX_ITER, 10, 0.1) flags = cv.KMEANS_RANDOM_CENTERS _, _, centers = cv.kmeans(pixels, cluster_num, None, criteria, 1, flags) elif cluster == 'fcm': import skfuzzy as skf pixels = np.transpose(pixels, (1, 0)) cmeans_res = skf.cmeans(pixels, cluster_num, 2, 1e-4, 100) centers = cmeans_res[0] else: raise NotImplementedError('Unrecognised cluster method.') color_list = np.zeros((cluster_num, 3), dtype='int') for c in range(cluster_num): color_list[c] = centers[c, ::-1].astype('int') if if_show: show_plate(img, name, cluster_num, color_list) return color_list
def subtractiveColor(image, tone): z = image.reshape((-1, 3)) z = np.float32(z) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) ret, label, center = cv2.kmeans(z, tone, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) res = center[label.flatten()] return res.reshape((image.shape))
def _kmeans_cluster(self, bin_img, k=5): ''' ### Now deprecated ! ### K-means clustering to determine possible ROI.\n img: np.array, binary image\n k: int, number of cluster centers\n return: (labels, centers) ''' coords = self._get_pos_for_cluster(bin_img) _, labels, centers = cv.kmeans(coords, k, None, (cv.TERM_CRITERIA_EPS, 0, 0.1), 1, cv.KMEANS_RANDOM_CENTERS) return labels, centers
def clustering_color(img): pixels = np.float32(img) # number of clusters required at end n_clusters = 5 # cv2.TERM_CRITERIA_EPS : stop the algorithm iteration if specified accuracy is reached # cv2.TERM_CRITERIA_MAX_ITER : stop the algorithm after the specified number of iterations # the sum of both allow to stop the iteration when any of the above condition is met criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1) # initial centers are choosen randomly : flags = cv2.KMEANS_RANDOM_CENTERS compactness, labels, centroids = cv2.kmeans(pixels.reshape( (-1, 3)), n_clusters, None, criteria, 10, flags) palette = np.uint8(centroids) dominant_color = palette[np.argmax(stats.itemfreq(labels)[:, -1])] return [x for x in dominant_color]
def getAverageColor(img: np.ndarray) -> str: img = cv2.resize(img, (150, 150)) pixels = np.float32(img.reshape(-1, 3)) n_colors = 5 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1) flags = cv2.KMEANS_RANDOM_CENTERS _, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags) _, counts = np.unique(labels, return_counts=True) dominant = palette[np.argmax(counts)] return dominant
def ColorCluster(img): #img = cv.cvtColor(img,cv2.COLOR_BGR2GRAY) Z = img.reshape((-1, 1)) # convert to np.float32 Z = np.float32(Z) # define criteria, number of clusters(K) and apply kmeans() criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 2 #类别数量 _, label, center = cv.kmeans(Z, K, None, criteria, 10, cv.KMEANS_RANDOM_CENTERS) # Now convert back into uint8, and make original image center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) return res2
def main(): """batch processing for color quantization using K-Means Algorithm""" path1 = 'Data/' path2 = 'Output/' backPath = '../' sorceContent = '00.mov' deletePath1 = 'Data/*' deletePath2 = 'Output/*.png' os.chdir(path1) subprocess.call(['ffmpeg', '-i', '00.mov', '-r', '23', 'frames%06d.png']) os.remove(sorceContent) os.chdir(backPath) dirs = os.listdir(path1) for frame in dirs: if not frame.startswith('.'): print(frame) img = cv2.imread(os.path.join(path1, frame)) Z = img.reshape((-1, 3)) Z = np.float32(Z) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) k_mean = 5 ret, label, center = cv2.kmeans(Z, k_mean, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) cv2.imwrite('Output/' + str(frame), res2) cv2.waitKey(0) cv2.destroyAllWindows() files1 = glob.glob(deletePath1) for i in files1: os.remove(i) os.chdir(path2) #subprocess.call(['mogrify', '*.png', '-spread', '40', '*.png']) subprocess.call([ 'ffmpeg', '-i', 'frames%06d.png', '-framerate', '23', '-pix_fmt', 'yuv420p', 'process.mov' ]) os.chdir(backPath) files2 = glob.glob(deletePath2) for j in files2: os.remove(j)
def paint(image, average_square=(5, 5), sigma_x=0, reshape_size=(-1, 3), criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), k=128): image_blurring = cv2.GaussianBlur(image, average_square, sigma_x) z = image_blurring.reshape(reshape_size) z = np.float32(z) ret, label, center = cv2.kmeans(z, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) res = center[label.flatten()] image_reshape = res.reshape((image_blurring.shape)) return cv2.GaussianBlur(image_reshape, average_square, sigma_x)
def kmeans_color_quantization(): # read img = cv2.imread('./tutorial/data/ryan.jpg') Z = img.reshape((-1, 3)).astype(np.float32) # number of clusters K = 8 # define criteria, number of clusters(K) and apply kmeans() criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) _, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # visualize fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for idx in range(K): this_data = Z[label.ravel() == idx] this_color = np.array( [center[idx, 2] / 255, center[idx, 1] / 255, center[idx, 0] / 255]) ax.scatter(this_data[::10, 0], this_data[::10, 1], this_data[::10, 2], color=this_color) ax.set_xlabel('B') ax.set_ylabel('G') ax.set_zlabel('R') plt.show() # now convert back into uint8, and make original image center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) cv2.imshow('input', img) cv2.waitKey(10) cv2.imshow('output', res2) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('./tutorial/data/ryan_quantized.jpg', res2)
def kmeans_color_clustering(): X = np.random.randint(25, 50, (25, 2)) Y = np.random.randint(60, 85, (25, 2)) Z = np.vstack((X, Y)) # convert to np.float32 Z = np.float32(Z) # define criteria and apply kmeans() criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) _, label, center = cv2.kmeans(Z, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # now separate the data, Note the flatten() A = Z[label.ravel() == 0] B = Z[label.ravel() == 1] # plot the data plt.scatter(A[:, 0], A[:, 1]) plt.scatter(B[:, 0], B[:, 1], c='r') plt.scatter(center[:, 0], center[:, 1], s=80, c='y', marker='s') plt.xlabel('Height'), plt.ylabel('Weight') plt.show()
# create some random weight, height data wei = 25 Z = np.random.randint(25, 50, (1, 2)) for i in range(10): rand = np.random.randint(wei, wei + 50, (25, 2)) Z = np.vstack((Z, rand)) wei = wei + 20 # convert to np.float32 Z = np.float32(Z) count = 10 # define criteria and apply kmeans() criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) ret, label, center = cv2.kmeans(Z, count, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # Now separate the data, Note the flatten() colors = [ 'r', 'g', 'b', 'm', 'c', 'r', 'g', 'b', 'm', 'c', 'r', 'g', 'b', 'm', 'c' ] ravel = label.ravel() for i in range(count): A = Z[ravel == i] plt.scatter(A[:, 0], A[:, 1], c=colors[i]) # Plot the data plt.scatter(center[:, 0], center[:, 1], s=80, c='y', marker='s') plt.xlabel('Height'), plt.ylabel('Weight') plt.show()
y = np.random.randint(175, 255, 25) z = np.hstack((x, y)) z = z.reshape((50, 1)) z = np.float32(z) # plt.hist(z,256,[0,256]),plt.show() # So we have ‘z’ which is an array of size 50, and values ranging from 0 to 255. I have reshaped ‘z’ to a column vector. It will be more useful when more than one features are present. Then I made data of np.float32 type. # Now we apply the KMeans function. Before that we need to specify the criteria. My criteria is such that, whenever 10 iterations of algorithm is ran, or an accuracy of epsilon = 1.0 is reached, stop the algorithm and return the answer. # Define criteria = ( type, max_iter = 10 , epsilon = 1.0 ) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) # Set flags (Just to avoid line break in the code) flags = cv2.KMEANS_RANDOM_CENTERS # Apply KMeans compactness, labels, centers = cv2.kmeans(z, 2, None, criteria, 10, flags) # This gives us the compactness, labels and centers. In this case, I got centers as 60 and 207. Labels will have the same size as that of test data where each data will be labelled as ‘0’,‘1’,‘2’ etc. depending on their centroids. Now we split the data to different clusters depending on their labels. A = z[labels == 0] B = z[labels == 1] # Now we plot A in Red color and B in Blue color and their centroids in Yellow color. # Now plot 'A' in red, 'B' in blue, 'centers' in yellow plt.hist(A, 256, [0, 256], color='r') plt.hist(B, 256, [0, 256], color='b') plt.hist(centers, 32, [0, 256], color='y') plt.show()
# convert to RGB image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # reshape the image to a 2D array of pixels and 3 color values (RGB) pixel_values = image.reshape((-1, 3)) # convert to float pixel_values = np.float32(pixel_values) print(pixel_values.shape) # define stopping criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2) # number of clusters (K) k = 3 _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # convert back to 8 bit values centers = np.uint8(centers) # flatten the labels array labels = labels.flatten() # convert all pixels to the color of the centroids segmented_image = centers[labels.flatten()] # reshape back to the original image dimension segmented_image = segmented_image.reshape(image.shape) # show the image plt.imshow(segmented_image) plt.show()
import numpy as np from cv2 import cv2 as cv img = cv.imread("image.jpg") Z = img.reshape((-1, 3)) print(Z) # convert to np.float32 Z = np.float32(Z) # define criteria, number of clusters(K) and apply kmeans() criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 6 ret, label, center = cv.kmeans(Z, K, None, criteria, 10, cv.KMEANS_RANDOM_CENTERS) # Now convert back into uint8, and make original image center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) cv.imshow('res2', res2) cv.waitKey(0) cv.destroyAllWindows()