Search code examples
pythontuplespool

“Too many values to unpack”


I have a function to preprocess images in batches to forward to caffe as input, it is something like below and returns two variables.

 def processImageCrop(im_info, transformer, flowtransformer): 
      .....

      return processed_image, processed_flowimage

      class ImageProcessorCrop(object):
      def __init__(self, transformer, flowtransformer): 
        self.transformer = transformer
        self.flowtransformer = flowtransformer
        #self.flow = flow
      def __call__(self, im_info):
        return processImageCrop(im_info, self.transformer, self.flowtransformer) #, self.flow)

I call this function with pool.map sending im_info parameters, and want to assign the two variables returned as below, but I get the exception Too many values to unpack. Both variables should have length 192. How can I assign the returned values? Thx. I don't want to iterate over each element, but return the two values and assign them to two variables.

result['data'] , result['flowdata'] = pool.map(image_processor, im_info)


Solution

  • Your pool.map call is going to return a list with the results of calling your callable class once per value in im_info. If im_info has more than two value, your assignment that unpacks the list into two variables will not work.

    If you actually want to be unpacking the two-tuples within the list, you probably want to use zip to transpose the data:

    result['data'], result['flowdata'] = zip(*pool.map(image_processor, im_info))