Detect mp3 duration in PHP condition advice - php

I have this script and is working just fine, but i want some conditions for duration, if duration of the file is bigger than 2 minutes to stop uploading the file and if the file is smaller than 1minute, to do the same. Any help appreciated! PS: i don't have any logical upload script.
PHP Script:
<?php
$mp3file = new MP3File("test.mp3");
$duration1 = $mp3file->getDurationEstimate();//(faster) for CBR only
$duration2 = $mp3file->getDuration();//(slower) for VBR (or CBR)
echo MP3File::formatTime($duration2)."\n";
?>
<?php
class MP3File
{
protected $filename;
public function __construct($filename)
{
$this->filename = $filename;
}
public static function formatTime($duration) //as hh:mm:ss
{
//return sprintf("%d:%02d", $duration/60, $duration%60);
$hours = floor($duration / 3600);
$minutes = floor( ($duration - ($hours * 3600)) / 60);
$seconds = $duration - ($hours * 3600) - ($minutes * 60);
return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
}
//Read first mp3 frame only... use for CBR constant bit rate MP3s
public function getDurationEstimate()
{
return $this->getDuration($use_cbr_estimate=true);
}
//Read entire file, frame by frame... ie: Variable Bit Rate (VBR)
public function getDuration($use_cbr_estimate=false)
{
$fd = fopen($this->filename, "rb");
$duration=0;
$block = fread($fd, 100);
$offset = $this->skipID3v2Tag($block);
fseek($fd, $offset, SEEK_SET);
while (!feof($fd))
{
$block = fread($fd, 10);
if (strlen($block)<10) { break; }
//looking for 1111 1111 111 (frame synchronization bits)
else if ($block[0]=="\xff" && (ord($block[1])&0xe0) )
{
$info = self::parseFrameHeader(substr($block, 0, 4));
if (empty($info['Framesize'])) { return $duration; } //some corrupt mp3 files
fseek($fd, $info['Framesize']-10, SEEK_CUR);
$duration += ( $info['Samples'] / $info['Sampling Rate'] );
}
else if (substr($block, 0, 3)=='TAG')
{
fseek($fd, 128-10, SEEK_CUR);//skip over id3v1 tag size
}
else
{
fseek($fd, -9, SEEK_CUR);
}
if ($use_cbr_estimate && !empty($info))
{
return $this->estimateDuration($info['Bitrate'],$offset);
}
}
return round($duration);
}
private function estimateDuration($bitrate,$offset)
{
$kbps = ($bitrate*1000)/8;
$datasize = filesize($this->filename) - $offset;
return round($datasize / $kbps);
}
private function skipID3v2Tag(&$block)
{
if (substr($block, 0,3)=="ID3")
{
$id3v2_major_version = ord($block[3]);
$id3v2_minor_version = ord($block[4]);
$id3v2_flags = ord($block[5]);
$flag_unsynchronisation = $id3v2_flags & 0x80 ? 1 : 0;
$flag_extended_header = $id3v2_flags & 0x40 ? 1 : 0;
$flag_experimental_ind = $id3v2_flags & 0x20 ? 1 : 0;
$flag_footer_present = $id3v2_flags & 0x10 ? 1 : 0;
$z0 = ord($block[6]);
$z1 = ord($block[7]);
$z2 = ord($block[8]);
$z3 = ord($block[9]);
if ( (($z0&0x80)==0) && (($z1&0x80)==0) && (($z2&0x80)==0) && (($z3&0x80)==0) )
{
$header_size = 10;
$tag_size = (($z0&0x7f) * 2097152) + (($z1&0x7f) * 16384) + (($z2&0x7f) * 128) + ($z3&0x7f);
$footer_size = $flag_footer_present ? 10 : 0;
return $header_size + $tag_size + $footer_size;//bytes to skip
}
}
return 0;
}
public static function parseFrameHeader($fourbytes)
{
static $versions = array(
0x0=>'2.5',0x1=>'x',0x2=>'2',0x3=>'1', // x=>'reserved'
);
static $layers = array(
0x0=>'x',0x1=>'3',0x2=>'2',0x3=>'1', // x=>'reserved'
);
static $bitrates = array(
'V1L1'=>array(0,32,64,96,128,160,192,224,256,288,320,352,384,416,448),
'V1L2'=>array(0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384),
'V1L3'=>array(0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320),
'V2L1'=>array(0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256),
'V2L2'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160),
'V2L3'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160),
);
static $sample_rates = array(
'1' => array(44100,48000,32000),
'2' => array(22050,24000,16000),
'2.5' => array(11025,12000, 8000),
);
static $samples = array(
1 => array( 1 => 384, 2 =>1152, 3 =>1152, ), //MPEGv1, Layers 1,2,3
2 => array( 1 => 384, 2 =>1152, 3 => 576, ), //MPEGv2/2.5, Layers 1,2,3
);
//$b0=ord($fourbytes[0]);//will always be 0xff
$b1=ord($fourbytes[1]);
$b2=ord($fourbytes[2]);
$b3=ord($fourbytes[3]);
$version_bits = ($b1 & 0x18) >> 3;
$version = $versions[$version_bits];
$simple_version = ($version=='2.5' ? 2 : $version);
$layer_bits = ($b1 & 0x06) >> 1;
$layer = $layers[$layer_bits];
$protection_bit = ($b1 & 0x01);
$bitrate_key = sprintf('V%dL%d', $simple_version , $layer);
$bitrate_idx = ($b2 & 0xf0) >> 4;
$bitrate = isset($bitrates[$bitrate_key][$bitrate_idx]) ? $bitrates[$bitrate_key][$bitrate_idx] : 0;
$sample_rate_idx = ($b2 & 0x0c) >> 2;//0xc => b1100
$sample_rate = isset($sample_rates[$version][$sample_rate_idx]) ? $sample_rates[$version][$sample_rate_idx] : 0;
$padding_bit = ($b2 & 0x02) >> 1;
$private_bit = ($b2 & 0x01);
$channel_mode_bits = ($b3 & 0xc0) >> 6;
$mode_extension_bits = ($b3 & 0x30) >> 4;
$copyright_bit = ($b3 & 0x08) >> 3;
$original_bit = ($b3 & 0x04) >> 2;
$emphasis = ($b3 & 0x03);
$info = array();
$info['Version'] = $version;//MPEGVersion
$info['Layer'] = $layer;
//$info['Protection Bit'] = $protection_bit; //0=> protected by 2 byte CRC, 1=>not protected
$info['Bitrate'] = $bitrate;
$info['Sampling Rate'] = $sample_rate;
//$info['Padding Bit'] = $padding_bit;
//$info['Private Bit'] = $private_bit;
//$info['Channel Mode'] = $channel_mode_bits;
//$info['Mode Extension'] = $mode_extension_bits;
//$info['Copyright'] = $copyright_bit;
//$info['Original'] = $original_bit;
//$info['Emphasis'] = $emphasis;
$info['Framesize'] = self::framesize($layer, $bitrate, $sample_rate, $padding_bit);
$info['Samples'] = $samples[$simple_version][$layer];
return $info;
}
private static function framesize($layer, $bitrate,$sample_rate,$padding_bit)
{
if ($layer==1)
return intval(((12 * $bitrate*1000 /$sample_rate) + $padding_bit) * 4);
else //layer 2, 3
return intval(((144 * $bitrate*1000)/$sample_rate) + $padding_bit);
}
}
?>
I have managed a solution with this script. See the code below:
<?php
require 'mp3class.php';
$fileMp3 = new MP3File("test.mp3");
$duration = $fileMp3->getDuration();
$time_limit ="00:02:27";
$accept = "Your file has ".MP3File::formatTime($duration)." minute and can be uploaded ";
$decline = "Your file has ".MP3File::formatTime($duration)." minutes and cannot be uploaded";
if(MP3File::formatTime($duration) <= $time_limit) {
echo $accept;
} else {
echo $decline;
}
?>

Related

Thumbnails with Face Detection in PHP

My objective with this script is to make smart thumbnails. In my demo package, I am using two scripts from different sources.
To crop thumbnails (Source) - It totally works like native wordpress thumbnails
Face Detection in PHP (Source)
I am using the Face Detection to get the desired coordinates (where the face is) and then feed the coordinates to the crop script to make a thumbnail.
The problem is, if the Face Detection script does not find a face, it'd just time-out with the time out error
Fatal error: Maximum execution time of 30 seconds exceeded in...
I do not know how to come around this issue.
Is there any way to limit the amount of time the face detector takes to detect? I mean, if not found in like 15 seconds, return null.
Here's the Face Detection code:
<?php
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// 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
namespace svay;
use Exception;
class FaceDetector
{
protected $detection_data;
protected $canvas;
protected $face;
private $reduced_canvas;
/**
* Creates a face-detector with the given configuration
*
* Configuration can be either passed as an array or as
* a filepath to a serialized array file-dump
*
* #param string|array $detection_data
*/
public function __construct($detection_data = 'detection.dat')
{
if (is_array($detection_data)) {
$this->detection_data = $detection_data;
return;
}
if (!is_file($detection_data)) {
// fallback to same file in this class's directory
$detection_data = dirname(__FILE__) . DIRECTORY_SEPARATOR . $detection_data;
if (!is_file($detection_data)) {
throw new \Exception("Couldn't load detection data");
}
}
$this->detection_data = unserialize(file_get_contents($detection_data));
}
public function faceDetect($file)
{
if (is_resource($file)) {
$this->canvas = $file;
} elseif (is_file($file)) {
//getting extension type (jpg, png, etc)
$type = explode(".", $file);
$ext = strtolower($type[sizeof($type)-1]);
$ext = (!in_array($ext, array("jpeg","png","gif"))) ? "jpeg" : $ext;
if ($ext == 'jpeg') {
$this->canvas = imagecreatefromjpeg($file);
} else if ($ext == 'png') {
$this->canvas = imagecreatefrompng($file);
} else if ($ext == 'gif') {
$this->canvas = imagecreatefromgif($file);
}
} else {
throw new Exception("Can not load $file");
}
$im_width = imagesx($this->canvas);
$im_height = imagesy($this->canvas);
//Resample before detection?
$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->getImgStats($this->reduced_canvas);
$this->face = $this->doDetectGreedyBigToSmall(
$stats['ii'],
$stats['ii2'],
$stats['width'],
$stats['height']
);
if ($this->face['w'] > 0) {
$this->face['x'] *= $ratio;
$this->face['y'] *= $ratio;
$this->face['w'] *= $ratio;
}
} else {
$stats = $this->getImgStats($this->canvas);
$this->face = $this->doDetectGreedyBigToSmall(
$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 json_encode($this->face);
}
public function getFace()
{
return $this->face;
}
protected function getImgStats($canvas)
{
$image_width = imagesx($canvas);
$image_height = imagesy($canvas);
$iis = $this->computeII($canvas, $image_width, $image_height);
return array(
'width' => $image_width,
'height' => $image_height,
'ii' => $iis['ii'],
'ii2' => $iis['ii2']
);
}
protected function computeII($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_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;
}
}
return array('ii'=>$ii, 'ii2' => $ii2);
}
protected function doDetectGreedyBigToSmall($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->detectOnSubImage($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 detectOnSubImage($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;
$count_data = count($this->detection_data);
for ($i_stage = 0; $i_stage < $count_data; $i_stage++) {
$stage = $this->detection_data[$i_stage];
$trees = $stage[0];
$stage_thresh = $stage[1];
$stage_sum = 0;
$count_trees = count($trees);
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;
$count_rects = count($rects);
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;
}
}
Here's an example use:
include "facedetection/FaceDetector.php";
$detector = new svay\FaceDetector('detection.dat');
$detector->faceDetect($path);
$coord = $detector->getFace();
Any help or suggest other php thumbnails with face detection script.
Can you increase the time limit? You can use set_time_limit() or change your php.ini if you have access to it.
Also, how big is the detection.dat file? Loading the entire file in memory with file_get_contents() can take some time if the file is large.
Unless you mess up with the FaceDetection code (which is not recommended, unless you will never want to upgrade the library), you won't be able to stop the execution after 15 seconds. They don't provide any hooks where you could tell the script to stop.

GET , will not receive my POST ? PHP

I have created a dynamic signature maker for my online game.
You can create the sig manually via
http://pernix-rsps.com/sig/pcard.php?user=usernamehere
I tried to make a userbox and submit , so that people does not have to visit
http://pernix-rsps.com/sig/pcard.php?user=USERNAME
and edit it, i want it to create the link for them upon entering username
my code for the username box
<center>
<form name="sig" id="sig" method="get" action="pcard.php">
<table border="0">
<tr><td colspan="2"><?php echo isset($_GET["user"])?$_GET["user"]:"";?> </td></tr>
<tr><td width="30">Username</td><td width="249"><input name="username" type="text" id="username" width="150px" placeholder="Username" /> </td></tr>
<tr><td></td><td><input name="btnsubmit" type="submit" id="btnsubmit" title="create sig" /></td></tr>
</table>
</form>
</center>
And then pcard.php
<?php
if (isset($_GET['user'])) {
$image_path = "img/saved_cards/".$_GET['user'].".png";
if (file_exists($image_path)) {
if (time() < filemtime($image_path) + 300) { // every 5 minutes ?
pullFromCache($image_path);
exit;
}
}
generate();
}
function pullFromCache($image_path) {
header("Content-type: image/png");
$image = imagecreatefrompng($image_path);
imagepng($image);
}
function generate() {
$DB_HOST = "localhost";
$DB_USER = "";
$DB_PASS = "";
$DB_NAME = "";
$user = clean($_GET['user']);
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die($con->error);
$res = $con->query("SELECT * FROM hs_users WHERE username='$user'");
if($res->num_rows > 0) {
header("Content-type: image/png");
getSig($res->fetch_assoc());
} else {
header("Content-type: image/png");
$image = imagecreatefrompng('./img/sigbg.png');
$color = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 3, 251, 10, 'Invalid User', $color);
imagepng($image);
}
}
function getSig($row) {
$image = imagecreatefrompng('./img/sigbg.png');
$color = imagecolorallocate($image, 255, 255, 255);
$yellow = imagecolorallocate($image, 255, 255, 0);
$total = getTotalLevel($row);
$combat = getCombatLevel($row);
imagestring($image, 5, 250, 10, ''.$row['username'].'', $yellow);
imagestring($image, 2, 250, 26, 'Exp: '.number_format($row['overall_xp']).'', $color);
imagestring($image, 2, 250, 39, 'Total: '.number_format($total).'', $color);
imagestring($image, 2, 250, 51, 'Pernix-Rsps.com ', $color);
$array = array("Attack", "Defence", "Strength", "hitpoints", "Range", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "pk", "Summoning", "Dungeoneering");
$baseX = 28;
$baseY = 4;
foreach ($array as $i => $value) {
imagestring($image, 2, $baseX, $baseY, ''.getRealLevel($row[''.strtolower($array[$i]).'_xp'], strtolower($array[$i])).'', $color);
$baseY += 15;
if ($baseY > 64) {
$baseY = 4;
$baseX += 45;
}
}
ImagePNG($image, "img/saved_cards/".$row['username'].".png");
imagepng($image);
}
function getTotalLevel($row) {
$total = 0;
$array = array("Attack", "Defence", "Strength", "Hitpoints", "Range", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "pk", "Summoning", "Dungeoneering");
foreach ($array as $i => $value) {
$skillName = strtolower($array[$i]);
$total += getRealLevel($row[$skillName.'_xp'], strtolower($skillName));
}
return $total;
}
function getLevel($exp) {
$points = 0;
$output = 0;
for ($lvl = 1; $lvl <= 99; $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return 99;
}
function getRealLevel($exp, $skill) {
$points = 0;
$output = 0;
$skillId = $skill == "dungeoneering" ? 1 : 0;
for ($lvl = 1; $lvl <= ($skillId == 1 ? 120 : 99); $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return ($skillId == 1 ? 120 : 99);
}
function getDungLevel($exp) {
$points = 0;
$output = 0;
for ($lvl = 1; $lvl <= 120; $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return 120;
}
function clean($string) {
return preg_replace('/[^A-Za-z0-9 \-]/', '', $string);
}
function getCombatLevel($row) {
$attack = getLevel($row['attack_xp']);
$defence = getLevel($row['defence_xp']);
$strength = getLevel($row['strength_xp']);
$hp = getLevel($row['hitpoints_xp']);
$prayer = getLevel($row['prayer_xp']);
$ranged = getLevel($row['range_xp']);
$magic = getLevel($row['magic_xp']);
$combatLevel = (int) (($defence + $hp + floor($prayer / 2)) * 0.25) + 1;
$melee = ($attack + $strength) * 0.325;
$ranger = floor($ranged * 1.5) * 0.325;
$mage = floor($magic * 1.5) * 0.325;
if ($melee >= $ranger && $melee >= $mage) {
$combatLevel += $melee;
} else if ($ranger >= $melee && $ranger >= $mage) {
$combatLevel += $ranger;
} else if ($mage >= $melee && $mage >= $ranger) {
$combatLevel += $mage;
}
return (int)$combatLevel;
}
?>
upon entering and submiting the username in the box, it just takes you to the pcard.php without image being made
any ideas
You are using the wrong fieldname in your PHP. In your form you use the fieldname username:
<input name="username" ... />
And in your PHP you try to get GET['user']. Change that in GET['username'] and everything should work (the getting the value part that is ;)).

Using PHP to grab a simplified colour palette from an image?

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

Percentage to Hexcolor in PHP

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']);
}
}

Face detection in PHP

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

Categories