7

Possible Duplicate:
How to check dimensions of all images in a directory using python?

I was wondering if somebody knows how can I read an image total amount of pixels in a python sript. Could you provide and example?

Thanks a lot.

Community
  • 1
  • 1
user175259
  • 4,641
  • 5
  • 20
  • 15

4 Answers4

22

here is an example:

from PIL import Image

def get_num_pixels(filepath):
    width, height = Image.open(filepath).size
    return width*height

print(get_num_pixels("/path/to/my/file.jpg"))
gcamargo
  • 3,683
  • 4
  • 22
  • 34
pcardune
  • 690
  • 3
  • 7
  • 3
    While not incorrect, `open(filepath)` is not required - `Image.open()` will accept just the filename. – mhawke Oct 16 '09 at 01:26
  • @mhawke I inserted the filename of the file located in my project directory, but I still get `unresolved file reference` error. – the_prole Nov 16 '14 at 19:18
6

Use PIL to load the image. The total number of pixels will be its width multiplied by its height.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
5

Here is the example that you've asked for:

from PIL import Image
import os.path

filename = os.path.join('path', 'to', 'image', 'file')
img = Image.open(filename)
width, height = img.size
print "Dimensions:", img.size, "Total pixels:", width * height
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

PIL, the Python Imaging Library can help you get this info from image's metadata.

mjv
  • 73,152
  • 14
  • 113
  • 156