Rounding error in -compose subtract

Post any defects you find in the released or beta versions of the ImageMagick software here. Include the ImageMagick version, OS, and any command-line required to reproduce the problem. Got a patch for a bug? Post it here.
Post Reply
User avatar
foxyshadis
Posts: 15
Joined: 2010-04-29T19:29:46-07:00
Authentication code: 8675308
Location: Fresno, California

Rounding error in -compose subtract

Post by foxyshadis »

Hello, I'm trying to use subtract for a research project. It mostly works quite well, the original image is reconstructed perfectly, but in a few spots huge errors manifest - where it seems to create a difference of 255 in one or more channels. In all other cases I've verified that the difference is zero, so it's not going both ways. I tried both miff and png as intermediate images.

Looking closer, the problem only and always occurs when a channel in the second image is 255, it will be zero'd. If you reverse the order of the arguments, it doesn't happen (in my test image, I have no pixels at 255, it's a blur).

Here are the exact commandlines I used to create this:

composite -compose subtract blur_fc.png mini_fc.png subtestc.miff
composite -compose subtract blur_fc.png subtestc.miff subtest_fromc.png
composite -compose difference mini_fc.png subtest_fromc.png subtest_diffc.png

Here's the test images if you'd like to look at it.

Bug?
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Rounding error in -compose subtract

Post by fmw42 »

User avatar
foxyshadis
Posts: 15
Joined: 2010-04-29T19:29:46-07:00
Authentication code: 8675308
Location: Fresno, California

Re: Rounding error in -compose subtract

Post by foxyshadis »

I installed the 32-bit, Q8 version, and the bug does not appear. I was originally using the x64 Q16 version. I've just verified that the 32-bit Q16 version is incorrect as well. It looks like this line in composite.c:

Code: Select all

  if (pixel < 0.0)
    pixel+=(QuantumRange+1.0);
It looks like the floating point arithmetic is just far enough off to round incorrectly. I'm not really sure if that should be 1.1 or 0.9 to compensate. My brain is pretty tired at the moment.
Last edited by foxyshadis on 2010-04-29T21:05:33-07:00, edited 1 time in total.
User avatar
foxyshadis
Posts: 15
Joined: 2010-04-29T19:29:46-07:00
Authentication code: 8675308
Location: Fresno, California

Re: Rounding error in -compose subtract

Post by foxyshadis »

fmw42 wrote:-compose subtract will wrap. try using -compose minus. see http://www.imagemagick.org/Usage/compose/#subtract and http://www.imagemagick.org/Usage/compose/#minus
That's the intent. Check my command lines again - if I used minus, it'll destroy the recreated image.
Post Reply