S
S
samarkand12018-01-13 17:20:43
code review
samarkand1, 2018-01-13 17:20:43

How to speed up the site (algorithm for calculating the nearest color from a known color palette)?

Hello,
I have a php script. Main tasks:
1. Analysis of the dominant colors of the image
2. Matching the dominant color to one of the colors in a known palette
The whole thing works on php gd.
Namely:
1. Color selection by palette - imagecolorclosest
2. Formula - nearest color -

$diff = ( sqrt(pow($r1,2) + pow($g1,2)) + sqrt(pow($g1,2) + pow($b1,2)) + sqrt(pow($b1,2) + pow($r1,2))) / 3;

The use of an additional calculation formula is due to the fact that there are more than 255 colors in the color palette for comparison. In practice, the comparison takes place among three or four values ​​(a palette of up to 1000 colors).
With an increase in the initial image size, the script execution time also increases, mainly due to the calculation of the nearest color formula.
Replacing the formula with the most simplified version
$diff = $r1 + $g1 + $b1;
gives too much error.
Since the script execution time directly depends on the size of the source image, one of the options for solving the problem (in addition to switching to your own server) is to artificially limit the size of the final image. This option works, but, as expected, at high resolutions, there is a loss in image quality.
Question : how to speed up the script within the current technical limitations ?
Restrictions:
1. Regular shared hosting for $10 per month
2. php gd
Writing options in another language are considered. I would just like to really understand that this will speed up the process.
Demo here goo.gl/9gQbQC

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Oleg Frolov, 2019-10-31
@g905

Looks good at a glance :)

M
Maxim K, 2019-10-31
@mkvmaks

They threw off a link not to the main one, as it should be? Error at the bottom of the main "Article".

A
Adamos, 2018-01-13
@Adamos

The function you provided in the comments clearly lacks two things:
1. Caching, so as not to repeat the calculation for the color that has already been calculated. I foresee an increase in speed by a couple of orders of magnitude.
2. Understanding that in order to find ONE optimal value for hell, you don’t need to collect an entire array and sort it. Have you ever seen an algorithm for finding the smallest value in an array?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question