matterport / Mask_RCNN

Mask R-CNN for object detection and instance segmentation on Keras and TensorFlow
Other
24.57k stars 11.69k forks source link

IndexError: boolean index did not match indexed array along dimension 0; dimension is 0 but corresponding boolean dimension is 1 #2059

Open DreamMemory001 opened 4 years ago

DreamMemory001 commented 4 years ago

i meet this problem, Who solve it? Please help me. thanks U

DreamMemory001 commented 4 years ago

i have solve this problem, load_mask() has a problem, below code should change , it should own labels, hope can help you. for i in range(len(labels)): if labels[i].find("one") != -1: print("one") labels_form.append("one")

txdywmwddhxs commented 4 years ago

I met this problem too and I tried to fix it with ur method, but the problem still exist .

marcfielding1 commented 4 years ago

Err as I remember it means when you're loading your labels it doesn't have the required data, have you checked the JSON(or whatever) you're importing?

jayhou07 commented 4 years ago

thanks dude, i met the same problew and solved it use your method. it turned i missed one label.

gfaizld commented 3 years ago

i have solve this problem, load_mask() has a problem, below code should change , it should own labels, hope can help you. for i in range(len(labels)): if labels[i].find("one") != -1: print("one") labels_form.append("one")

thanks! Your method solved my problem

MajidNikoogoftar commented 2 years ago

@DreamMemory001

Hello. I used your code but it dosen't solve the error

My code:

class CustomDataset(utils.Dataset):

    def load_custom(self, dataset_dir, subset):
        """Load a subset of the custom dataset.
        dataset_dir: Root directory of the dataset.
        subset: Subset to load: train or val
        """
        # Add classes according to the numbe of classes required to detect
        self.add_class("custom", 0, "mound")
        # self.add_class("custom", 1, "tree")
        self.add_class("custom", 2, "water")
        self.add_class("custom", 3, "debris")

        # Train or validation dataset?
        assert subset in ["train", "val"]
        dataset_dir = os.path.join(dataset_dir, subset)

        # Load annotations
        # VGG Image Annotator (up to version 1.6) saves each image in the form:
        # { 'filename': '28503151_5b5b7ec140_b.jpg',
        #   'regions': {
        #       '0': {
        #           'region_attributes': {},
        #           'shape_attributes': {
        #               'all_points_x': [...],
        #               'all_points_y': [...],
        #               'name': 'polygon'}},
        #       ... more regions ...
        #   },
        #   'size': 100202
        # }
        # We mostly care about the x and y coordinates of each region
        # Note: In VIA 2.0, regions was changed from a dict to a list.
        annotations = json.load(open(os.path.join(dataset_dir, "via_region_data.json")))
        annotations = list(annotations.values()) # don't need the dict keys

        # The VIA tool saves images in the JSON even if they don't have any
        # annotations. Skip unannotated images.
        annotations = [a for a in annotations if a['regions']]

        # Add images
        for a in annotations:
            # Get the x, y coordinaets of points of the polygons that make up
            # the outline of each object instance. These are stores in the
            # shape_attributes (see json format above)
            # The if condition is needed to support VIA versions 1.x and 2.x.
            polygons = [r['shape_attributes'] for r in a['regions']]
            #labelling each class in the given image to a number

            custom = [s['region_attributes'] for s in a['regions']]

            num_ids=[]
            #Add the classes according to the requirement
            for n in custom:
                try:
                    if n['name']=="mound":
                        num_ids.append(0)
                    # elif n['name']=='tree':
                    #     num_ids.append(1)
                    elif n['name']=="water":
                        num_ids.append(2)
                    elif n['name']=="debris":
                        num_ids.append(3)
                except:
                    pass

            # load_mask() needs the image size to convert polygons to masks.
            # Unfortunately, VIA doesn't include it in JSON, so we must read
            # the image. This is only managable since the dataset is tiny.
            image_path = os.path.join(dataset_dir, a['filename'])
            image = skimage.io.imread(image_path)
            height, width = image.shape[:2]

            self.add_image(
                "custom",
                image_id=a['filename'],  # use file name as a unique image id
                path=image_path,
                width=width, height=height,
                polygons=polygons,
                num_ids=num_ids)

    def load_mask(self, image_id):
        """Generate instance masks for an image.
       Returns:
        masks: A bool array of shape [height, width, instance count] with
            one mask per instance.
        class_ids: a 1D array of class IDs of the instance masks.
        """
        # If not a custom dataset image, delegate to parent class.
        image_info = self.image_info[image_id]
        if image_info["source"] != "custom":
            return super(self.__class__, self).load_mask(image_id)
        num_ids = image_info['num_ids'] 
        #print("Here is the nmID",num_ids)

        # Convert polygons to a bitmap mask of shape
        # [height, width, instance_count]
        info = self.image_info[image_id]
        mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
                        dtype=np.uint8)
        for i, p in enumerate(info["polygons"]):
            if p['name'] == 'polygon':
            # Get indexes of pixels inside the polygon and set them to 1
                rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
            else:
                rr, cc = skimage.draw.rectangle((p['y'], p['x']), extent=(p['height'], p['width']))

            rr[rr > mask.shape[0]-1] = mask.shape[0]-1
            cc[cc > mask.shape[1]-1] = mask.shape[1]-1

            mask[rr, cc, i] = 1

        # Return mask, and array of class IDs of each instance. Since we have
        # one class ID only, we return an array of 1s
        num_ids = np.array(num_ids, dtype=np.int32) 
        return mask.astype(np.bool), num_ids#.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32),
        #return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)  # --> works but only detect 1 class
Pollo2048 commented 6 months ago

i have solve this problem, load_mask() has a problem, below code should change , it should own labels, hope can help you. for i in range(len(labels)): if labels[i].find("one") != -1: print("one") labels_form.append("one")

thank you! i met the same problew and solved it use your method.I didn't modify the labelname. thank you again