我正在尝试在php gd中实现对比度拉伸功能,我想将图像的5%设置为最小值,将第95%设置为最大值。谁知道如何使用php gd获取直方图和这些值?
谢谢。
答案 0 :(得分:4)
我担心你需要逐个计算像素。
$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');
答案 1 :(得分:0)
获取所有值的排序列表(升序为第5个百分位,降序为第95个)。然后遍历所有值,直到子列表从开始到该索引的长度&gt; =完整列表长度的5%。当前指数的值是您正在寻找的百分位数。甚至不涉及直方图。