ultralytics/yolov5

scale_masks fucntion

polinamalova0 opened this issue · 1 comments

Search before asking

Question

Dear Ultralytics!
I faced the problem when i wsa trying to resize the masks I got after the inference. In the documentation you have the function that does it:

def scale_masks(masks, shape, padding=True):
    """
    Rescale segment masks to shape.

    Args:
        masks (torch.Tensor): (N, C, H, W).
        shape (tuple): Height and width.
        padding (bool): If True, assuming the boxes is based on image augmented by yolo style. If False then do regular
            rescaling.
    """
    # print('masks.shape[0:2]: ',masks.shape[0:2])
    mh, mw = masks.shape[2:]
    gain = min(mh / shape[0], mw / shape[1])  # gain  = old / new
    pad = [mw - shape[1] * gain, mh - shape[0] * gain]  # wh padding
    if padding:
        pad[0] /= 2
        pad[1] /= 2
    top, left = (int(pad[1]), int(pad[0])) if padding else (0, 0)  # y, x
    bottom, right = (int(mh - pad[1]), int(mw - pad[0]))
    masks = masks[..., top:bottom, left:right]

    masks = F.interpolate(masks, shape, mode="bilinear", align_corners=False)  # NCHW
    return masks

after submitting masks = scale_masks(results[0].masks, (w, h)) command, i received this error

Traceback (most recent call last):
  File "proj.py", line 169, in <module>
    masks = scale_masks(results[0].masks, (w, h))
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "proj.py", line 60, in scale_masks
    mh, mw = masks.shape[2:]
    ^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)

and i do not understand what is wrong since there's not much i could have possibly disrupt in the process (the results variable is calculated as results = model(img))

I would be really grateful for the help!

Additional

No response

Hello! It looks like the error you're encountering is likely due to masks.shape not having the expected dimensions. The scale_masks function expects a four-dimensional tensor (N, C, H, W), but the masks tensor you are passing might be missing some dimensions.

Please ensure that the results[0].masks tensor has the correct shape. You can debug this by adding a print statement just before you call scale_masks to check the shape of your masks tensor:

print(results[0].masks.shape)
masks = scale_masks(results[0].masks, (w, h))

This will let you see if the dimensions are indeed (N, C, H, W). If the dimensions are different, you'll need to adjust them appropriately before passing them to scale_masks.

Hope this helps! 👍