0

I am trying to follow this tutorial: land cover fastai And while executing the workflow, I got this error:

enter image description here

This is the code where the error occurs:

def png_gen(patch, inference=False):
    """Save RGB, spectral info and labeled images for the coming deep learning

    Args:
        patch: Saved eopatches for deep learning LULC training and prediction 
    Return:
        None: images in the PNG.
    """

    patch_data = EOPatch.load(patch)
    patch_dir, patch_id = patch.split("/")
    if inference == True:
        inds_path = "inds_inference"

        if not op.isdir(inds_path):
            makedirs(inds_path)
        for i in range(len(bands)):
            #get NDVI, NDWI and NDBI from the bands
            inds = color_scale(bands[i][..., [-3, -2, -1]]).astype("uint8")
            Image.fromarray(inds).save(op.join(inds_path, patch+'_'+str(i)+'.png'))

    else:
        lulc = patch_data.mask_timeless['LULC']
        lulc_path = "lulc_all"
        rgb_path = "rgb_all"
        inds_path = "inds_all"
        if not op.isdir(lulc_path):
            makedirs(lulc_path)
        if not op.isdir(rgb_path):
            makedirs(rgb_path)
        if not op.isdir(inds_path):
            makedirs(inds_path)
        for i in range(len(bands)):
            # Switch R, G, B band index from bands
            rgb = color_scale(bands[i][..., [2, 1, 0]]).astype("uint8")
            inds = color_scale(bands[i][..., [-3, -2, -1]]).astype("uint8")
            Image.fromarray(rgb).save(op.join(rgb_path, "{}_{}.png".format(patch_id, str(i))))
            Image.fromarray(inds).save(op.join(inds_path, "{}_{}.png".format(patch_id, str(i))))
            Image.fromarray(lulc).save(op.join(lulc_path, "{}_{}.png".format(patch_id, str(i))))

And this is the execution code:

#download eopatch for the desired AOI and covert the numpy array into RGB, spectral info (NDVI, NDWI, NDBI) 
# and training lulc label into PNG and saved them under "rgb_all", "inds_all" and "lulc_all"
pbar = tqdm(total=len(patchIDs))
for idx, bbox in enumerate(tile_list[patchIDs]):
    # define additional parameters of the workflow
    extra_param = {
        add_data: {'bbox': bbox, 'time_interval': time_interval},
        save_s2: {'eopatch_folder': 'eopatch_{}'.format(idx)}
    }

    workflow.execute(extra_param)
    print("eopatch {} has been processed!".format(idx))
    # png_gen('eopatch_{}'.format(idx))
    png_gen(op.join(path_out_sampled, 'eopatch_{}'.format(idx)), inference=False)
    print("Saving RGB, LULC and Inds PNG to eopatch_{} for the coming ML pipeline".format(idx))
    # del 'eopatch_{}'.format(idx)
    shutil.rmtree(op.join(path_out_sampled, 'eopatch_{}'.format(idx)), ignore_errors=True)
    print("eopatch_{} deleted!".format(idx))
    pbar.update(1)

Instead of '/' I tried '_' in this line patch_dir, patch_id = patch.split("/") because the downloaded patches have this format "eopatch_idx", but I got the same error.

This where the downloaded data are stored:

path_out_sampled = './eopatches_sampled_Slovenia/'
if not op.isdir(path_out_sampled):
    makedirs(path_out_sampled)
save_s2 = SaveToDisk(path_out_sampled, overwrite_permission=OverwritePermission.OVERWRITE_PATCH)
1

The problem seems to be that the split() functions returns more value than the variables used on the left side of the = operator. I quickly tried the following code snippet:

s = "./eopatches_sampled_Slovenia/"
s.split("/")
['.', 'eopatches_sampled_Slovenia', '']
a,b = s.split("/")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
a,b = s.split("_")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

In both cases the split() returns 3 element and, if only 2 variables are used (a, b in my example), the ValueError is raised by Python. Depending on what you need to achieve, the solution is either to use a third variable and then discard it (e.g., _var_to_discard) or to use another function like shown hereafter:

s.strip("./")
'eopatches_sampled_Slovenia'
2
  • thanks for the response. I did try the Extended Iterable Unpacking method by adding " *others" on the left side of the equation, but since I got other errors subsequently to that one. I didn't post it as a solution until I make sure that these errors are not related to adding the third element. – Rim Sleimi May 20 '20 at 6:14
  • I concur that the error occurs at patch_dir, patch_id = patch.split("/"), because it is expecting 2 values from the split. You could try using os.path.basename and similar functions to extract the directory and filename. – smiller May 21 '20 at 19:34
1

Python functions can return multiple variables . These variables can be stored in variables directly. This is a unique property of Python , other programming languages such as C++ or Java do not support this by default.

The valueerror: too many values to unpack occurs during a multiple-assignment where you either don't have enough objects to assign to the variables or you have more objects to assign than variables. If for example myfunction() returned an iterable with three items instead of the expected two then you would have more objects than variables necessary to assign to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.