[Perl][图片处理]判断一张壁纸是深色还是浅色

There's more than one way to do it!
https://metacpan.org http://perlmonks.org
回复
头像
523066680
Administrator
Administrator
帖子: 523
注册时间: 2016年07月19日 12:14
联系:

[Perl][图片处理]判断一张壁纸是深色还是浅色

帖子 523066680 »

参考:

结合以上参考,写出最终代码:

代码: 全选

use utf8;
use Encode;
use Modern::Perl;
use File::Slurp;
use Image::Magick;
use JSON qw/from_json to_json/;
STDOUT->autoflush(1);

# 图片路径使用 gbk编码,关键字使用 Unicode
my $pics = [
    gbk("../壁纸/壁纸1.png"),
    gbk("../壁纸/壁纸2.png") 
];

for my $e ( @$pics )
{
    my ($r, $g, $b) = get_avg_color( $e );
    say $e;

    # 转换成YUV格式的亮度值
    my $value = sprintf "%.2f", $r * 0.299 + $g * 0.587 + $b * 0.114;
    say $value;
} 

write_file($cfg_file, gbk($cfg));

# 获取所有像素颜色的平均值
sub get_avg_color
{
    my ( $pic ) = @_;
    my $img = Image::Magick->new();
    $img->Read( decode('gbk', $pic) );

    my @hist_data = $img->Histogram;
    my @hist_entries;

    # Histogram returns data as a single list, but the list is actually groups of
    # 5 elements. Turn it into a list of useful hashes.

    my $sum = {'r' => 0, 'g' => 0, 'b' => 0};
    my $pixels = 0;
    while ( @hist_data ) 
    {
        my ($r, $g, $b, $a, $count) = splice @hist_data, 0, 5;
        $sum->{'r'} += ($r / 255) * $count;
        $sum->{'g'} += ($g / 255) * $count;
        $sum->{'b'} += ($b / 255) * $count;
        $pixels += $count;
    }

    $sum->{'r'} /= $pixels;
    $sum->{'g'} /= $pixels;
    $sum->{'b'} /= $pixels;
    
    return @{$sum}{'r','g','b'};
}


sub gbk { encode('gbk', $_[0]) }
sub utf8 { encode('utf8', $_[0]) }
sub u2gbk { encode('gbk', decode('utf8', $_[0])) }
sub uni { decode('utf8', $_[0]) }
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 1 访客