Use k-means clustering algorithm to identify dominant image tones

Source: Internet
Author: User

Because it is too troublesome to use php to write the image's primary color recognition function, I would like to introduce how to use the k-means clustering algorithm to identify the Dominant Color of the image, which is 100 times better than php.

There are several methods on the Internet to identify dominant image tones. However, the most accurate and elegant solution is to use clustering algorithms...

Directly go to the code .... However, my test results show that PHP is not efficient, and PHP is not suitable for such large-scale operations ~~~, The efficiency of using nodejs is about 100 times higher...

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? It cannot be parsed ');

}

 

$ 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> 16) & 0xFF, 'G' => ($ rgb> 8) & 0xFF, 'B' => $ rgb & 0xFF ));

}

}

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 I <256; $ I ++)

{

$ Cache [$ I] = $ I * $ I;

}

 

# Random k value generation

$ 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;

 

# Finding the point with the smallest distance

# Index is used to save the K value closest to the point

$ Index = 0;

$ I = $ k;

While ($ I -)

{

$ Distance = 0;

Foreach ($ value as $ key => $ p1)

{

& N
Bsp; if ($ p1> $ clusters [$ I] [0] [$ key])

{

$ Distance + = $ cache [$ p1-$ clusters [$ I] [0] [$ key];

}

Else

{

$ Distance + = $ cache [$ clusters [$ I] [0] [$ key]-$ p1];

}

}

 

$ Ii ++;

 

If ($ distance <$ smallest_distance)

{

$ Smallest_distance = $ distance;

$ Index = $ I;

}

}

$ Point_list [$ index] [] = $ value;

}

 

$ Diff = 0;

#1 iteration K value

$ I = $ k;

While ($ I -)

{

$ Old = $ clusters [$ I];

 

# Move to queue Center

$ Center = calculateCenter ($ point_list [$ I], 3 );

# Forming a new K value set queue

$ New_cluster = array ($ center, $ point_list [$ I]);

$ Clusters [$ I] = $ new_cluster;

 

# Calculate the new K value and the position of the queue point

$ Diff = euclidean ($ old [0], $ center );

}

 

# Determine whether aggregation is sufficient

If ($ diff <$ min_diff)

{

Break;
>

}

 

}

Echo '->'. $ ii;

 

Return $ clusters;

}

 

# Calculate the 2-point distance

$ Ii = 0;

Function euclidean ($ p1, $ p2)

{

 

$ S = 0;

Foreach ($ p1 as $ key => $ value)

{

 

$ Temp = ($ value-$ p2 [$ key]);

$ S + = $ temp * $ temp;

}

 

Return sqrt ($ s );

 

}

 

# Move the K value to the center of all vertices

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.