donglu9978 2014-08-20 09:07
浏览 42
已采纳

如何知道图像中存在多少种颜色?

<?php
$img=imagecreatefrompng('dense.png');
list($width, $height)=getimagesize('dense.png'); 
$t=0;
for( $i=0 ; $i<$height ; $i++ )
{
    for( $j=0 ; $j<$width ; $j++ )
    {
        $pix  = imagecolorat($img, $i, $j);
        $cols = imagecolorsforindex($img, $pix);
        $r = $cols['red'];
        $g = $cols['green'];
        $b = $cols['blue'];
        $pixel[$i][$j][0]=$r;
        $pixel[$i][$j][1]=$g;
        $pixel[$i][$j][2]=$b;       
        }
}

for( $i=0 ; $i<$height ; $i++ )
{
    for( $j=0 ; $j<$width ; $j++ )
    {
        echo "(".$i.",".$j.") color of that pixel is (".$pixelcolor[$i][$j][0].",".$pixelcolor[$i][$j][1].",".$pixelcolor[$i][$j][2].").</p>";
    }
    echo"<br/>";
}
?>

This is the my code but when i run this code its give me blank webpage.

I want to make one array which store the rgb value of each pixel and it also print on the webpage and reduce those value which are repeating in the array.

so i want to know that how many colors are exist in the images?

  • 写回答

2条回答 默认 最新

  • duanguochi6194 2014-08-22 13:22
    关注

    Your code is probably dying from a memory exhaustion error. Creating a million or so arrays can cause that. Here's a script that counts the number of unique colors in an image in a fairly efficient manner (for PHP):

    <?php
    
    $path = "test.jpg";
    
    $img = imagecreatefromjpeg($path);
    $w = imagesx($img);
    $h = imagesy($img);
    
    // capture the raw data of the image
    ob_start();
    imagegd2($img, null, $w);
    $data = ob_get_clean();
    $totalLength = strlen($data);
    
    // calculate the length of the actual pixel data
    // from that we can derive the header size
    $pixelDataLength = $w * $h * 4;
    $headerLength = $totalLength - $pixelDataLength;
    
    // use each four-byte segment as the key to a hash table
    $counts = array();
    for($i = $headerLength; $i < $totalLength; $i += 4) {
        $pixel = substr($data, $i, 4);
        $count =& $counts[$pixel];
        $count += 1;
    }
    $colorCount = count($counts);
    echo $colorCount;
    
    ?>
    

    $colorCount is the number of unique colors in the image. $counts gives you the number of times each color occurs. Each $key is a 4-byte string. The first byte is transparency. A value of zero means opaque. The second, third, and fourth bytes are R, G, and B respectively. You'll need to call ord() to get the value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大