UnboundLocalError:分配前引用了本地变量“压缩”:生成器错误

时间:2019-05-24 07:57:28

标签: python multithreading keras multiprocessing generator

我正在尝试在keras中建立语义分割模型。由于我使用了自定义数据,因此我决定编写一个自定义生成器,以将其提供给keras函数_.fit_generator,在解决生成器错误

时,我走到了死胡同。
UnboundLocalError: local variable 'zipped' referenced before assignment

经过github和stackover的研究,我发现“ https://github.com/keras-team/keras/issues/1638#issuecomment-182139908” ans与我的问题相似,即使此解决方案似乎也无法再次抛出相同的错误

def image_segmentation_generator( PROC_DATA, target_size, 
batch_size , gen, do_augment=False):
    if gen=='train':
        images_path = PROC_DATA+'/train_images/images'
        segs_path = PROC_DATA+'/train_labels/labels'
    elif 'val':
        images_path = PROC_DATA+'/val_images/images'
        segs_path = PROC_DATA+'/val_labels/labels'

    img_seg_pairs = get_pairs_from_paths( images_path , segs_path)
    random.shuffle( img_seg_pairs )
    zipped = itertools.cycle( img_seg_pairs  )
    while True:

        X = []
        Y = []
        for _ in range( batch_size) :
            im , seg = next(zipped)
            im = cv2.imread(im , 1 )
            im = cv2.resize(im,(target_size[0],target_size[1]))
            seg = cv2.imread(seg , 0 )
            seg = ia.imresize_single_image(seg, (target_size), 
interpolation='nearest')
            if do_augment:
                img , seg[:,:,0] = augment_seg( img , seg[:,:,0] )
            X.append( get_image_arr(im )  )
            Y.append( get_segmentation_arr( seg )  )

        yield np.array(X) , np.array(Y) 

my_gen = image_segmentation_generator(...)

my_gen.next()应该给我给定批处理大小的图像和标签帧。

堆栈跟踪: im,seg = next(zipped) UnboundLocalError:分配前已引用本地变量“压缩”

我该如何解决?

1 个答案:

答案 0 :(得分:0)

以供将来参考。 我已经找到解决方法。看起来像函数对象在作为生成器创建时应该是可自我维持的,不依赖于额外的参数。因此,带有地址的迭代器对象应随函数传递。

压缩=调用image_segmentation_generator_1之前创建的对象

def image_segmentation_generator_1(已压缩=已压缩,target_size =(1242,378),batch_size = 4,do_augment = False):     而True:

    image_list = []
    label_list = []
    _image_list = []
    _label_list = []
    for _ in range((batch_size/2)) :
        im , seg = next(zipped)
        im = cv2.imread(im , 1 )
        im = cv2.resize(im,(target_size[0],target_size[1]))
        seg = cv2.imread(seg , 0 )
        seg = ia.imresize_single_image(seg, (target_size[0],target_size[1]), interpolation='nearest')
        if do_augment:
            _image_list , _label_list = augment_seg( im , seg)
        else :
            _image_list = im
            _label_list = seg
        _image_list = get_image_arr(_image_list)
        image_list = image_list + _image_list
        label_list = label_list + _label_list

    yield np.array(image_list) , np.array(label_list)