How to calculate 2D DCT of an image using php?
I am trying to find 2D DCT (Discrete Cosine Transform) of an image using php. I found the following equation to find it.
Here is the code I used to find the DCT.
function getGray($img,$x,$y){
$col = imagecolorsforindex($img, imagecolorat($img,$x,$y));
return intval($col['red']*0.3 + $col['green']*0.59 + $col['blue']*0.11);
}
function initCoefficients() {
for ($i=1;$i<$this->size;$i++)
{
$c[$i]=1;
}
$c[0]=1/sqrt(2.0);
return $c;
}
function applyDCT($imagePath) {
$img = $this->readImageTo($imagePath, 32, 32);
$color=array();
for($i=0;$i<32;$i++)
{
for($j=0;$j<32;$j++)
{
$color[]=$this->getGray($img,$i,$j);
}
}
$N=32;
$c=$this->initCoefficients();
$sum=0;
for ($u=0;$u<$N;$u++) {
for ($v=0;$v<$N;$v++) {
for ($i=0;$i<$N;$i++) {
for ($j=0;$j<$N;$j++) {
$sum += ($c[$i]*$c[$j])*cos(((2*$i+1)*$u*pi()/(2.0*$N)))*cos(((2*$j+1)*$v*pi()/(2.0*$N)))*($color[$i][$j]);
}
}
$sum *=sqrt(2/$N)*sqrt(2/$N);
$F[$u][$v] = $sum;
}
}
return $F;
}
Image size 32*32
. My problem is that after the function is called, applyDCT()
it gives an array that has all the element values as 0.
eg: -
Array ([0] => Array (..., 3 => 0 [4] => 0 [5] => 0, ...
I think the problem is in my calculations. What am I doing wrong? please help me Thanks.
source to share
Here's an answer based on the comments:
the color is not very good. You initialize it to 1D, but you call it in your math operation as if it were a 2D array. In your math operation replace $ color [$ i] [$ j] with $ color [$ i * 32 + $ j] and it should work I guess ... Or make sure your $ color array is formed like you expect
source to share