函数random.choice出错

时间:2016-01-14 00:52:18

标签: python-3.x random python-imaging-library

使用此代码:

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)

我收到此错误:

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'

在第33行使用random.choice命令之前,一切正常。问题是什么?为什么它给我这个错误?是否有另一种方法可以从特定文件夹中打开随机图像?谢谢。

2 个答案:

答案 0 :(得分:1)

错误指出您尝试打开的文件不存在。这很可能是因为os.listdir(path)只返回'path'中的文件名,而不是完整的目录和文件名。

在您的情况下,它确实选择了一个名为'bai19-266x400.jpg'的随机文件,然后您尝试打开该文件。当你应该打开'/home/leonardo/Scrivania/background/bai19-266x400.jpg'。更像这样的东西应该有效:

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

答案 1 :(得分:0)

尝试并尝试,我终于解决了多输出图像的问题。原因是cicle for的存在并且现在每次移除它都没问题。谢谢大家。