MASK-RCNN的自定义训练类怎么写?

时间:2021-06-22 06:12:52

标签: deep-learning artificial-intelligence mask image-segmentation

我正在尝试在 MASK-RCNN 上进行培训,我有两个班级, apple 和banana 。我正在从 matterport github repo 做,但遇到很多错误,我已经上传了 Json 文件和我的类,看看它并帮助我,我已经完成了来自 VIA 2.0.8 的注释,它是使用矩形完成的,而不是多边形。

Json 看起来像

{"_via_settings":{"ui":{"annotation_editor_height":25,"annotation_editor_fontsize":0.8, "leftsidebar_width":18,"image_grid{"img_height":80,"rshape_fill":"none","rshape_fill_opacity":0.3,"rshape_stroke":"yellow","rshape_stroke_width":2,"show_region_shape":true," show_image_policy":"all"},"image":{"region_label":"via_region_id","re​​gion_color":"class","re​​gion_label_font":"10px Sans","on_image_annotation_editor_placement":" NEAR_REGION"}},"core":{"buffer_size":18,"filepath":{},"default_filepath":""},"project":{"name":"Train_Annotations_New"}},"_via_img_metadata": {"1Apple.jpg3895":{"filename":"1Apple.jpg","size":3895,"regions":[{"shape_attributes":{"name":"rect","x":80," y":10,"width":154,"height":137},"region_attributes":{"class":{"apple":true}}}],"file_attributes":{}}

我的班级:

class FruitsDataset(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", 1, "apple")
        self.add_class("custom",2,"banana")

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

        annotations = json.load(open(os.path.join(dataset_dir, "via_region_data.json")))
        
        annotations = [annotations['_via_img_metadata'][a] for a in annotations['_via_img_metadata']]

        # print(annotations)
        # Add images
        for ind, a in enumerate(annotations):

            # Get the x, y coordinates 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 annotations[ind]['regions']]
            #labelling each class in the given image to a number

            custom = [s['region_attributes'] for s in annotations[ind]['regions']]

            num_ids=[]
            #Add the classes according to the requirement
            for n in custom:
                try:
                    if n['label']=='apple':
                        num_ids.append(1)
                    elif n['label']=='banana':
                        num_ids.append(2)
                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, annotations[ind]['filename'])
            image = skimage.io.imread(image_path)
            height, width = image.shape[:2]

            self.add_image(
                "custom",
                image_id=annotations[ind]['filename'], 
                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 Horse/Man dataset image, delegate to parent class.
        image_info = self.image_info[image_id]
        if image_info["source"] != "object":
            return super(self.__class__, self).load_mask(image_id)

        # Convert polygons to a bitmap mask of shape
        # [height, width, instance_count]
        info = self.image_info[image_id]
        if info["source"] != "object":
            return super(self.__class__, self).load_mask(image_id)
        num_ids = info['num_ids']
        mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
                        dtype=np.uint8)
        for i, p in enumerate(info["polygons"]):
            # 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'])

            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
        # Map class names to class IDs.
        num_ids = np.array(num_ids, dtype=np.int32)
        return mask, num_ids #np.ones([mask.shape[-1]], dtype=np.int32)

    def image_reference(self, image_id):
        """Return the path of the image."""
        info = self.image_info[image_id]
        if info["source"] == "object":
            return info["path"]
        else:
            super(self.__class__, self).image_reference(image_id)

0 个答案:

没有答案