Checking if an image format is Lossless in Python? - python

I am working on an application that requires images submitted to it to be lossless. Currently I am opening the image with PIL and checking if the "format" attribute is a lossless format. This requires me to manually keep a list of formats, and I have no idea if, for instance, a jpeg that was submitted just happens to have the lossless variant applied.
import PIL
import PIL.Image
def validate_image(path):
img = PIL.Image.open(path)
if not img.format.lower() in ['bmp', 'gif', 'png', ...]:
raise Exception("File %s has invalid image format %s" % (path, img.format))
Is there a better way to check if the image file is lossless?

I think I now understand things: You want to open the images via PIL. You want to reject lossy images because you're doing scientific processing of some kind that needs all that lost data because information that's unimportant for human visual processing is important for your algorithms.
PIL does not have any kind of interface at the top level to distinguish different types of compression. You could reach inside the image decoders and assume that anything that uses the "raw" decoder is lossless, but even if you wanted to do that, that's too limited—it'll rule out GIF, LZW-compressed TIFF, etc. along with JPEG, JPEG-compressed TIFF, etc.
Keep in mind that the real problem is here is messaging and documentation—managing user expectations. The check for lossy images is really just a heuristic, a way to catch the more obvious mistakes and remind the user what the requirements are. So, you don't need something perfect, but having something pretty good may be helpful anyway.
So, there are only a few options, none of them very good:
Hack up PIL's decoder source to retain the encoding information and pass it up to the top level. This is, obviously, going to take some non-trivial work, in 30 different importers, possibly involving C as well as Python, and it will result in a patch that you have to maintain against a (slowly-)evolving codebase—although of course you can always submit it upstream and hope that it makes it into future versions of PIL.
Dig into the decoders themselves to get the information at runtime. The only semi-standard thing you can really find is whether they use the raw decoder or the bit decoder, which isn't useful at all (many lossless formats will need the bit decoder), so you'll probably end up reading all 30 importers and writing a dozen or so pieces of code to extract information from them.
Use another library along with (or in place of) PIL. For example, while ImageMagick is definitely not significantly easier than PIL, it does have an API to tell you what type of compression an image file uses. Basically, if it's UndefinedCompression or JPEGCompression it's lossy, anything else, it's lossless. The major downside (besides needing to install two image libraries) is that there will be files that PIL can open but IM can't, and vice-versa, and multi-image files that PIL and IM handle differently, and so on.
Do what you're already doing. Read through the 30 importers to make a list of which are lossy and which are lossless. To handle cases like JPEG and TIFF that are sometimes lossless, you may want to write code that doesn't flat-out reject them, but instead gives a warning saying "These files may be lossy. Are you sure you want to import them?" (Or, alternatively, just offer an "I know what I'm doing" override for all lossy formats, and then just consider JPEG and TIFF lossy.)
For many use cases, I'd be very wary of going with #4, but for yours, it actually seems pretty reasonable. You're not trying to block lossy images because your code will crash, or for security reasons, or anything like that; you're just trying to warn people that they're going to waste a lot of time getting useless information if they submit a JPEG, right?

Related

Python: Tensorflow PNG encoding

I'm trying to figure out the reason, why this code snippet returns False:
decodedBase64 = tf.io.decode_base64(imgBase64)
decodedBase64==tf.io.encode_png(tf.io.decode_png(decodedBase64))
A png image can be compressed and decode_png detects it, so I used different 'compression=' values in encode_png. I still got False with all values between -1 to 9.
What can be done to retrieve correct decodedBase64 characteristics to make encode_png <-> decode_png reversible?
I am not very familiar with tensorflow and your code is not runnable to be able to try it, so I may well be wrong and will delete my answer if so. I also think that the base64 encoding and decoding is something of a red herring. I think you are actually asking why you get a different PNG from one you already have when you encode with tensorflow. If so, there are several possible reasons:
the date and time may be encoded in the PNG so if you write a PNG and then write it again with the same compression 1 second later, it will differ if that is the case
the original PNG might have been created with a different library, a different version or different parameters, and although you will get the same pixels back because the encoding is lossless, the encoded data on disk could differ. For example, one library might choose a different filter for some rows - or no filter at all
Of course, if you want a definitive rather than speculative answer, you'd need to share the 2 PNGs - unmodified.

How to improve the quality of function ‘image.save()’?

I saved the image to the clipboard, and when I read the image information from the clipboard and saved it locally, the image quality changed. How can I save it to maintain the original high quality?
from PIL import ImageGrab
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
I tried adding the parameter 'quality=95' in im.save(), but it didn't work. The original image quality is 131K, and the saved image is 112K.
The size of the file is not directly related to the quality of the image. It also depends on how efficiently the encoder does its job. As it is PNG, the process is lossless, so you don't need to worry - the quality is retained.
Note that the quality parameter has a different meaning when saving JPEG files versus PNG files:
With JPEG files, if you specify a lower quality you are effectively allowing the encoder to discard more information and give up image quality in return for a smaller file size.
With PNG, your encoding and decoding are lossless. The quality is a hint to the decoder as to how much time to spend compressing the file (always losslessly) and about the types of filtering/encoding that may suit best. It is more akin to the parameter to gzip like --best or --fast.
Further information about PNG format is here on Wikipedia.
Without analysing the content of the two images it is impossible to say why the sizes differ - there could be many reasons:
One encoder may have noticed that the image contains fewer than 256 colours and so has decided to use a palette whereas the other may not have done. That could make the images size differ by a factor of 3 times, yet the quality would be identical.
One encoder may use a larger buffer and spend longer looking for repeating patterns in the image. For a simplistic example, imagine the image was 32,000 pixels wide and each line was the same as the one above. If one encoder uses an 8kB buffer, it can never spot that the image just repeats over and over down the page so it has to encode every single line in full, whereas an encoder with a 64kB buffer might just be able to use 1 byte per line and use the PNG filtering to say "same as line above".
One encoder might decide, on grounds of simplicity of code or for lack of code space, to always encode the data in a 16-bit version even if it could use just 8 bits.
One encoder might decide it is always going to store an alpha layer even if it is opaque because that may make the code/data cleaner simpler.
One encoder may always elect to do no filtering, whilst the other has the code required to do sub, up, average or Paeth filtering.
One encoder may not have enough memory to hold the entire image, so it may have to use a simplistic approach to be assured that it can handle whatever turns up later in the image stream.
I just made these examples up - don't take them was gospel - I am just trying to illustrate some possibilities.
To reproduce an exact copy of file from a clipboard, the only way is if the clipboard contains a byte-for-byte copy of the original. This does not happen when the content comes from the "Copy" function in a program.
In theory a program could be created to do that by setting a blob-type object with a copy of the original file, but that would be highly inefficient and defeat the purpose of the clipboard.
Some points:
- When you copy into the clipboard using the file manager, the clipboard will have a reference to the original file (not the entire file which can potentially be much larger than ram)
- Most programs will set the clipboard contents to some "useful version" of the displayed or selected data. This is very much subject to interpretation by the creator of the program.
- Parsing the clipboard content when reading an image is again subject to the whims of the library used to process the data and pack it back into an image format.
Generally if you want to copy a file exactly you will be better off just copying the original file.
Having said that: Evaluate the purpose of the copy-paste process and decide whether the data you get from the clipboard is "good enough" for the intended purpose. This obviously depends on what you want to use it for.

How do I read an arbitrary image file format (PNG, JPEG, TIFF, BMP) in Python using only the standard library?

I'm an experienced Python programmer with plenty of image manipulation and computer vision experience. I'm very familiar with all of the standard tools like PIL, Pillow, opencv, numpy, and scikit-image.
How would I go about reading an image into a Python data format like a nested list, bytearray, or similar, if I only had the standard library to work with?
I realize that different image formats have different specifications. My question is how I would even begin to build a function that reads any given format.
NOTE Python 2.6 had a jpeg module in the standard library that has since been deprecated. Let's not discuss that since it is unsupported.
If you're asking how to implement these formats "from scratch" (since the standard libraries don't do this), then a good starting point would be the format specification.
For PNG, this is https://www.w3.org/TR/2003/REC-PNG-20031110/. It defines the makeup of a PNG stream, consisting of the signature (eight bytes, 8950 4e47 0d0a 1a0a, which identifies the file as a PNG image) and a number of data chunks that contain meta data, palette information and the image itself. (It's certainly a substantial project to take on, if you really don't want to use the existing libraries, but not overly so.)
For BMP, it's a bit easier since the file already contains the uncompressed pixel data and you only need to know how to find the size and offset; some of the format definition is on Wikipedia (https://en.wikipedia.org/wiki/BMP_file_format) and here: http://www.digicamsoft.com/bmp/bmp.html
JPG is much trickier. The file doesn't store pixels, but rather "wavelets" which are transformed into the pixel map you see on the screen. To read this format, you'll need to implement this transformation function.

How to get just the image format with Magick/py-wand?

I'm using py-wand to read images in Python. All I really want though is the image meta information, like size, format, color depth, etc. I don't want to load the entire image. Some of my images are extremely large and loading them this way is causing memory problems.
How can I get just the meta information?
The Magickwand method for this is MagickPingImageFile. I quickly skimmed the pywand documentation and didn't see a binding to this method, but it might be provided under another name than 'ping'. It may require a feature request.

"logging" images

I'm writing a scientific program that has some intermediate results (plots and images) that I'd like to log (additional to the usual text messages).
I like python's logging interface a lot, so I'm wondering if there is a possibility to use it to create log files that include images.
The first idea that came to my mind was creating a log file as a SVG, so the log text is machine readable and the images can be included easily.
Is there a better approach to make this possible?
You could use SVG, but I'm not sure how compact the SVG would be since it would probably (in general) store the bitmap rather than vector information. An alternative would be to base64-encode the image and store it using a structured format, as documented here - the linked example uses JSON, which might be handy to e.g. store metadata about the image, but you could use a simpler scheme if all you're storing is the image and the format is always the same.

Categories