質問

I am trying to implement contrast stretching function in php gd and I want to set 5th percent of the image as min value and 95th as max value. Anyone know how to get the histogram and those values using php gd?

Thank you.

役に立ちましたか?

解決

I'm afraid you'll need to count pixels one by one.

$gd = // Create image of same size, copy original image into $gd
// Make grayscale
imageFilter($gd, IMG_FILTER_GRAYSCALE);

$pre = array_fill(0, 256, 0);

for ($y = 0; $y < ImageSY($gd); $y++)
{
    for ($x = 0; $x < ImageSX($gd); $x++)
    {
        $luma = (imageColorAt($x, $y) & 0xFF); // Grayscale, so R=G=B=luma
        $pre[$luma]++;
    }
}

// Then you need to build the cumulative histogram:

$max = $pre[0];
$hist[0] = $pre[0];
for ($i = 1; $i < 256; $i++)
{
    $hist[$i] = $hist[$i-1]+$pre[$i];
    if ($max < $pre[$i])
            $max = $pre[$i];
}
// Now scale to 100%
for ($i = 0; $i < 256; $i++)
{
    $hist[$i] = ($hist[$i]*100.0)/((float)$hist[255]);
    if ($hist[$i] >= 5)
        if ((0 == $i) || ($hist[$i-1] < 5))
            print "Fifth percentile ends at index $i (not included)\n";
    if ($hist[$i] >= 95)
        if ($hist[$i-1] < 95)
            print "Ninety-fifth percentile begins at index $i (included)\n";
}

// Create graphics, just to check.
// Frequency is red, cumulative histogram is green

$ck = ImageCreateTrueColor(255, 100);
$w  = ImageColorAllocate($ck, 255, 255, 255);
$r  = ImageColorAllocate($ck, 255,   0,   0);
$g  = ImageColorAllocate($ck,   0, 255,   0);
ImageFilledRectangle($ck, 0, 0, 255, 100, $w);
for ($i = 0; $i < 256; $i++)
{
    ImageLine($ck, $i, 100-$hist[$i], $i, 100, $g);
    ImageLine($ck, $i, 100.0-100.0*((float)$pre[$i]/$max), $i, 100, $r);
}
ImagePNG($ck, 'histograms.png');

他のヒント

Get a sorted list of all values (ascending for 5th percentile, descending for 95th). Then loop through all values until the length of the sublist from the start to that index >=5% of the length of the full list. The value at the current index is the percentile you're looking for. Doesn't even involve a histogram.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top