I'm new to CI but would like to include the code below (which sits in a file called color.php) within a view and reference the functions. But doesn't seem to work when I do this per normal php include include('/assets/color.php'); I've also tried adding color.php as a helper and loading it in the view but again not working … Any help on how best to include this would be great.
class GetMostCommonColors
{
var $PREVIEW_WIDTH = 150;
var $PREVIEW_HEIGHT = 150;
var $error;
/**
* Returns the colors of the image in an array, ordered in descending order, where the keys are the colors, and the values are the count of the color.
*
* #return array
*/
function Get_Color( $img, $count=20, $reduce_brightness=true, $reduce_gradients=true, $delta=16 )
{
if (is_readable( $img ))
{
if ( $delta > 2 )
{
$half_delta = $delta / 2 - 1;
}
else
{
$half_delta = 0;
}
// WE HAVE TO RESIZE THE IMAGE, BECAUSE WE ONLY NEED THE MOST SIGNIFICANT COLORS.
$size = GetImageSize($img);
$scale = 1;
if ($size[0]>0)
$scale = min($this->PREVIEW_WIDTH/$size[0], $this->PREVIEW_HEIGHT/$size[1]);
if ($scale < 1)
{
$width = floor($scale*$size[0]);
$height = floor($scale*$size[1]);
}
else
{
$width = $size[0];
$height = $size[1];
}
$image_resized = imagecreatetruecolor($width, $height);
if ($size[2] == 1)
$image_orig = imagecreatefromgif($img);
if ($size[2] == 2)
$image_orig = imagecreatefromjpeg($img);
if ($size[2] == 3)
$image_orig = imagecreatefrompng($img);
// WE NEED NEAREST NEIGHBOR RESIZING, BECAUSE IT DOESN'T ALTER THE COLORS
imagecopyresampled($image_resized, $image_orig, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
$im = $image_resized;
$imgWidth = imagesx($im);
$imgHeight = imagesy($im);
$total_pixel_count = 0;
for ($y=0; $y < $imgHeight; $y++)
{
for ($x=0; $x < $imgWidth; $x++)
{
$total_pixel_count++;
$index = imagecolorat($im,$x,$y);
$colors = imagecolorsforindex($im,$index);
// ROUND THE COLORS, TO REDUCE THE NUMBER OF DUPLICATE COLORS
if ( $delta > 1 )
{
$colors['red'] = intval((($colors['red'])+$half_delta)/$delta)*$delta;
$colors['green'] = intval((($colors['green'])+$half_delta)/$delta)*$delta;
$colors['blue'] = intval((($colors['blue'])+$half_delta)/$delta)*$delta;
if ($colors['red'] >= 256)
{
$colors['red'] = 255;
}
if ($colors['green'] >= 256)
{
$colors['green'] = 255;
}
if ($colors['blue'] >= 256)
{
$colors['blue'] = 255;
}
}
$hex = substr("0".dechex($colors['red']),-2).substr("0".dechex($colors['green']),-2).substr("0".dechex($colors['blue']),-2);
if ( ! isset( $hexarray[$hex] ) )
{
$hexarray[$hex] = 1;
}
else
{
$hexarray[$hex]++;
}
}
}
// Reduce gradient colors
if ( $reduce_gradients )
{
// if you want to *eliminate* gradient variations use:
// ksort( $hexarray );
arsort( $hexarray, SORT_NUMERIC );
$gradients = array();
foreach ($hexarray as $hex => $num)
{
if ( ! isset($gradients[$hex]) )
{
$new_hex = $this->_find_adjacent( $hex, $gradients, $delta );
$gradients[$hex] = $new_hex;
}
else
{
$new_hex = $gradients[$hex];
}
if ($hex != $new_hex)
{
$hexarray[$hex] = 0;
$hexarray[$new_hex] += $num;
}
}
}
// Reduce brightness variations
if ( $reduce_brightness )
{
// if you want to *eliminate* brightness variations use:
// ksort( $hexarray );
arsort( $hexarray, SORT_NUMERIC );
$brightness = array();
foreach ($hexarray as $hex => $num)
{
if ( ! isset($brightness[$hex]) )
{
$new_hex = $this->_normalize( $hex, $brightness, $delta );
$brightness[$hex] = $new_hex;
}
else
{
$new_hex = $brightness[$hex];
}
if ($hex != $new_hex)
{
$hexarray[$hex] = 0;
$hexarray[$new_hex] += $num;
}
}
}
arsort( $hexarray, SORT_NUMERIC );
// convert counts to percentages
foreach ($hexarray as $key => $value)
{
$hexarray[$key] = (float)$value / $total_pixel_count;
}
if ( $count > 0 )
{
// only works in PHP5
// return array_slice( $hexarray, 0, $count, true );
$arr = array();
foreach ($hexarray as $key => $value)
{
if ($count == 0)
{
break;
}
$count--;
$arr[$key] = $value;
}
return $arr;
}
else
{
return $hexarray;
}
}
else
{
$this->error = "Image ".$img." does not exist or is unreadable";
return false;
}
}
function _normalize( $hex, $hexarray, $delta )
{
$lowest = 255;
$highest = 0;
$colors['red'] = hexdec( substr( $hex, 0, 2 ) );
$colors['green'] = hexdec( substr( $hex, 2, 2 ) );
$colors['blue'] = hexdec( substr( $hex, 4, 2 ) );
if ($colors['red'] < $lowest)
{
$lowest = $colors['red'];
}
if ($colors['green'] < $lowest )
{
$lowest = $colors['green'];
}
if ($colors['blue'] < $lowest )
{
$lowest = $colors['blue'];
}
if ($colors['red'] > $highest)
{
$highest = $colors['red'];
}
if ($colors['green'] > $highest )
{
$highest = $colors['green'];
}
if ($colors['blue'] > $highest )
{
$highest = $colors['blue'];
}
// Do not normalize white, black, or shades of grey unless low delta
if ( $lowest == $highest )
{
if ($delta <= 32)
{
if ( $lowest == 0 || $highest >= (255 - $delta) )
{
return $hex;
}
}
else
{
return $hex;
}
}
for (; $highest < 256; $lowest += $delta, $highest += $delta)
{
$new_hex = substr("0".dechex($colors['red'] - $lowest),-2).substr("0".dechex($colors['green'] - $lowest),-2).substr("0".dechex($colors['blue'] - $lowest),-2);
if ( isset( $hexarray[$new_hex] ) )
{
// same color, different brightness - use it instead
return $new_hex;
}
}
return $hex;
}
function _find_adjacent( $hex, $gradients, $delta )
{
$red = hexdec( substr( $hex, 0, 2 ) );
$green = hexdec( substr( $hex, 2, 2 ) );
$blue = hexdec( substr( $hex, 4, 2 ) );
if ($red > $delta)
{
$new_hex = substr("0".dechex($red - $delta),-2).substr("0".dechex($green),-2).substr("0".dechex($blue),-2);
if ( isset($gradients[$new_hex]) )
{
return $gradients[$new_hex];
}
}
if ($green > $delta)
{
$new_hex = substr("0".dechex($red),-2).substr("0".dechex($green - $delta),-2).substr("0".dechex($blue),-2);
if ( isset($gradients[$new_hex]) )
{
return $gradients[$new_hex];
}
}
if ($blue > $delta)
{
$new_hex = substr("0".dechex($red),-2).substr("0".dechex($green),-2).substr("0".dechex($blue - $delta),-2);
if ( isset($gradients[$new_hex]) )
{
return $gradients[$new_hex];
}
}
if ($red < (255 - $delta))
{
$new_hex = substr("0".dechex($red + $delta),-2).substr("0".dechex($green),-2).substr("0".dechex($blue),-2);
if ( isset($gradients[$new_hex]) )
{
return $gradients[$new_hex];
}
}
if ($green < (255 - $delta))
{
$new_hex = substr("0".dechex($red),-2).substr("0".dechex($green + $delta),-2).substr("0".dechex($blue),-2);
if ( isset($gradients[$new_hex]) )
{
return $gradients[$new_hex];
}
}
if ($blue < (255 - $delta))
{
$new_hex = substr("0".dechex($red),-2).substr("0".dechex($green),-2).substr("0".dechex($blue + $delta),-2);
if ( isset($gradients[$new_hex]) )
{
return $gradients[$new_hex];
}
}
return $hex;
}
}
// loading library from within view
$this->load->library('GetMostCommonColors');
$ex = new GetMostCommonColors();
$colors=$ex->Get_Color($artwork->large_image, 5);
Put The file into library folder and load the the library using this code
$this->load->library('GetMostCommonColors');
This link will help you..
Library detail documentation
Seems the path is not correct, try the following code:
require_once(dirname(__FILE__).'/assets/color.php');
or
require_once __DIR__ . '/assets/color.php';
but
include('/assets/color.php');
will work as well provided the assets folder is a sub-folder of the folder where the main file is from where you are making this inclusion.
Related
H ieveryone,
I would like to sort colors so that they are beautifully organized (in a way that similar colors are grouped together)
I have found this function 'rgb2hsl' somewhere in a forum (sorryif I don't recall the link) to convert an RGB value to HSL then sort by H, S, L.
the result is OK but far from satisfying because some light colors are mixed with dark ones:
Below is the entire script in php:
could you please help tune-in the function to group the colors in a nicer way?
thanks in advance.
<?php
function rgb2hsl ($R, $G, $B)
{
$var_R = ($R / 255);
$var_G = ($G / 255);
$var_B = ($B / 255);
$var_Min = min($var_R, $var_G, $var_B);
$var_Max = max($var_R, $var_G, $var_B);
$del_Max = $var_Max - $var_Min;
$V = $var_Max;
if ($del_Max == 0)
{
$H = 0;
$S = 0;
}
else
{
$S = $del_Max / $var_Max;
$del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
$del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
$del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
if ($var_R == $var_Max) $H = $del_B - $del_G;
else if ($var_G == $var_Max) $H = ( 1 / 3 ) + $del_R - $del_B;
else if ($var_B == $var_Max) $H = ( 2 / 3 ) + $del_G - $del_R;
if ($H<0) $H++;
if ($H>1) $H--;
}
$HSL = array();
$HSL['H'] = $H;
$HSL['S'] = $S;
$HSL['L'] = $V;
return $HSL;
}
function hex2rgb( $colour )
{
if ( $colour[0] == '#' )
{
$colour = substr( $colour, 1 );
}
if ( strlen( $colour ) == 6 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
} elseif ( strlen( $colour ) == 3 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
} else {
return false;
}
$r = hexdec( $r );
$g = hexdec( $g );
$b = hexdec( $b );
return array( 'R' => $r, 'G' => $g, 'B' => $b );
}
function cmp($a, $b)
{
$rgb1 = hex2rgb($a);
$rgb2 = hex2rgb($b);
$hsl1 = rgb2hsl($rgb1['R'], $rgb1['G'], $rgb1['B']);
$hsl2 = rgb2hsl($rgb2['R'], $rgb2['G'], $rgb2['B']);
$h1 = $hsl1['H'];
$s1 = $hsl1['S'];
$l1 = $hsl1['L'];
$h2 = $hsl2['H'];
$s2 = $hsl2['S'];
$l2 = $hsl2['L'];
if($h1 == $h2 && $s1 == $s2 && $l1 == $l2)
{
return 0;
}
else
{
if (($h1 > $h2) ||
(($h1 == $h2) && ($s1 > $s1) ) ||
(($h1 == $h2) && ($s1 == $s1) && ($l1 > $l2)))
{
return 1;
}
else
{
return -1;
}
}
}
$a = array(
"#000000","#FFFFFF","#642424","#CC0605","#CB2821","#A2231D",
"#AF2B1E","#BF4435","#F54021","#C93C20","#FFDDD6","#F44611","#F75E25","#C1876B",
"#FABFA1","#734222","#FF7514","#FFCC99","#8A6642","#FDF4E3","#F3A505","#C6A664",
"#F4A900","#C2B078","#F5CB21","#E6D690","#FAD201","#E1CC4F","#F3DA0B","#7E7B52",
"#FFFCC1","#B8B799","#F8F32B","#FFFF99","#EDFF21","#B8CE3B","#424632","#343B29",
"#85BD3E","#31372B","#79BB51","#89AC76","#4FAE2E","#C0DEBC","#2D572C","#8D948D",
"#1CA744","#1E5945","#39B49F","#3F888F","#439AA4","#256D7B","#434B4D","#293133",
"#008FB7","#0D3A4D","#D0E6F1","#474B4E","#2271B3","#0E294B","#0B2C59","#0E3987",
"#4170CC","#1D1E33","#A49FC7","#6C3EC3","#261448","#986DE9","#37225D","#260B3E",
"#D8C6DE","#6C4675","#FFA3FF","#E54EE5","#6D3F5B","#D569A7","#A03472","#9E1A65",
"#421C31","#CF3476","#DE4C8A","#4A192C","#641C34","#F8C5CE","#EA899A","#412227",
"#5E2129","#9B111E","#75151E","#D60B11","#D36E70","#D53032" );
usort($a, "cmp");
foreach ($a as $key => $value)
{
echo "<div style=\"width:390px; height:40px; background:$value;\"> $value</div>";
}
?>
You cannot have random colors aesthetically listed together unless you first define the color scheme you want to use, that is if you want to automate it.
This web site shows you how to use different color schemes : http://colorschemedesigner.com/
what you may do is calculate the Hues of all the colors using HSV r HSL and make groups of colors (maximum colors in a group should not be more that 5).
TBH even though standard color schemes are only to facilitate you to a certain extent, there are many color schemes which look really great but they completely violate the standard schemes due to the fact that standard color schemes do not take account of saturation and perceptive brightness. e.g. http://www.colourlovers.com/palettes
Now I do not want to pull you off the road so my suggestion would be to instead of selecting the pallets yourself select some random Hues and calculate the rest of the hues/tints/saturation by selecting a particular color scheme.
So far I have found examples on how to grab all the RGB values of each pixel in an image but I want something that will break down an image and give me a simplified color palette.
Is there a way to use imagetruecolortopalette to somehow spit out the reduced palette colours, or to break an image into 25 x 25 blocks and then grab the average value of that block?
Maybe there is an alternative I'm missing? I basically just want to be able to find the most common colors within an image.
Thanks in advance.
Hmm, well I have had created something like this for a client. The screenshot is below
The complete code is as follows
$microTime = microtime(true);
function textColor($R1, $G1, $B1) {
$a = (($R1 * 299) + ($G1 * 587 ) + ($B1 * 114 )) / 1000;
if ($a < 128)
return 'white';
else
return 'black';
}
function rgb2html($r, $g = -1, $b = -1) {
$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;
if (is_array($r) && sizeof($r) == 3)
list($r, $g, $b) = $r;
$r = intval($r);
$g = intval($g);
$b = intval($b);
$r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r));
$g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g));
$b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b));
$color = (strlen($r) < 2 ? '0' : '') . $r;
$color .= (strlen($g) < 2 ? '0' : '') . $g;
$color .= (strlen($b) < 2 ? '0' : '') . $b;
return '#' . $color;
}
function colorPalette($imageFile, $colorJump, $granularity = 5) {
$granularity = max(1, abs((int) $granularity));
$colors = array();
$ratio = array();
$wastageCount = array();
$occurrenceSCount = array();
$occurrenceMCount = array();
$size = #getimagesize($imageFile);
if ($size === false) {
return false;
}
$img = #imagecreatefromstring(file_get_contents($imageFile));
if (!$img) {
user_error("Unable to open image file");
return false;
}
for ($y = 0; $y < $size[1]; $y += $granularity) {
$lastColor = NULL;
$lastX = -1;
for ($x = 0; $x < $size[0]; $x += $granularity) {
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$red = round(round(($rgb['red'] / $colorJump)) * $colorJump);
$green = round(round(($rgb['green'] / $colorJump)) * $colorJump);
$blue = round(round(($rgb['blue'] / $colorJump)) * $colorJump);
$thisRGB = $red . ',' . $green . ',' . $blue;
if ($lastColor != $thisRGB) {
if (array_key_exists($thisRGB, $wastageCount)) {
$wastageCount[$thisRGB]++;
} else {
$wastageCount[$thisRGB] = 1;
}
if ($lastX + 1 == $x) {
if (array_key_exists($lastColor, $occurrenceSCount)) {
$occurrenceSCount[$lastColor]++;
} else {
$occurrenceSCount[$lastColor] = 1;
}
}
if ($lastX + 1 != $x) {
if (array_key_exists($lastColor, $occurrenceMCount)) {
$occurrenceMCount[$lastColor]++;
} else {
$occurrenceMCount[$lastColor] = 1;
}
}
$lastColor = $thisRGB;
$lastX = $x;
}
if (array_key_exists($thisRGB, $colors)) {
$colors[$thisRGB]++;
} else {
$colors[$thisRGB] = 1;
}
}
}
$totalPixels = array_sum($colors);
foreach ($colors as $k => $v) {
$ratio[$k] = round(($v / $totalPixels ) * 100, 2);
}
return array($ratio, $wastageCount, $colors, $occurrenceSCount, $occurrenceMCount);
}
usage
$colorJump = 1;
$pixelJump = 1;
$paletteR = colorPalette($dbImgFile_dir, $colorJump, $pixelJump);
$palette = $paletteR[0];
$wastage = $paletteR[1];
$colorsFound = $paletteR[2];
$occSArray = $paletteR[3];
$occMArray = $paletteR[4];
$totalPixels = array_sum($colorsFound);
$totalTime = abs(microtime(true) - $microTime);
the looping around is more complex, as I have to get the pallet from the DB and to match the colors with them, and also the template parser is used which is full custom code, and will not help you.
Just ignore the Required Weight column from this, the single occurrences and multiple occurrences are calculated, if there is a single pixel, for example RED, RED, BLUE, RED, RED it will be 1 single occurrence and 2 multiple occurrence
I want to create piechart in my pdf file created using fpdf. already i had created pdf with fpdf . then i want to create pie chart in that using same table data, is there any option to create pie chart using fpdf ?
Please Help.
Thanks in advance
Try this make changes in code as per your requirements:
You can display following view file on your pdf using pdf helper.
you can use dom pdf helper download it from following link.
http://code.google.com/p/dompdf/downloads/detail?name=dompdf_0-6-0_beta3.zip
<?php
$show_label = true; // true = show label, false = don't show label.
$show_percent = true; // true = show percentage, false = don't show percentage.
$show_text = true; // true = show text, false = don't show text.
$show_parts = false; // true = show parts, false = don't show parts.
$label_form = 'square'; // 'square' or 'round' label.
$width = 199;
$background_color = 'FFFFFF'; // background-color of the chart...
$text_color = '000000'; // text-color.
$colors = array('003366', 'CCD6E0', '7F99B2','F7EFC6', 'C6BE8C', 'CC6600','990000','520000','BFBFC1','808080'); // colors of the slices.
$shadow_height = 16; // Height on shadown.
$shadow_dark = true; // true = darker shadow, false = lighter shadow...
// DON'T CHANGE ANYTHING BELOW THIS LINE...
$data = $_GET["data"];
$label = $_GET["label"];
$height = $width/2;
$data = explode('*',$data);
if ($label != '') $label = explode('*',$label);
for ($i = 0; $i < count($label); $i++)
{
if ($data[$i]/array_sum($data) < 0.1) $number[$i] = ' '.number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
else $number[$i] = number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
if (strlen($label[$i]) > $text_length) $text_length = strlen($label[$i]);
}
if (is_array($label))
{
$antal_label = count($label);
$xtra = (5+15*$antal_label)-($height+ceil($shadow_height));
if ($xtra > 0) $xtra_height = (5+15*$antal_label)-($height+ceil($shadow_height));
$xtra_width = 5;
if ($show_label) $xtra_width += 20;
if ($show_percent) $xtra_width += 45;
if ($show_text) $xtra_width += $text_length*8;
if ($show_parts) $xtra_width += 35;
}
$img = ImageCreateTrueColor($width+$xtra_width, $height+ceil($shadow_height)+$xtra_height);
ImageFill($img, 0, 0, colorHex($img, $background_color));
foreach ($colors as $colorkode)
{
$fill_color[] = colorHex($img, $colorkode);
$shadow_color[] = colorHexshadow($img, $colorkode, $shadow_dark);
}
$label_place = 5;
if (is_array($label))
{
for ($i = 0; $i < count($label); $i++)
{
if ($label_form == 'round' && $show_label && $data[$i] > 0)
{
imagefilledellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $colors[$i % count($colors)]));
imageellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $text_color));
}
else if ($label_form == 'square' && $show_label && $data[$i] > 0)
{
imagefilledrectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $colors[$i % count($colors)]));
imagerectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $text_color));
}
if ($data[$i] > 0)
{
if ($show_percent) $label_output = $number[$i].' ';
if ($show_text) $label_output = $label_output.$label[$i].' ';
if ($show_parts) $label_output = $label_output.$data[$i];
imagestring($img,'2',$width+20,$label_place,$label_output,colorHex($img, $text_color));
$label_output = '';
$label_place = $label_place + 15;
}
}
}
$centerX = round($width/2);
$centerY = round($height/2);
$diameterX = $width-4;
$diameterY = $height-4;
$data_sum = array_sum($data);
$start = 270;
for ($i = 0; $i < count($data); $i++)
{
$value += $data[$i];
$end = ceil(($value/$data_sum)*360) + 270;
$slice[] = array($start, $end, $shadow_color[$value_counter % count($shadow_color)], $fill_color[$value_counter % count($fill_color)]);
$start = $end;
$value_counter++;
}
for ($i=$centerY+$shadow_height; $i>$centerY; $i--)
{
for ($j = 0; $j < count($slice); $j++)
{
if ($slice[$j][0] != $slice[$j][1]) ImageFilledArc($img, $centerX, $i, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][2], IMG_ARC_PIE);
}
}
for ($j = 0; $j < count($slice); $j++)
{
if ($slice[$j][0] != $slice[$j][1]) ImageFilledArc($img, $centerX, $centerY, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][3], IMG_ARC_PIE);
}
OutputImage($img);
ImageDestroy($img);
function colorHex($img, $HexColorString)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
return ImageColorAllocate($img, $R, $G, $B);
}
function colorHexshadow($img, $HexColorString, $mork)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
if ($mork)
{
($R > 99) ? $R -= 100 : $R = 0;
($G > 99) ? $G -= 100 : $G = 0;
($B > 99) ? $B -= 100 : $B = 0;
}
else
{
($R < 220) ? $R += 35 : $R = 255;
($G < 220) ? $G += 35 : $G = 255;
($B < 220) ? $B += 35 : $B = 255;
}
return ImageColorAllocate($img, $R, $G, $B);
}
function OutputImage($img)
{
header('Content-type: image/jpg');
ImageJPEG($img,NULL,100);
}
?>
Hope this will help you... :)
I'd like to make a percentage into a hexidecimal color. Kind of how HSV color degrees work...
I am using PHP.
IE:
0% : RED (#FF0000)
8% : ORANGE (#FF7F00)
17% : YELLOW (#FFFF00)
25% : LIMEGREEN (#7FFF00)
... : ...
83% : MAGENTA (#FF00FF)
92% : ROSE (#FF007F)
100% : RED (#FF0000)
This little snippet would appear to do what you're trying to achieve
http://bytes.com/topic/php/insights/890539-how-produce-first-pair-rgb-hex-color-value-percent-value
function percent2Color($value,$brightness = 255, $max = 100,$min = 0, $thirdColorHex = '00')
{
// Calculate first and second color (Inverse relationship)
$first = (1-($value/$max))*$brightness;
$second = ($value/$max)*$brightness;
// Find the influence of the middle color (yellow if 1st and 2nd are red and green)
$diff = abs($first-$second);
$influence = ($brightness-$diff)/2;
$first = intval($first + $influence);
$second = intval($second + $influence);
// Convert to HEX, format and return
$firstHex = str_pad(dechex($first),2,0,STR_PAD_LEFT);
$secondHex = str_pad(dechex($second),2,0,STR_PAD_LEFT);
return $firstHex . $secondHex . $thirdColorHex ;
// alternatives:
// return $thirdColorHex . $firstHex . $secondHex;
// return $firstHex . $thirdColorHex . $secondHex;
}
Try converting the percentage to HSV (divide the percentage by 100 to get the hue and just set the saturation and value to an arbitrary constant like 1) and then using this question to convert that to RGB form: PHP HSV to RGB formula comprehension
This is not my code and I don't remember where I found it. I've been using it for a couple of years and it works perfectly for me. It could be what your looking for (or part of it may be).
<?php
class colour
{
protected $R = 0; //Red
protected $G = 0; //Green
protected $B = 0; //Blue
protected $H = 0; //Hue
protected $S = 0; //Saturation
protected $L = 0; //Luminance
protected $hex = 0;
protected $web;
protected $complement;
public function __construct($r, $g = false, $b = false)
{
//set up array of web colour names
$this->web = array(
'black' => '#000000',
'green' => '#008000',
'silver' => '#C0C0C0',
'lime' => '#00FF00',
'gray' => '#808080',
'olive' => '#808000',
'white' => '#FFFFFF',
'yellow' => '#FFFF00',
'maroon' => '#800000',
'navy' => '#000080',
'red' => '#FF0000',
'blue' => '#0000FF',
'purple' => '#800080',
'teal' => '#008080',
'fuchsia' => '#FF00FF'
);
//accept either R,G,B or hex colour
//If hex, convert to RGB
//RGB?
if($r && $g && $b){
//yes then save
$this->R = $r;
$this->G = $g;
$this->B = $b;
} elseif(isset($this->web[strtolower($r)])){
//named colour?
$this->hex = $this->web[strtolower($r)];
$this->convertToRGB($this->hex);
} else {
//no - so convert
if($r[0] != '#') $r = '#' . $r;
$this->hex = $r;
$this->convertToRGB($r);
}
$this->rgbTohsl();
//$this->complement = $this->getComplement();
}
public function getLighter($factor)
{
//return colour lightened by %$factor in hex
//$factor can be negative to give a darker colour
if($factor > 1 || $factor < -1) $factor = $factor/100;
$r = (string)round($this->R+((255 - $this->R) * $factor));
$g = (string)round($this->G+((255 - $this->G) * $factor));
$b = (string)round($this->B+((255 - $this->B) * $factor));
if($r > 255)$r = 255;
if($r < 0)$r = 0;
if($g > 255)$g = 255;
if($g < 0)$g = 0;
if($b > 255)$b = 255;
if($b < 0)$b = 0;
var_dump($r, $g, $b);
return $this->convertToHex($r, $g, $b);
}
public function opposite()
{
$r = $this->R;
$g = $this->G;
$b = $this->B;
$r = 255 - $r;
$g = 255 - $g;
$b = 255 - $b;
return $this->convertToHex($r, $g, $b);
}
public function getRGB()
{
//returns an array (r, g, b)
$rgb = array( 'r' => $this->R,
'g' => $this->G,
'b' => $this->B);
return $rgb;
}
public function getHex()
{
if($this->hex) return $this->hex;
$hex = '#' . dechex($this->R) . dechex($this->G) . dechex($this->B);
return $hex;
}
public static function namedToHex($name)
{
//return hex value of named colour
$web = array(
'black' => '#000000',
'green' => '#008000',
'silver' => '#C0C0C0',
'lime' => '#00FF00',
'gray' => '#808080',
'olive' => '#808000',
'white' => '#FFFFFF',
'yellow' => '#FFFF00',
'maroon' => '#800000',
'navy' => '#000080',
'red' => '#FF0000',
'blue' => '#0000FF',
'purple' => '#800080',
'teal' => '#008080',
'fuchsia' => '#FF00FF'
);
if(isset($web[strtolower($name)])){
return $web[strtolower($name)];
}
return false;
}
public static function contrast(colour $fg, colour $bg){
//calculate and return contrast between $fg and $bg
$cont = 1;
$fglum = $fg->luminance();
$bglum = $bg->luminance();
if($fglum > $bglum) $cont = ($fglum + 0.05) / ($bglum + 0.05);
if($bglum > $fglum) $cont = ($bglum + 0.05) / ($fglum + 0.05);
return $cont;
}
public static function colourDiff(colour $colour1, colour $colour2)
{
//returns the colour difference between two colours
$rgb1 = $colour1->getRGB();
$rgb2 = $colour2->getRGB();
$r1 = $rgb1['r'];
$r2 = $rgb2['r'];
$g1 = $rgb1['g'];
$g2 = $rgb2['g'];
$b1 = $rgb1['b'];
$b2 = $rgb2['b'];
$diff = max($r1, $r2) - min($r1, $r2);
$diff += max($g1, $g2) - min($g1, $g2);
$diff += max($b1, $b2) - min($b1, $b2);
return $diff;
}
public function brightness()
{
return (($this->R * 299) + ($this->G * 587) + ($this->B * 114))/1000;
}
public function luminance()
{
//returns luminence of coulour
$r = $this->lumCheck($this->R/255);
$g = $this->lumCheck($this->G/255);
$b = $this->lumCheck($this->B/255);
$lum = (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
return $lum;
}
protected function lumCheck($col)
{
if($col <= 0.03298){
return $col/12.92;
} else {
return pow((($col + 0.055)/1.055), 2.4);
}
}
protected function convertToRGB($color)
{
$color = (string)$color;
if($color[0] == '#'){
$color = substr($color, 1);
}
if(strlen($color) == 6){
list($r, $g, $b) = array($color[0].$color[1],
$color[2].$color[3],
$color[4].$color[5]);
}
elseif(strlen($color) == 3){
list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
}
else{
return false;
}
$r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
$this->R = (int)$r;
$this->G = (int)$g;
$this->B = (int)$b;
}
protected function convertToHex($r, $g, $b)
{
$r = dechex($r);
if(strlen($r) == 1)$r = '0' . $r;
$g = dechex($g);
if(strlen($g) == 1)$g = '0' . $g;
$b = dechex($b);
if(strlen($b) == 1)$b = '0' . $b;
$hex = '#' . $r . $g . $b;
return $hex;
}
protected function rgbTohsl()
{
$r = ( $this->R / 255 ); //RGB from 0 to 255
$g = ( $this->G / 255 );
$b = ( $this->B / 255 );
$var_Min = min( $r, $g, $b ); //Min. value of RGB
$var_Max = max( $r, $g, $b ); //Max. value of RGB
$del_Max = $var_Max - $var_Min; //Delta RGB value
$l = ( $var_Max + $var_Min ) / 2;
$this->L = $l;
if ( $del_Max == 0 ){ //This is a gray, no chroma...
$this->H = 0; //HSL results from 0 to 1
$this->S = 0;
} else { //Chromatic data...
if ( $l < 0.5 ) {
$this->S = $del_Max / ( $var_Max + $var_Min );
} else {
$this->S = $del_Max / ( 2 - $var_Max - $var_Min );
$del_R = ( ( ( $var_Max - $r ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
$del_G = ( ( ( $var_Max - $g ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
$del_B = ( ( ( $var_Max - $b ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
if( $r == $var_Max ){
$h = $del_B - $del_G;
} elseif( $g == $var_Max ){
$h = ( 1 / 3 ) + $del_R - $del_B;
} elseif( $b == $var_Max ) {
$h = ( 2 / 3 ) + $del_G - $del_R;
}
if ( $h < 0 ) $h += 1;
if ( $h > 1 ) $h -= 1;
$this->H = $h;
}
}
}
protected function hslTorgb($h, $s, $l)
{
if ( $s == 0 ){ //HSL from 0 to 1
$r = $l * 255; //RGB results from 0 to 255
$g = $l * 255;
$b = $l * 255;
} else {
if ( $l < 0.5 ) {
$var_2 = $l * ( 1 + $s );
} else {
$var_2 = ( $l + $s ) - ( $s * $l );
}
$var_1 = 2 * $l - $var_2;
$r = 255 * $this->hueToRGB( $var_1, $var_2, $h + ( 1 / 3 ) );
$g = 255 * $this->hueToRGB( $var_1, $var_2, $h );
$b = 255 * $this->hueToRGB( $var_1, $var_2, $h - ( 1 / 3 ) );
}
return array('r'=>$r,'g'=>$g,'b'=>$b);
}
protected function hueToRGB($v1, $v2, $vH)
{
if($vH < 0)$vH += 1;
if($vH > 1)$vH -= 1;
if ( ( 6 * $vH ) < 1 ) return ( $v1 + ( $v2 - $v1 ) * 6 * $vH );
if ( ( 2 * $vH ) < 1 ) return ( $v2 );
if ( ( 3 * $vH ) < 2 ) return ( $v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
return ( $v1 );
}
public function getComplement()
{
$h = $this->H + 180;
if($h > 360)$h -= 360;
$rgb = $this->hslTorgb($h, $this->S, $this->L);
return $this->convertToHex($rgb['r'], $rgb['g'], $rgb['b']);
}
}
Does anybody know of a good way to do face detection in PHP? I came across some code here that claims to do this, but I can't seem to get it to work properly. I'd like to make this work (even though it will be slow) and any help you can give me would be really appreciated.
Here's the code from the link:
<?php
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// #Author Karthik Tharavaad
// karthik_tharavaad#yahoo.com
// #Contributor Maurice Svay
// maurice#svay.Com
class Face_Detector {
protected $detection_data;
protected $canvas;
protected $face;
private $reduced_canvas;
public function __construct($detection_file = 'detection.dat') {
if (is_file($detection_file)) {
$this->detection_data = unserialize(file_get_contents($detection_file));
} else {
throw new Exception("Couldn't load detection data");
}
//$this->detection_data = json_decode(file_get_contents('data.js'));
}
public function face_detect($file) {
if (!is_file($file)) {
throw new Exception("Can not load $file");
}
$this->canvas = imagecreatefromjpeg($file);
$im_width = imagesx($this->canvas);
$im_height = imagesy($this->canvas);
//Resample before detection?
$ratio = 0;
$diff_width = 320 - $im_width;
$diff_height = 240 - $im_height;
if ($diff_width > $diff_height) {
$ratio = $im_width / 320;
} else {
$ratio = $im_height / 240;
}
if ($ratio != 0) {
$this->reduced_canvas = imagecreatetruecolor($im_width / $ratio, $im_height / $ratio);
imagecopyresampled($this->reduced_canvas, $this->canvas, 0, 0, 0, 0, $im_width / $ratio, $im_height / $ratio, $im_width, $im_height);
$stats = $this->get_img_stats($this->reduced_canvas);
$this->face = $this->do_detect_greedy_big_to_small($stats['ii'], $stats['ii2'], $stats['width'], $stats['height']);
$this->face['x'] *= $ratio;
$this->face['y'] *= $ratio;
$this->face['w'] *= $ratio;
} else {
$stats = $this->get_img_stats($this->canvas);
$this->face = $this->do_detect_greedy_big_to_small($stats['ii'], $stats['ii2'], $stats['width'], $stats['height']);
}
return ($this->face['w'] > 0);
}
public function toJpeg() {
$color = imagecolorallocate($this->canvas, 255, 0, 0); //red
imagerectangle($this->canvas, $this->face['x'], $this->face['y'], $this->face['x']+$this->face['w'], $this->face['y']+ $this->face['w'], $color);
header('Content-type: image/jpeg');
imagejpeg($this->canvas);
}
public function toJson() {
return "{'x':" . $this->face['x'] . ", 'y':" . $this->face['y'] . ", 'w':" . $this->face['w'] . "}";
}
public function getFace() {
return $this->face;
}
protected function get_img_stats($canvas){
$image_width = imagesx($canvas);
$image_height = imagesy($canvas);
$iis = $this->compute_ii($canvas, $image_width, $image_height);
return array(
'width' => $image_width,
'height' => $image_height,
'ii' => $iis['ii'],
'ii2' => $iis['ii2']
);
}
protected function compute_ii($canvas, $image_width, $image_height ){
$ii_w = $image_width+1;
$ii_h = $image_height+1;
$ii = array();
$ii2 = array();
for($i=0; $i<$ii_w; $i++ ){
$ii[$i] = 0;
$ii2[$i] = 0;
}
for($i=1; $i<$ii_w; $i++ ){
$ii[$i*$ii_w] = 0;
$ii2[$i*$ii_w] = 0;
$rowsum = 0;
$rowsum2 = 0;
for($j=1; $j<$ii_h; $j++ ){
$rgb = ImageColorAt($canvas, $j, $i);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$grey = ( 0.2989*$red + 0.587*$green + 0.114*$blue )>>0; // this is what matlab uses
$rowsum += $grey;
$rowsum2 += $grey*$grey;
$ii_above = ($i-1)*$ii_w + $j;
$ii_this = $i*$ii_w + $j;
$ii[$ii_this] = $ii[$ii_above] + $rowsum;
$ii2[$ii_this] = $ii2[$ii_above] + $rowsum2;
}
}
return array('ii'=>$ii, 'ii2' => $ii2);
}
protected function do_detect_greedy_big_to_small( $ii, $ii2, $width, $height ){
$s_w = $width/20.0;
$s_h = $height/20.0;
$start_scale = $s_h < $s_w ? $s_h : $s_w;
$scale_update = 1 / 1.2;
for($scale = $start_scale; $scale > 1; $scale *= $scale_update ){
$w = (20*$scale) >> 0;
$endx = $width - $w - 1;
$endy = $height - $w - 1;
$step = max( $scale, 2 ) >> 0;
$inv_area = 1 / ($w*$w);
for($y = 0; $y < $endy ; $y += $step ){
for($x = 0; $x < $endx ; $x += $step ){
$passed = $this->detect_on_sub_image( $x, $y, $scale, $ii, $ii2, $w, $width+1, $inv_area);
if( $passed ) {
return array('x'=>$x, 'y'=>$y, 'w'=>$w);
}
} // end x
} // end y
} // end scale
return null;
}
protected function detect_on_sub_image( $x, $y, $scale, $ii, $ii2, $w, $iiw, $inv_area){
$mean = ( $ii[($y+$w)*$iiw + $x + $w] + $ii[$y*$iiw+$x] - $ii[($y+$w)*$iiw+$x] - $ii[$y*$iiw+$x+$w] )*$inv_area;
$vnorm = ( $ii2[($y+$w)*$iiw + $x + $w] + $ii2[$y*$iiw+$x] - $ii2[($y+$w)*$iiw+$x] - $ii2[$y*$iiw+$x+$w] )*$inv_area - ($mean*$mean);
$vnorm = $vnorm > 1 ? sqrt($vnorm) : 1;
$passed = true;
for($i_stage = 0; $i_stage < count($this->detection_data); $i_stage++ ){
$stage = $this->detection_data[$i_stage];
$trees = $stage[0];
$stage_thresh = $stage[1];
$stage_sum = 0;
for($i_tree = 0; $i_tree < count($trees); $i_tree++ ){
$tree = $trees[$i_tree];
$current_node = $tree[0];
$tree_sum = 0;
while( $current_node != null ){
$vals = $current_node[0];
$node_thresh = $vals[0];
$leftval = $vals[1];
$rightval = $vals[2];
$leftidx = $vals[3];
$rightidx = $vals[4];
$rects = $current_node[1];
$rect_sum = 0;
for( $i_rect = 0; $i_rect < count($rects); $i_rect++ ){
$s = $scale;
$rect = $rects[$i_rect];
$rx = ($rect[0]*$s+$x)>>0;
$ry = ($rect[1]*$s+$y)>>0;
$rw = ($rect[2]*$s)>>0;
$rh = ($rect[3]*$s)>>0;
$wt = $rect[4];
$r_sum = ( $ii[($ry+$rh)*$iiw + $rx + $rw] + $ii[$ry*$iiw+$rx] - $ii[($ry+$rh)*$iiw+$rx] - $ii[$ry*$iiw+$rx+$rw] )*$wt;
$rect_sum += $r_sum;
}
$rect_sum *= $inv_area;
$current_node = null;
if( $rect_sum >= $node_thresh*$vnorm ){
if( $rightidx == -1 )
$tree_sum = $rightval;
else
$current_node = $tree[$rightidx];
} else {
if( $leftidx == -1 )
$tree_sum = $leftval;
else
$current_node = $tree[$leftidx];
}
}
$stage_sum += $tree_sum;
}
if( $stage_sum < $stage_thresh ){
return false;
}
}
return true;
}
}
Usage:
$detector = new Face_Detector('detection.dat');
$detector->face_detect('maurice_svay_150.jpg');
$detector->toJpeg();
The problem I am running into, seems to be coming up in the comments on that page as well. "imagecolorat() [function.imagecolorat]: 320,1 is out of bounds." So, I added a error_reporting(0) to the top of the file (not really the solution), and it seems to work sometimes while other times it just doesn't do anything.
Any thoughts?
It would probably be easier/safer to do this with OpenCV, which is written in lower-level code. PHP is interpreted, so it's likely going to be hella slow when doing the job.
Hope this helps!
You need to turn off error reporting
<?php
ini_set( 'display_errors', 1 );
error_reporting( E_ALL ^ E_NOTICE );
require_once('face_detector.php');
$detector = new Face_Detector('detection.dat');
$detector->face_detect('img/8.jpg');
$detector->toJpeg();
?>
The project has been upgraded on github repository by following this link Face detection
The problem was on the loop, this code works fine :
for ($i=1; $i<$ii_h-1; $i++) {
$ii[$i*$ii_w] = 0;
$ii2[$i*$ii_w] = 0;
$rowsum = 0;
$rowsum2 = 0;
for ($j=1; $j<$ii_w-1; $j++) {
$rgb = ImageColorAt($canvas, $j, $i);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$grey = (0.2989*$red + 0.587*$green + 0.114*$blue)>>0; // this is what matlab uses
$rowsum += $grey;
$rowsum2 += $grey*$grey;
$ii_above = ($i-1)*$ii_w + $j;
$ii_this = $i*$ii_w + $j;
$ii[$ii_this] = $ii[$ii_above] + $rowsum;
$ii2[$ii_this] = $ii2[$ii_above] + $rowsum2;
}
}
Good luck
Try removing the +1 from these lines:
$ii_w = $image_width+1;
$ii_h = $image_height+1;
This code is trying to check the colors from positions 1 to 320 instead of 0 to 319 in the 320 pixel image.
This is an old topic but still this fix is better than any I saw so far so, it might help someone
// Turn off error reporting...
$ctl = error_reporting();
error_reporting(0);
$detector = new Face_Detector('detection.dat');
$detector->face_detect('img/8.jpg');
$detector->toJpeg();
// Turn on reporting...if you wish
error_reporting($ctl);
Quick fix: in the compute_ii function
Replace:
$rgb = ImageColorAt($canvas, $j, $i);
With:
$rgb = ImageColorAt($canvas, $j-1, $i-1);