以下是我使用的代码以及我应用每个过滤器的原因。我已经对这些功能和设置进行了大量测试,但您仍需要运行一些测试来优化您的图像集的这些设置。
在计算以下图像属性时,我使用了 IMagick(ImageMagick 的 PHP 包装器)来完成这项工作:
$Image = new Imagick( $image_path );
$height = $Image->getImageHeight();
$width = $Image->getImageWidth();
$histogram = $Image->getImageHistogram();
$num_colors = $image->getImageColors();
高宽比
按高宽比过滤图像可消除大部分垃圾。将过滤器设置为 1:1 越接近,此过滤器的效果就越好,但您也会开始过滤很多好的图像。这是我应用的最有价值的过滤器之一:
// max height to width ratio we allow on images before we junk them
$max_size_ratio = 3;
if( $size_ratio > $max_size_ratio )
throw new Exception( "image height to width ratio exceeded max of $max_size_ratio" );
颜色数量
过滤32色以下的图片一般只能去除垃圾图片,但是我也丢失了很多黑白图表和图纸。
// min number of colors allowed before junking
$min_colors = 32;
if( $num_colors < $min_colors )
throw new Exception( "image had less than $min_colors colors" );
最小高度和宽度
根据两个维度必须通过的绝对最小高度和宽度以及至少一个维度必须通过的稍大的值过滤图像有助于过滤一些垃圾。
// min height and width in pixels both dimensions must meet
$min_height_single = 50;
$min_width_single = 50;
if(
$width < $min_width_single
OR $height < $min_height_single
)
throw new Exception( "height or width were smaller than absolute minimum" );
// min height and width in pixels at least one dimension must meet
$min_height = 75;
$min_width = 75;
if(
$width < $min_width
&& $height < $min_height
)
throw new Exception( "height and width were both smaller than minimum combo" );
使用图像直方图的图像颜色熵
最后,我为系统中的每个图像计算图像颜色熵(正如@Jason 在他的回答中所建议的那样)。当我选择要显示的图像时,我通常按此熵按降序排列它们。熵越高,图像就越有可能是真实事物的照片,而不是图形。这种方法存在三个主要问题:
由于颜色深度和颜色变化很大,高度风格化的图形往往具有更高的熵。
经过 photoshop 处理以具有纯色背景和工作室背景的照片往往具有较低的熵,因为主要是纯色。
由于我的集合中的图像、它们的文件类型、颜色深度等之间存在很大差异,这作为绝对过滤器效果不佳。然而,它非常有用的地方在于选择最佳图像我的整个集合中的一个小子集。例如,从一个网页上找到的所有图像中选择要显示的主图像。
这是我用来计算图像熵的函数:
function set_image_entropy()
{
// create Imagick object and get image data
$Image = new Imagick( $this->path );
$histogram = $Image->getImageHistogram();
$height = $Image->getImageHeight();
$width = $Image->getImageWidth();
$num_pixels = $height * $width;
// calculate entropy for each color in the image
foreach( $histogram as $color )
{
$color_count = $color->getColorCount();
$color_percentage = $color_count / $num_pixels;
$entropies[] = $color_percentage * log( $color_percentage, 2 );
}
// calculate total image color entropy
$entropy = ( -1 ) * array_sum( $entropies );
return $entropy;
}