GrayscaleType and scaling colors

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
EchoKo
Posts: 3
Joined: 2014-12-11T07:21:17-07:00
Authentication code: 6789

GrayscaleType and scaling colors

Post by EchoKo »

I'm trying to write a PNG with very specific grayscale values.
In particular, I want certain pixels to have value, say, 80 (out of 255).

The following code writes a PNG that, when inspecting in GIMP, gives the pixels value 20 where I wanted 80.
When looking at the bottom part of the image, 80 seems to be more than halfway across, so something clearly isn't linear.

Code: Select all

  Magick::Image m(Magick::Geometry(256, 256), "white");
  for (size_t r = 0; r < 128; ++r)
    for (size_t c  = 0; c < 256; ++c) {
      double val = 80/255.0;
      m.pixelColor((ssize_t) c, (ssize_t) r, Magick::ColorGray(val));
    }
  for (size_t r = 128; r < 256; ++r)
    for (size_t c  = 0; c < 256; ++c) {
      double val = c  / 255.0;
      m.pixelColor((ssize_t) c, (ssize_t) r, Magick::ColorGray(val));
    }

  m.type(Magick::GrayscaleType);
  m.write("foo.png");
Could someone explain what's going on here?
Is there a way to make it so that the pixel values are linear, so that 128 is halfway across the strip at the bottom, etc.?

Thanks so much!
EchoKo
Posts: 3
Joined: 2014-12-11T07:21:17-07:00
Authentication code: 6789

Re: GrayscaleType and scaling colors

Post by EchoKo »

Update: it looks like moving this line

Code: Select all

  m.type(Magick::GrayscaleType); 
up to right after the image is created makes it work.

Problem resolved.
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: GrayscaleType and scaling colors

Post by snibgo »

Glad you've solved it.

A conversion of 80/255 to 20/255 corresponds exactly to an sRGB->RGB conversion.

Are you using an old version of IM? If so, I suggest you upgrade it. Otherwise, there is a danger than when you do upgrade it, your software will no longer work.
snibgo's IM pages: im.snibgo.com
EchoKo
Posts: 3
Joined: 2014-12-11T07:21:17-07:00
Authentication code: 6789

Re: GrayscaleType and scaling colors

Post by EchoKo »

I'm using whatever's in Ubuntu's apt-get repositories. Seems like it's a bit out of date. I suppose I should build from source.
Post Reply