GetPixel after SetPixel gives incorrect result

青春壹個敷衍的年華 提交于 2019-12-20 04:50:47

问题


I set pixel from one jpg. Save it another jpg file. Read a new file again. Get pixel. But it gives me incorrect result. That's my code:

use Image::Magick;
use Data::Dumper;

my $im = new Image::Magick;
$im->Read('file1.jpg');
my @pixel = $im->GetPixel(x=>0,y=>0,channel=>'RGB', normalize=>'True');
print Dumper(@pixel);

my @color = ('1.0', '0.0', '0.0');
$im->SetPixel(x=>0, y=>0, channel=>'RGB', normalize=>'True', color => \@color);
$im->Write('file30.jpg');

@pixel = $im->GetPixel(x=>0,y=>0,channel=>'RGB', normalize=>'True');
print Dumper(@pixel);

print "-" x 30, "\n";
my $nim = new Image::Magick;
$nim->Read('file30.jpg');

my @npixel = $nim->GetPixel(x=>0,y=>0,channel=>'RGB', normalize=>'True');
print Dumper(@npixel);

when I run it:

$VAR1 = '0.133333333333333';
$VAR2 = '0.141176470588235';
$VAR3 = '0.0588235294117647';
$VAR1 = '1';
$VAR2 = '0';
$VAR3 = '0';
------------------------------
$VAR1 = '0.32156862745098';
$VAR2 = '0.247058823529412';
$VAR3 = '0.188235294117647';

Why @npixel gives me wrong result? How can it be fixed?

UPD

It works fine with .BMP files.


回答1:


Posting an answer to correspond to my comment above.

This would be best explained by a comparison of lossy vs lossless compression:

https://en.wikipedia.org/wiki/Lossy_compression

In short, you can work with an array of RGB pixels with imagemagick, set pixel values, get them, etc.

When you save, there are additional operations that are out of your control. In the case of JPEG, it is a lossy compression algorithm known as DCT (discrete cosine transformation): http://en.wikipedia.org/wiki/Discrete_cosine_transform. This lossy compression (in the case of JPEG) is necessary in order to reduce the file size.

If you do not want to encounter this issue, you either need to work with:

  1. Uncompressed data (ie: RAW/BMP files). When you save the file, it is written as-is to an output file. No compression or distortion is applied. http://en.wikipedia.org/wiki/BMP_file_format
  2. Use lossless compression. This typically compresses the data to reduce the file size, but does not shrink the file size as much as lossy compression does. PNG is an example of this, and ImageMagick supports it. Your data is NOT written as-is to the output file, but it is translated when saving and opening so you get all the original data back for every pixel exactly. http://en.wikipedia.org/wiki/Portable_Network_Graphics


来源:https://stackoverflow.com/questions/16724211/getpixel-after-setpixel-gives-incorrect-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!