Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I am no expert in OpenCV so I will give a general advice that relates to your question K-means takes list of vectors which is essentially a matrix:</p> <pre><code>[x0, y0, r0, g0, b0] [x1, y1, r1, g1, b1] [x2, y2, r2, g2, b2] . . . </code></pre> <p>You are giving it an image which is not going to work. You first have to convert the image to this k-means matrix format. For each pixel of the source image you have one row in the resulting matrix. Also note that you should scale the values so that they all have similar values. If you don't do that, x and y coordinates will usually have much higher "gravity" than the color which leads to unsatisfactory results. C++ pseudocode:</p> <pre><code>int pixel_index = 0; for (int y = 0; y &lt; image height; y++) { for (int x = 0; x &lt; image width; x++) { matrix[pixel_index][0] = (float)x / image width; matrix[pixel_index][1] = (float)y / image height; matrix[pixel_index][2] = (float)pixel(x, y).r / 255.0f; matrix[pixel_index][3] = (float)pixel(x, y).g / 255.0f; matrix[pixel_index][4] = (float)pixel(x, y).b / 255.0f; } } // Pass the matrix to kmeans... </code></pre> <p>As a result, you get labels of each individual pixel which corresponds to the cluster it has been assigned to. You then need to determine the color of the clusters - this can vary from taking the center pixel color value to computing an average/median color of the cluster. After you determine the color, just walk the image and set pixels to their cluster colors:</p> <pre><code>for (int y = 0; y &lt; image height; y++) { for (int x = 0; x &lt; image width; x++) { int index = y * image width + x; // This corresponds to pixel_index above int cluster_index = labels[index]; // 0 to 7 in your case Color color = colors[cluster_index]; // Colors is an array of 8 colors of the clusters image.setpixel(x, y, color) } } </code></pre> <p>If you prefer to use HSV instead of RGB, just use HSV values instead of RGB ones. </p> <p>It is possible that OpenCV has functions that perform exactly the conversion I described above but I was unable to quick find them using Google.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload