Error when testing

#7
by fnando1995 - opened

I am using this code, this part runs ok

import numpy as np
import matplotlib.pyplot as plt
import gc
from transformers import pipeline
from PIL import Image
import requests

def show_mask(mask, ax, random_color=False):
    if random_color:
        color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
    else:
        color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])
    h, w = mask.shape[-2:]
    mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
    ax.imshow(mask_image)
    del mask
    gc.collect()

def show_masks_on_image(raw_image, masks):
  plt.imshow(np.array(raw_image))
  ax = plt.gca()
  ax.set_autoscale_on(False)
  for mask in masks:
      show_mask(mask, ax=ax, random_color=True)
  plt.axis("off")
  plt.show()
  del mask
  gc.collect()

generator = pipeline("mask-generation", model="facebook/sam-vit-base")

img_url = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")

after I try to generate the outputs with:

outputs = generator(raw_image, points_per_batch=64)

and get this error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 outputs = generator(raw_image, points_per_batch=64)

File /mnt/data/workspaces/TESTING/sam-vit-base/ambiente/lib/python3.10/site-packages/transformers/pipelines/mask_generation.py:166, in MaskGenerationPipeline.__call__(self, image, num_workers, batch_size, *args, **kwargs)
    128 def __call__(self, image, *args, num_workers=None, batch_size=None, **kwargs):
    129     """
    130     Generates binary segmentation masks
    131 
   (...)
    164 
    165     """
--> 166     return super().__call__(image, *args, num_workers=num_workers, batch_size=batch_size, **kwargs)

File /mnt/data/workspaces/TESTING/sam-vit-base/ambiente/lib/python3.10/site-packages/transformers/pipelines/base.py:1246, in Pipeline.__call__(self, inputs, num_workers, batch_size, *args, **kwargs)
   1244     return self.iterate(inputs, preprocess_params, forward_params, postprocess_params)
   1245 elif self.framework == "pt" and isinstance(self, ChunkPipeline):
-> 1246     return next(
   1247         iter(
   1248             self.get_iterator(
   1249                 [inputs], num_workers, batch_size, preprocess_params, forward_params, postprocess_params
   1250             )
   1251         )
   1252     )
   1253 else:
   1254     return self.run_single(inputs, preprocess_params, forward_params, postprocess_params)

File /mnt/data/workspaces/TESTING/sam-vit-base/ambiente/lib/python3.10/site-packages/transformers/pipelines/pt_utils.py:125, in PipelineIterator.__next__(self)
    123 # We're out of items within a batch
    124 item = next(self.iterator)
--> 125 processed = self.infer(item, **self.params)
    126 # We now have a batch of "inferred things".
    127 if self.loader_batch_size is not None:
    128     # Try to infer the size of the batch

File /mnt/data/workspaces/TESTING/sam-vit-base/ambiente/lib/python3.10/site-packages/transformers/pipelines/mask_generation.py:271, in MaskGenerationPipeline.postprocess(self, model_outputs, output_rle_mask, output_bboxes_mask, crops_nms_thresh)
    269 all_scores = torch.cat(all_scores)
    270 all_boxes = torch.cat(all_boxes)
--> 271 output_masks, iou_scores, rle_mask, bounding_boxes = self.image_processor.post_process_for_mask_generation(
    272     all_masks, all_scores, all_boxes, crops_nms_thresh
    273 )
    275 extra = defaultdict(list)
    276 for output in model_outputs:

File /mnt/data/workspaces/TESTING/sam-vit-base/ambiente/lib/python3.10/site-packages/transformers/models/sam/image_processing_sam.py:761, in SamImageProcessor.post_process_for_mask_generation(self, all_masks, all_scores, all_boxes, crops_nms_thresh, return_tensors)
    745 """
    746 Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.
    747 
   (...)
    758         If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
    759 """
    760 if return_tensors == "pt":
--> 761     return _postprocess_for_mg(all_masks, all_scores, all_boxes, crops_nms_thresh)
    762 elif return_tensors == "tf":
    763     return _postprocess_for_mg_tf(all_masks, all_scores, all_boxes, crops_nms_thresh)

File /mnt/data/workspaces/TESTING/sam-vit-base/ambiente/lib/python3.10/site-packages/transformers/models/sam/image_processing_sam.py:1456, in _postprocess_for_mg(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh)
   1442 def _postprocess_for_mg(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh=0.7):
   1443     """
   1444     Perform NMS (Non Maximum Suppression) on the outputs.
   1445 
   (...)
   1454                 NMS threshold.
   1455     """
-> 1456     keep_by_nms = batched_nms(
   1457         boxes=mask_boxes.float(),
   1458         scores=iou_scores,
   1459         idxs=torch.zeros(mask_boxes.shape[0]),
   1460         iou_threshold=amg_crops_nms_thresh,
   1461     )
   1463     iou_scores = iou_scores[keep_by_nms]
   1464     rle_masks = [rle_masks[i] for i in keep_by_nms]

NameError: name 'batched_nms' is not defined

Sign up or log in to comment