Incorrect saturation calculation in RGB to HSL function - php

Does anybody know the correct formula to get the saturation level from an RGB color?
I already have a function that does it. I've tried loads of them posted on the internet but only this one seemed to work (first-time) for me, apart from the saturation level being occasionally slightly out.
rgb(204,153,51) should equal hsl(40,60,50), instead I have hsl(40,75,50). As you can see my hue and lightness are correct, in-fact, the saturation is mostly correct too, but sometimes it's not and I need to correct that if I can.
This is what I've built so far, so I can check all the color values are correct for my images, before storing them in a database for my search engine.
And this is the function in question where I believe the saturation is being calculated incorrectly:
function RGBtoHSL($red, $green, $blue)
{
$r = $red / 255.0;
$g = $green / 255.0;
$b = $blue / 255.0;
$H = 0;
$S = 0;
$V = 0;
$min = min($r,$g,$b);
$max = max($r,$g,$b);
$delta = ($max - $min);
$L = ($max + $min) / 2.0;
if($delta == 0) {
$H = 0;
$S = 0;
} else {
$S = $delta / $max;
$dR = ((($max - $r) / 6) + ($delta / 2)) / $delta;
$dG = ((($max - $g) / 6) + ($delta / 2)) / $delta;
$dB = ((($max - $b) / 6) + ($delta / 2)) / $delta;
if ($r == $max)
$H = $dB - $dG;
else if($g == $max)
$H = (1/3) + $dR - $dB;
else
$H = (2/3) + $dG - $dR;
if ($H < 0)
$H += 1;
if ($H > 1)
$H -= 1;
}
$HSL = ($H*360).', '.($S*100).', '.round(($L*100),0);
return $HSL;
}
One clue I have, as to why this doesn't work 100%, is that I'm first converting a HEX color to an RGB, then the RGB to an HSL. Would this be a problem due to web-safe colors or can you spot anything else that may cause this in the function? Or is this just how it is?
UPDATE 1
Trying other images, it appears to be mostly 'beige' (approx.) colors that are slightly out on saturation. Using a color picker, if I move the saturation bar to where it should be there isn't a huge difference, so maybe my search feature won't pick up on this too much. It would be nice to solve it though, before I run it on 500,000 photos.
THE FIX
Thanks to OmnipotentEntity, below, he noticed I missing piece to my function. I changed:
$S = $delta / $max;
to:
$S = $L > 0.5 ? $delta / (2 - $max - $min) : $delta / ($max + $min);
and now produces 100% correct results.
FRIENDLY NOTE
If anybody would like the code to produce this color table, just ask.

It looks like you’re missing a piece of the calculation for saturation if your luma is > .5 as shown here in this JavaScript HSL code.
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;

Related

Converting string to integer from form

Need a little help
I have
$_POST["zapremina"]=2000;
$_POST["starost"]="15%";
$_POST["namena"]="50%";
I want simple function to do this
$foo=(2000 - 15%) - 50%;
How to do that?
PHP is loosely typed, so you don't have to cast types explicity or do unnecessary operations (e.g. str_replace)
You can do the following:
$z = $_POST["zapremina"]; //$_POST["zapremina"]=2000;
$s = $_POST["starost"]; //$_POST["starost"]=15%;
$n = $_POST["namena"]; //$_POST["namena"]="50%;
$result = (($z - ($z *($s / 100))) - ($z * ($n / 100)));
Remember to use parentheses to have a readable code and meaningful var names.
Like this:
$starostPercentage = (substr($POST["starost"], 0, -1) / 100);
$namenaPercentage = (substr($POST["namena"], 0, -1) / 100);
$foo = ($_POST["zapremina"] * (100 - $starostPercentage)) * $namenaPercentage;
This is what this does and why:
Convert the percentages (like 15%) from their text form to their decimal form (substr(15%) = 15, 15 / 100 = 0.15).
Calculate $foo with these decimals. 2000 - 15% is what you would write (as a human), but in PHP you need to write that as 2000 * (100 * 0.15), meaning: 85% of 2000).
I'd go with this:
$zap = intval($_POST['zapremina']);
$sta = intval($_POST['starost']);
$nam = intval($_POST['namena']);
$foo = ($zap * ((100-$sta)/100)) * ((100 - $nam)/100)
add this function and then call it
function calculation($a, $b, $c)
{
$b = substr($b, 0, -1) / 100;
$c = substr($c, 0, -1) / 100;
return (($a * $b) * $c);
}
and now you can call
$foo = calculation($_POST["zapremina"], $_POST["starost"], $_POST["namena"]);
go with function most of times, because it will be helpful for reusability.

Determine position of one image in another with PHP

I have two images(small and big). One of them contains another one. Something like one image is a photo and another one is a picture of the page of the photoalbum where this photo is situated. I hope you understood what I said.
So how do I get coordinates (x,y) of a small image on the big one using PHP?
It is quite easy to do on your own, without relying on external libs other than gd.
What you need to be aware of, is that you most likely cannot do a simple pixel per pixel check, as filtering and compression might slightly modify the value of each pixel.
The code I am proposing here will most likely be slow, if performance is a concern, you could optimize it or take shortcuts. Hopefully, the code puts you on the right track!
First, lets iterate on our pictures
$small = imagecreatefrompng("small.png");
$large = imagecreatefrompng("large.png");
$smallwidth = imagesx($small);
$smallheight = imagesy($small);
$largewidth = imagesx($large);
$largeheight = imagesy($large);
$foundX = -1;
$foundY = -1;
$keepThreshold = 20;
$potentialPositions = array();
for($x = 0; $x <= $largewidth - $smallwidth; ++$x)
{
for($y = 0; $y <= $largeheight - $smallheight; ++$y)
{
// Scan the whole picture
$error = GetImageErrorAt($large, $small, $x, $y);
if($error["avg"] < $keepThreshold)
{
array_push($potentialPositions, array("x" => $x, "y" => $y, "error" => $error));
}
}
}
imagedestroy($small);
imagedestroy($large);
echo "Found " . count($potentialPositions) . " potential positions\n";
The goal here is to find how similar the pixels are, and if they are somewhat similar, keep the potential position. Here, I iterate each and every pixel of the large picture, this could be a point of optimization.
Now, where does this error come from?
Getting the likeliness
What I did here is iterate over the small picture and a "window" in the large picture checking how much difference there was on the red, green and blue channel:
function GetImageErrorAt($haystack, $needle, $startX, $startY)
{
$error = array("red" => 0, "green" => 0, "blue" => 0, "avg" => 0);
$needleWidth = imagesx($needle);
$needleHeight = imagesy($needle);
for($x = 0; $x < $needleWidth; ++$x)
{
for($y = 0; $y < $needleHeight; ++$y)
{
$nrgb = imagecolorat($needle, $x, $y);
$hrgb = imagecolorat($haystack, $x + $startX, $y + $startY);
$nr = $nrgb & 0xFF;
$hr = $hrgb & 0xFF;
$error["red"] += abs($hr - $nr);
$ng = ($nrgb >> 8) & 0xFF;
$hg = ($hrgb >> 8) & 0xFF;
$error["green"] += abs($hg - $ng);
$nb = ($nrgb >> 16) & 0xFF;
$hb = ($hrgb >> 16) & 0xFF;
$error["blue"] += abs($hb - $nb);
}
}
$error["avg"] = ($error["red"] + $error["green"] + $error["blue"]) / ($needleWidth * $needleHeight);
return $error;
}
So far, we've established a potential error value for every "window" in the large picture that could contain the small picture, and store them in an array if they seem "good enough".
Sorting
Now, we simply need to sort our best matches and keep the best one, it is most likely where our small picture is located:
function SortOnAvgError($a, $b)
{
if($a["error"]["avg"] == $b["error"]["avg"])
{
return 0;
}
return ($a["error"]["avg"] < $b["error"]["avg"]) ? -1 : 1;
}
if(count($potentialPositions) > 0)
{
usort($potentialPositions, "SortOnAvgError");
$mostLikely = $potentialPositions[0];
echo "Most likely at " . $mostLikely["x"] . "," . $mostLikely["y"];
}
Example
Given the two following pictures:
and
You should have the following result:
Found 5 potential positions
Most likely at 288,235
Which corresponds exactly with the position of our duck. The 4 other positions are 1 pixel up, down, left and right.
I am going to edit this entry after I'm done working on some optimizations for you, as this code is way too slow for big images (PHP performed even worse than I expected).
Edit
First, before doing anything to "optimize" the code, we need numbers, so I added
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
and
$time_end = microtime_float();
echo "in " . ($time_end - $time_start) . " seconds\n";
at the end to have a specific idea of how much time is taken during the algorithm. This way, I can know if my changes improve or make the code worse. Given that the current code with these pictures takes ~45 minutes to execute, we should be able to improve this time quite a lot.
A tentative that was not succesful, was to cache the RGB from the $needle to try to accelerate the GetImageErrorAt function, but it worsened the time.
Given that our computation is on a geometric scale, the more pixels we explore, the longer it will take... so a solution is to skip many pixels to try to locate as fast as possible our picture, and then more accurately zone in on our position.
I modified the error function to take as a parameter how to increment the x and y
function GetImageErrorAt($haystack, $needle, $startX, $startY, $increment)
{
$needleWidth = imagesx($needle);
$needleHeight = imagesy($needle);
$error = array("red" => 0, "green" => 0, "blue" => 0, "avg" => 0, "complete" => true);
for($x = 0; $x < $needleWidth; $x = $x + $increment)
{
for($y = 0; $y < $needleHeight; $y = $y + $increment)
{
$hrgb = imagecolorat($haystack, $x + $startX, $y + $startY);
$nrgb = imagecolorat($needle, $x, $y);
$nr = $nrgb & 0xFF;
$hr = $hrgb & 0xFF;
$ng = ($nrgb >> 8) & 0xFF;
$hg = ($hrgb >> 8) & 0xFF;
$nb = ($nrgb >> 16) & 0xFF;
$hb = ($hrgb >> 16) & 0xFF;
$error["red"] += abs($hr - $nr);
$error["green"] += abs($hg - $ng);
$error["blue"] += abs($hb - $nb);
}
}
$error["avg"] = ($error["red"] + $error["green"] + $error["blue"]) / ($needleWidth * $needleHeight);
return $error;
}
For example, passing 2 will make the function return 4 times faster, as we skip both x and y values.
I also added a stepSize for the main loop:
$stepSize = 10;
for($x = 0; $x <= $largewidth - $smallwidth; $x = $x + $stepSize)
{
for($y = 0; $y <= $largeheight - $smallheight; $y = $y + $stepSize)
{
// Scan the whole picture
$error = GetImageErrorAt($large, $small, $x, $y, 2);
if($error["complete"] == true && $error["avg"] < $keepThreshold)
{
array_push($potentialPositions, array("x" => $x, "y" => $y, "error" => $error));
}
}
}
Doing this, I was able to reduce the execution time from 2657 seconds to 7 seconds at a price of precision. I increased the keepThreshold to have more "potential results".
Now that I wasn't checking each pixels, my best answer is:
Found 8 potential positions
Most likely at 290,240
As you can see, we're near our desired position, but it's not quite right.
What I'm going to do next is define a rectangle around this "pretty close" position to explore every pixel inside the stepSize we added.
I'm now changing the lower part of the script for:
if(count($potentialPositions) > 0)
{
usort($potentialPositions, "SortOnAvgError");
$mostLikely = $potentialPositions[0];
echo "Most probably around " . $mostLikely["x"] . "," . $mostLikely["y"] . "\n";
$startX = $mostLikely["x"] - $stepSize + 1; // - $stepSize was already explored
$startY = $mostLikely["y"] - $stepSize + 1; // - $stepSize was already explored
$endX = $mostLikely["x"] + $stepSize - 1;
$endY = $mostLikely["y"] + $stepSize - 1;
$refinedPositions = array();
for($x = $startX; $x <= $endX; ++$x)
{
for($y = $startY; $y <= $endY; ++$y)
{
// Scan the whole picture
$error = GetImageErrorAt($large, $small, $x, $y, 1); // now check every pixel!
if($error["avg"] < $keepThreshold) // make the threshold smaller
{
array_push($refinedPositions, array("x" => $x, "y" => $y, "error" => $error));
}
}
}
echo "Found " . count($refinedPositions) . " refined positions\n";
if(count($refinedPositions))
{
usort($refinedPositions, "SortOnAvgError");
$mostLikely = $refinedPositions[0];
echo "Most likely at " . $mostLikely["x"] . "," . $mostLikely["y"] . "\n";
}
}
Which now gives me an output like:
Found 8 potential positions
Most probably around 290,240
Checking between X 281 and 299
Checking between Y 231 and 249
Found 23 refined positions
Most likely at 288,235
in 13.960182189941 seconds
Which is indeed the right answer, roughly 200 times faster than the initial script.
Edit 2
Now, my test case was a bit too simple... I changed it to a google image search:
Looking for this picture (it's located at 718,432)
Considering the bigger picture sizes, we can expect a longer processing time, but the algorithm did find the picture at the right position:
Found 123 potential positions
Most probably around 720,430
Found 17 refined positions
Most likely at 718,432
in 43.224536895752 seconds
Edit 3
I decided to try the option I told you in the comment, to scale down the pictures before executing the find, and I had great results with it.
I added this code before the first loop:
$smallresizedwidth = $smallwidth / 2;
$smallresizedheight = $smallheight / 2;
$largeresizedwidth = $largewidth / 2;
$largeresizedheight = $largeheight / 2;
$smallresized = imagecreatetruecolor($smallresizedwidth, $smallresizedheight);
$largeresized = imagecreatetruecolor($largeresizedwidth, $largeresizedheight);
imagecopyresized($smallresized, $small, 0, 0, 0, 0, $smallresizedwidth, $smallresizedheight, $smallwidth, $smallheight);
imagecopyresized($largeresized, $large, 0, 0, 0, 0, $largeresizedwidth, $largeresizedheight, $largewidth, $largeheight);
And for them main loop I iterated on the resized assets with the resized width and height. Then, when adding to the array, I double the x and y, giving the following:
array_push($potentialPositions, array("x" => $x * 2, "y" => $y * 2, "error" => $error));
The rest of the code remains the same, as we want to do the precise location on the real size pictures. All you have to do is add at the end:
imagedestroy($smallresized);
imagedestroy($largeresized);
Using this version of the code, with the google image result, I had:
Found 18 potential positions
Most around 720,440
Found 17 refined positions
Most likely at 718,432
in 11.499078989029 seconds
A 4 times performance increase!
Hope this helps
Use ImageMagick.
This page will give you answer: How can I detect / calculate if a small pictures is present inside a bigger picture?

Calculate percentage of up votes

I have searched this site and Google and even though the idea is pretty simple I can't figure it out.
I need to (like seen on YouTube) calculate the % of up-votes based on the amount up-votes and down-votes.
I have two vars, $upvotes and $downvotes now i need to calculate $ratio
For example
$upvotes = 3;
$downvotes = 1;
The ratio here needs to be 75 (%)
If you have
$upvotes = 0;
$downvotes = 100;
It needs to be 0 (%)
How do I calculate the percentage (in PHP)?
Simply
if(($upvotes+$downvotes) != 0)
$percentage = (float)($upvotes/($upvotes+$downvotes))*100;
else
$percentage = 0;
Simple maths!
$ratio = $upvotes / ($upvotes + $downvotes) * 100;
if($downvotes > 0 || $upvotes >0) {
$percentage = ($upvotes / ($upvotes+$downvotes));
}
elseif($upvotes > 0 && downvotes == 0) {
$percentage = 1;
}
$percentage = round(100*$percentage);
$percentage .= "%"; // if you want to add %
I tested it and it works.
$percent = ( $upvotes / ( $upvotes + $downvotes ) ) * 100;
$percentage = (float) round((100 /($upvotes + $downvotes)) * $upvotes, 2);
I would do a round on it aswell, this will round the result to the closest integer.
eg. 75.5% = 76%;
$ratio = round((($upvotes/($upvotes+$downvotes))*100), 0, PHP_ROUND_HALF_UP).'%';

Algorithm to portion

I have a number X, consider X = 1000
And I want piecemeal this number at three times, then Y = 3, then X = (X / 3)
This will give me equal, just not always accurate, so I need: a percentage value is set, also consider K = 8, K is the percentage, but what I want to do? I want the first portion has a value over 8% in K, suppose that 8% are: 500 and the other two plots are 250, 250
The algorithm is basically what I need it, add a percentage value for the first installment and the other equals
EDIT
I just realized, this is far simpler than I made it. To find the value of $div in my original answer you can just:
$div = (int)($num / ($parcels + $percent / 100));
Then the $final_parcels will be the same as below. Basically, the line above replaces the while loop entirely. Don't know what I was thinking.
/EDIT
I think this will do what you want... unless I am missing something.
<?php
$num = 1000;
$percent = 8;
$parcels = 3;
$total = PHP_INT_MAX;
$div = (int)($num / $parcels);
while ($total > $num) {
$div -= 1;
$total = (int)($div * ($parcels + $percent / 100));
}
$final_parcels = array();
$final_parcels[] = ($num - (($parcels - 1) * $div));
for ($i = 1; $i < $parcels; $i++) {
$final_parcels[] = $div;
}
print_r($final_parcels);
This output will be
Array
(
[0] => 352
[1] => 324
[2] => 324
)
324 * 1.08 = 350.
352 + 324 * 2 = 1000.
Let $T is your total X, $n is a number of parts and $K is percentage mentioned above. Than
$x1 = $T / $n + $T * $K / 100;
$x2 = $x3 = .. = $xn = ($T - $x1) / ($n - 1);
Applied to your example:
$x1 = 1000 / 3 + 1000 * 0.03 = 363.3333333333333333333333333333
// you could round it if you want
// lets round it to ten, as you mentioned
$x1 = round($x1, -1) = 360
$x2 = $x3 = (1000 - 360) / 2 = 320
Extra for the first piece W = X*K/100
Remaining Z = X-W
Each non-first piece = Z/Y = (X-W)/Y = (100-K)*X/(100*Y)
The first piece = W + (100-K)*X/(100*Y) = X*K/100 + (100-K)*X/(100*Y)

How can I calculate the points along a line in PHP?

I apologize if this is overly simple, but I'm the furthest thing possible from a math major, and I have trouble reducing abstract formulas into workable code. I know the formula for a line, but turning it into code is making my head spin. And stressing out my code debugger.
Given a 2D grid coordinate system, I need to be able to specify a starting point X1,Y1 and an ending point X2,Y2 and calculate a list of all grid cells directly on a line between those two points.
So if...
X1,Y1 = 3,3
X2,Y2 = 0,5
I would want to calculate an array of points
3,3
2,4
1,4
0,5
Or something like that. It's also kind of important that I be able to list these points in order - so as above, I'm starting with the origin X,Y and moving toward the destination X,Y.
(And no, this isn't homework - I've seen that asked for a lot of other math questions here, so I'll get it out of the way up front. Maybe if I'd done this as homework 25 years ago I wouldn't need to ask now!)
I did find PHP Find Coordinates between two points which seems to talk around the solution, but the comments indicate that the "accepted" answer isn't complete.
Many thanks.
Sounds like your best bet might be Bresenham's algorithm for drawing a line, except instead of plotting the points you'll be capturing the x,y values.
I don't know that this is particularly elegant, but here's how I would do it:
function getLinePoints( $startPoint, $endPoint ){
$totalSteps = max( abs( $startPoint[0] - $endPoint[0] ), abs( $startPoint[1] - $endPoint[1] ) );
if ( $totalSteps == 0 ){
return $startPoint;
}
$xStep = ( $endPoint[0] - $startPoint[0] ) / $totalSteps;
$yStep = ( $endPoint[1] - $startPoint[1] ) / $totalSteps;
$points[] = $currentPoint = $startPoint;
for( $step = 0; $step < $totalSteps; $step++ ){
$currentPoint[0] += $xStep;
$currentPoint[1] += $yStep;
$points[] = array( round( $currentPoint[0], 0 ), round( $currentPoint[1], 0 ) );
}
return $points;
}
$pointA = array( 3, 3 );
$pointB = array( 0, 5 );
$points = getLinePoints( $pointA, $pointB );
This takes the following steps:
Get the total whole number of points you'll have to traverse horizontally or vertically.
Calculates how far you'll have to travel horizontally or vertically at each step.
Constructs an array of points with coordinates rounded to whole numbers.
Return value should be:
Array(
Array( 3, 3 ),
Array( 2, 4 ),
Array( 1, 4 ),
Array( 0, 5 )
)
I'm assuming you want whole-number coordinates, since that's what you listed in the example. But note that this is not necessarily the case for any arbitrary set of (x1,y1) and (x2,y2). My answer here will give you whole-number x-coordinates only.
I would use the two-point form of the linear equation.
yi = (y2-y1)/(x2-x1)*(xi-x1) + y1
where (xi,yi) are the points you are looking for.
for ($xi=$x1; $xi<$x2; $xi++) {
$yi = ($y2-$y1)/($x2-$x1)*($xi-$x1) + $y1
echo $xi + "," + $yi
}
Just make sure you have $x1 < $x2 before you run the above code.
A more complicated situation arises when you draw a line between two arbitrary points (x1,y1) and (x2,y2) and you want to output the list of squares (grid cells) intersected by that line.
So, for more specifics, here's a PHP function that will always return the points with the first array element as the origin and the last as the destination. This is tested and working, and is an adaptation of http://alex.moutonking.com/wordpress/?p=44.
function bresenham($x1, $y1, $x2, $y2, $guaranteeEndPoint=true) {
$xBegin = $x1;
$yBegin = $y1;
$xEnd = $x2;
$yEnd = $y2;
$dots = array();
$steep = abs($y2 - $y1) > abs($x2 - $x1);
if ($steep) {
$tmp = $x1;
$x1 = $y1;
$y1 = $tmp;
$tmp = $x2;
$x2 = $y2;
$y2 = $tmp;
}
if ($x1 > $x2) {
$tmp = $x1;
$x1 = $x2;
$x2 = $tmp;
$tmp = $y1;
$y1 = $y2;
$y2 = $tmp;
}
$deltax = floor($x2 - $x1);
$deltay = floor(abs($y2 - $y1));
$error = 0;
$deltaerr = $deltay / $deltax;
$y = $y1;
$ystep = ($y1 < $y2) ? 1 : -1;
for ($x = $x1; $x < $x2; $x++) {
$dots[] = $steep ? array($y, $x) : array($x, $y);
$error += $deltaerr;
if ($error >= 0.5) {
$y += $ystep;
$error -= 1;
}
}
if ($guaranteeEndPoint) {
if ((($xEnd - $x) * ($xEnd - $x) + ($yEnd - $y) * ($yEnd - $y)) < (($xBegin - $x) * ($xBegin - $x) + ($yBegin - $y) * ($yBegin - $y))) {
$dots[] = array($xEnd, $yEnd);
} else
$dots[] = array($xBegin, $yBegin);
}
if ($dots[0][0] != $xBegin and $dots[0][1] != $yBegin) {
return array_reverse($dots);
} else {
return $dots;
}
}
looks like you re looking for interpolation methods, check this : http://paulbourke.net/miscellaneous/interpolation/ (what u need is linear interpolation)

Categories