Error with the function random.choice
Question: Using this code:

    
    
    from PIL import Image
    from PIL.ImageChops import subtract
    import numpy
    import math
    import time
    import glob
    import sys
    import os
    import logging
    import random
    
    
    def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None, tolerance=None):
        """
        http://gc-films.com/chromakey.html
        http://www.cs.utah.edu/~michael/chroma/
        :param infile:      Greenscreen image location
        :param inbg:        Background image location
        :param outfile:     Output file location
        :param keyColor:    greenscreen color; it can be any singular color
        :param tolerance:   tolerance of cleaning
        :return:
        """
    
        if not keyColor:
            keyColor = [151,44,21] #Y,Cb, and Cr values of the greenscreen
    
        if not tolerance:
            tolerance = [100,130] #Allowed Distance from Values
    
        #open files
        inDataFG = Image.open('/home/leonardo/Scrivania/KVfnt.jpg').convert('YCbCr')
        BG = random.choice(os.listdir('/home/leonardo/Scrivania/background')).convert('RGB')
        [Y_key, Cb_key, Cr_key] = keyColor
        [tola, tolb]= tolerance
    
        (x,y) = inDataFG.size #get dimensions
        foreground = numpy.array(inDataFG.getdata()) #make array from image
        maskgen = numpy.vectorize(colorclose) #vectorize masking function
    
    
        alphaMask = maskgen(foreground[:,1],foreground[:,2] ,Cb_key, Cr_key, tola, tolb) #generate mask
        alphaMask.shape = (y,x) #make mask dimensions of original image
        imMask = Image.fromarray(numpy.uint8(alphaMask))#convert array to image
        invertMask = Image.fromarray(numpy.uint8(255-255*(alphaMask/255))) #create inverted mask with extremes
    
        #create images for color mask
        colorMask = Image.new('RGB',(x,y),tuple([0,0,0]))
        allgreen = Image.new('YCbCr',(x,y),tuple(keyColor))
    
        colorMask.paste(allgreen,invertMask) #make color mask green in green values on image
        inDataFG = inDataFG.convert('RGB') #convert input image to RGB for ease of working with
        cleaned = subtract(inDataFG,colorMask) #subtract greens from input
        BG.paste(cleaned,imMask)#paste masked foreground over background
    
        # BG.show() #display cleaned image
        BG.save(outfile, "JPEG") #save cleaned image
    
    def colorclose(Cb_p,Cr_p, Cb_key, Cr_key, tola, tolb):
        temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2)
        if temp < tola:
            z = 0.0
        elif temp < tolb:
            z = ((temp-tola)/(tolb-tola))
        else:
            z = 1.0
        return 255.0*z
    
    def check_folders(logger):
        if not os.path.exists('out/'):
            os.mkdir('out/')
        if not os.path.exists('background/'):
            os.mkdir('background/')
            logger.error("Place background images in background/")
            sys.exit()
        if not os.path.exists('in/'):
            os.mkdir('in/')
            logger.error("Place input files in in/")
            sys.exit()
    
    def begin_greenbox(logger):
        """
        For all backgrounds loop through all input files into the out file
        """
        for bg in glob.glob('background/*'):
            if not('.jpg' or '.png' in bg.lower()):
                continue
            bg_name = bg.split('/')[-1].lower().strip('.jpg').strip('.png').strip('.jpeg')
            for picture in glob.glob('in/*'):
                if not('.jpg' or '.png' in picture.lower()):
                    continue
                pic_name = picture.split('/')[-1].lower().strip('.JPG').strip('.png').strip('.jpeg')
                output_file = 'out/' + bg_name + ' ' + pic_name + '.jpg'
    
                one_pic = time.time()
                GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
                one_pic_time_done = time.time()
    
                time_arr.append(one_pic_time_done-one_pic)
                logger.info(time_arr)
                logger.info('done : %s' % pic_name)
    
    def start_logging():
        logging.basicConfig()
        logger = logging.getLogger('greenbox')
        logger.setLevel(logging.INFO)
        return logger
    
    if __name__ == '__main__':
        time_start = time.time()
        time_arr = []
        logger = start_logging()
        logger.info("Start time: %s" % time_start)
        check_folders(logger)    
        begin_greenbox(logger)
        time_end = time.time()
        logger.info("End time: %s" % time_end)
    

I obtain this error:

    
    
    INFO:greenbox:Start time: 1452730719.31
    Traceback (most recent call last):
      File "chromakeyy.py", line 115, in <module>
        begin_greenbox(logger)
      File "chromakeyy.py", line 96, in begin_greenbox
        GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
      File "chromakeyy.py", line 33, in GreenScreen
        BG = Image.open(random.choice(os.listdir('/home/leonardo/Scrivania/background'))).convert('RGB')
      File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2288, in open
        fp = builtins.open(fp, "rb")
    IOError: [Errno 2] No such file or directory: 'bai19-266x400.jpg'
    

Before using the command random.choice in line 33, everything was ok. What is
the problem? Why is it giving me this error? Is there another method to open a
random image from a specific folder? Thank you.


Answer: The error states that the file you are trying to open does not exist. This is
most likely because os.listdir(path) returns only the file names in 'path',
and not the full directory and filename.

In your case, it did select a random file named 'bai19-266x400.jpg', which you
then tried to open. When you should be opening
'/home/leonardo/Scrivania/background/bai19-266x400.jpg'. Something more like
this should work:

    
    
    Path = '/home/leonardo/Scrivania/background'
    FullPath = os.path.join(Path, random.choice(os.listdir(Path)))
    BG = Image.open(FullPath).convert('RGB')
    

