Flora
Flora

Reputation: 11

Finding average color using Python

can someone explain me how the main function for the code below works? what does it mean by the average_image_color() function take argument of sys.argv[1] in the main function?

from PIL import Image

def average_image_color(filename):

    i = Image.open(filename)
    h = i.histogram()

    # split into red, green, blue
    r = h[0:256]
    g = h[256:256*2]
    b = h[256*2: 256*3]

    # perform the weighted average of each channel:
    # the *index* is the channel value, and the *value* is its weight
    return (
        sum( i*w for i, w in enumerate(r) ) / sum(r),
        sum( i*w for i, w in enumerate(g) ) / sum(g),
        sum( i*w for i, w in enumerate(b) ) / sum(b)
    )

if __name__ == '__main__':

    import sys

    if len(sys.argv) > 1:
       print average_image_color(sys.argv[1])
    else:
      print 'usage: average_image_color.py FILENAME'
      print 'prints the average color of the image as (R,G,B) where R,G,B are between 0 and 255.'

I found code above from githubsThank you so much!

Upvotes: 0

Views: 2450

Answers (2)

Saksham Varma
Saksham Varma

Reputation: 2130

sys.argv is a the list of command line arguments that you pass to your script, when you run them from the command line. The first element in this list is always the path of your python script itself. So, sys.argv[0] is the path to your python script. In your case, the second argument is the path to color/input file.

In case the second argument is not supplied, the len of the argv list would be just 1, and the the function average_image_color won't be called. If this second arg is supplied, it would call the function, passing this arg as a parameter. The command would look like this:

python script.py /path/to/the/image/input/file

If you would not like to use command line then, image files can be read from a directory:

import os

if __name__ == '__main__':

    dirpath, dirnames, filenames = next(os.walk('/path/to/images/directory'))
    for filename in filenames:
        print average_image_color(os.path.join(dirpath, filename))

Upvotes: 0

Barun Sharma
Barun Sharma

Reputation: 1468

sys.argv[1] is the argument provided to the program while running it, which is the image filename in this case.

So you run the program as, python myprogram.py path/to/image/filename.jpg. So argv[1] will be path/to/image/filename.jpg

Upvotes: 1

Related Questions