Skip to content Skip to sidebar Skip to footer

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? f

Solution 1:

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


Solution 2:

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))

Post a Comment for "Finding Average Color Using Python"