Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PNG to PGM conversion without quality loss

So, I have a PNG image file like the following example, and I need it to be converted into PGM format.

enter image description here

I'm using Ubuntu and Python, so any of terminal or Python tools would suit just fine. And there sure is a plenty of ways to do this: using ImageMagick convert command or pngtopam package or Python PIL library, etc.

But the point is, the quality of the image is essential in my case, and all of those failed in keeping it, always ending up with:

enter image description here

No need to mention this is totally not what I want to see. And the interesting thing is that when I tried to convert the same image into PGM manually using GIMP, it turned out quite well, looking exactly the way I'd like it to, i.e. the same as the PNG one.

So, that means it is possible to get a PGM image in fine quality after all, and now I'd really appreciate if someone can tell me how do I do that using terminal/Python tools. I guess, there should be some ImageMagick option that does the trick, it's just that I'm not aware of any.

like image 342
Romitas Avatar asked Dec 15 '22 10:12

Romitas


1 Answers

You lost the antialiasing, which is conveyed via the alpha channel. To preserve it, use:

convert in.png -flatten out.pgm

Without -flatten, convert simply deletes the alpha channel; with -flatten it composites the input image against the background color, which is white by default.

Here are the results, magnified 10x so you can see what's going on:

Not flattened:not flattened Flattened:flattened

like image 159
Glenn Randers-Pehrson Avatar answered Jan 02 '23 02:01

Glenn Randers-Pehrson