11

I want to retrieve the bit depth for a jpeg file using Python.

Using the Python Imaging Library:

import Image
data = Image.open('file.jpg')
print data.depth

However, this gives me a depth of 8 for an obviously 24-bit image. Am I doing something wrong? Is there some way to do it with pure Python code?

Thanks in advance.

Edit: It's data.bits not data.depth.

needthehelp
  • 113
  • 1
  • 1
  • 5
  • Are you sure you're using the right function? I couldn't find depth in the PIL Handbook and perhaps the return value of 8 is still correct - it could stand for "8 bits per pixel". – schnaader Jan 03 '10 at 22:45
  • Yeah it's 8 bpp. What wasn't obvious (to me) was that it was for each band as per Mike's answer. – needthehelp Jan 03 '10 at 22:52

4 Answers4

17

I don't see the depth attribute documented anywhere in the Python Imaging Library handbook. However, it looks like only a limited number of modes are supported. You could use something like this:

mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32, 'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}

data = Image.open('file.jpg')
bpp = mode_to_bpp[data.mode]
Debvrat Varshney
  • 450
  • 1
  • 7
  • 15
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 1
    There are more modes this is a more complete dictionary: `mode_to_bpp = {"1": 1, "L": 8, "P": 8, "RGB": 24, "RGBA": 32, "CMYK": 32, "YCbCr": 24, "LAB": 24, "HSV": 24, "I": 32, "F": 32}` – Mehdi Nellen Jan 18 '19 at 14:26
  • Also some experimental modes exist: `"I;16": 16, "I;16B": 16, "I;16L": 16, "I;16S": 16, "I;16BS": 16, "I;16LS": 16, "I;32": 32, "I;32B": 32, "I;32L": 32, "I;32S": 32, "I;32BS": 32, "I;32LS": 32` – Mehdi Nellen Jan 18 '19 at 14:27
7

Jpeg files don't have bit depth in the same manner as GIF or PNG files. The transform used to create the Jpeg data renders a continuous color spectrum on decompression.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
4

PIL is reporting bit depth per "band". I don't actually see depth as a documented property in the PIL docs, however, I think you want this:

data.depth * len(data.getbands())

Or better yet:

data.mode

See here for more info.

Mike
  • 4,976
  • 2
  • 18
  • 11
2

I was going to say that JPG images are 24 bit by definition. They normally consist of three 8 bit colour channels, one for each of red, green and blue making 24 bits per pixel. However, I've just found this page which states:

If you use a more modern version of Photoshop, you'll notice it will also let you work in 16-bits per channel, which gives you 48 bits per pixel.

But I can't find a reference for how you'd tell the two apart.

ChrisF
  • 134,786
  • 31
  • 255
  • 325