Using K-means Clustering algorithm to recognize picture main colors

Source: Internet
Author: User
Tags diff min

Identify the main colors of the picture this, there are seemingly several ways, but the most accurate, most elegant solution or using clustering algorithm to do ...

Directly on the code .... However, I test the results indicated that the use of PHP to do, inefficient, PHP is not suitable for this large-scale operation ~ ~ ~, with Nodejs do efficiency can be higher than 100 times times.

The code is as follows Copy Code

<?php

$start = Microtime (TRUE);

Main ();

function Main ($img = ' colors_files/t1ox3exldxxxcqfym._111424.jpg ')

{

List ($width, $height, $mime _code) = getimagesize ($img);

$im = null;

$point = Array ();

Switch ($mime _code)

{

# jpg

Case 2:

$im =imagecreatefromjpeg ($IMG);

Break

# png

Case 3:

Default

Exit (' Wipe, what image? Can not parse ah ');

}

$new _width = 100;

$new _height = 100;

$pixel = Imagecreatetruecolor ($new _width, $new _height);

Imagecopyresampled ($pixel, $im, 0, 0, 0, 0, $new _width, $new _height, $width, $height);

Run_time ();

$i = $new _width;

while ($i –)

{

# Reset Height

$k = $new _height;

while ($k –)

{

$rgb = Imagecolorat ($im, $i, $k);

Array_push ($point, Array (' R ' => ($rgb >>) & 0xFF, ' G ' => ($rgb >> 8) & 0xFF, ' B ' => $rgb & 0 XFF));

}

}

Imagedestroy ($im);

Imagedestroy ($pixel);

Run_time ();

$color = Kmeans ($point);

Run_time ();

foreach ($color as $key => $value)

&nb
Sp {

Echo ' <br><span style= ' Background-color: '. Rgbtohex ($value [0]). ' > '. Rgbtohex ($value [0]). ' </span> ';

}

}

function Run_time ()

{

Global $start;

Echo ' <br/> consumption: ', Microtime (TRUE)-$start;

}

function Kmeans ($point =array (), $k =3, $min _diff=1)

{

Global $ii;

$point _len = count ($point);

$clusters = Array ();

$cache = Array ();

for ($i =0; $i < 256; $i + +)

{

$cache [$i] = $i * $i;

}

# randomly generated k value

$i = $k;

$index = 0;

while ($i –)

{

$index = Mt_rand (1, $point _len-100);

Array_push ($clusters, Array ($point [$index], Array ($point [$index]));

}

Run_time ();

$point _list = Array ();

$run _num = 0;

while (TRUE)

{

foreach ($point as $value)

{

$smallest _distance = 10000000;

# Find the point with the smallest distance

# index is used to hold the nearest K value of point

$index = 0;

$i = $k;

while ($i –)

{

$distance = 0;

foreach ($value as $key => $p 1)

{

&n
Bsp if ($p 1 > $clusters [$i][0][$key])

{

$distance + + $cache [$p 1-$clusters [$i][0][$key]];

}

Else

{

$distance + + $cache [$clusters [$i][0][$key]– $p 1];

}

}

$ii + +;

if ($distance < $smallest _distance)

{

$smallest _distance = $distance;

$index = $i;

}

}

$point _list[$index] = $value;

}

$diff = 0;

# a 1 Iteration k value

$i = $k;

while ($i –)

{

$old = $clusters [$i];

# Move to the center of the queue

$center = Calculatecenter ($point _list[$i], 3);

# forming a new K-value collection queue

$new _cluster = Array ($center, $point _list[$i]);

$clusters [$i] = $new _cluster;

# calculates the location of the new K value and the point where the queue is located

$diff = Euclidean ($old [0], $center);

}

# to determine if there is enough aggregation

if ($diff < $min _diff)

{

Break
>

}

}

Echo '-> '. $ii;

return $clusters;

}

# calculate 2-point distance

$ii = 0;

function Euclidean ($p 1, $p 2)

{

$s = 0;

foreach ($p 1 as $key => $value)

{

$temp = ($value – $p 2[$key]);

$s + + $temp * $temp;

}

return sqrt ($s);

}

# move K values to the center of all points

function Calculatecenter ($point _list, $attr _num) {

$vals = Array ();

$point _num = 0;

$keys = Array_keys ($point _list[0]);

foreach ($keys as $value)

{

$vals [$value] = 0;

}

foreach ($point _list as $arr)

{

$point _num++;

foreach ($arr as $key => $value)

{

$vals [$key] + + = $value;

}

}

foreach ($keys as $index)

{

$vals [$index] = $vals [$index]/$point _num;

}

return $vals;

}

function Rgbtohex ($r, $g = ", $b =")

{

if (Is_array ($r))

{

$b = $r [' B '];

$g = $r [' g '];


$r = $r [' R '];

}

$hex = "#";

$hex. = Str_pad (Dechex ($r), 2, ' 0′, str_pad_left);

$hex. = Str_pad (Dechex ($g), 2, ' 0′, str_pad_left);

$hex. = Str_pad (Dechex ($b), 2, ' 0′, str_pad_left);

return $hex;

}

?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.