def extract(self, images, target_dir): config = InferenceConfig() dataset = InferenceDataset(images) config.display() dataset.prepare() utils.ensure_dir(target_dir) coco_model_path = 'mask_rcnn_coco.h5' if not os.path.exists(coco_model_path): mrcnn.utils.download_trained_weights(coco_model_path) model = ResNet(mode="inference", config=config, model_dir=target_dir) exclude_layers = [ "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask", ] model.load_weights(coco_model_path, by_name=True, exclude=exclude_layers) executor = ProcessPoolExecutor(max_workers=4) for i, image_info in enumerate(dataset.image_info): image_name = os.path.basename(image_info['path']) print('Processing image {}'.format(image_name)) image = dataset.load_image(i) features = model.detect(image) executor.submit(self.store_features, features[:4], os.path.join(target_dir, image_name)) executor.shutdown(wait=True)
def predecir(self, event): print("Funciono boton") config = estadios.BalloonConfig() config = InferenceConfig() config.display() DATA_DIR = "./Modelo/tfg_notebook/main_1/dataset" BALLOON_DIR = DATA_DIR dataset = estadios.BalloonDataset() with wx.FileDialog(self, "Selecciona una imagen para predecir su clase", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return pathname = fileDialog.GetPath() try: with open(pathname, 'r') as file: print(pathname) dataset.load_balloon(BALLOON_DIR, "val") dataset.prepare() print("Images: {}\nClasses: {}".format( len(dataset.image_ids), dataset.class_names)) config = InferenceConfig() with tf.device(DEVICE): model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) weights_path = model.find_last() print("Loading weights ", weights_path) model.load_weights(weights_path, by_name=True) #image = skimage.io.imread("./Modelo/tfg_notebook/main_1/dataset/val/estadio-25.JPG") image = skimage.io.imread(pathname) plt.figure(figsize=(12, 10)) skimage.io.imshow(image) plt.show() result = model.detect([image], verbose=1) r = result[0] visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], dataset.class_names, r['scores']) except IOError: wx.LogError("No se pudo abrir el archivo")
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5") # Download COCO trained weights from Releases if needed if not os.path.exists(COCO_MODEL_PATH): utils.download_trained_weights(COCO_MODEL_PATH) # Directory of images to run detection on IMAGE_DIR = os.path.join(ROOT_DIR, "images") class InferenceConfig(coco.CocoConfig): # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 config = InferenceConfig() config.display() """## Create Model and Load Trained Weights""" # Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # Load weights trained on MS-COCO model.load_weights(COCO_MODEL_PATH, by_name=True) # COCO Class names # Index of the class in the list is its ID. For example, to get ID of # the teddy bear class, use: class_names.index('teddy bear') class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
def imagedetection(): # Root directory of the project ROOT_DIR = os.path.abspath("../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library import mrcnn.utils import mrcnn.model as modellib from mrcnn import visualize # Import COCO config sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version import coco %matplotlib inline # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT_DIR, "logs") # Local path to trained weights file COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5") # Download COCO trained weights from Releases if needed if not os.path.exists(COCO_MODEL_PATH): utils.download_trained_weights(COCO_MODEL_PATH) # Directory of images to run detection on IMAGE_DIR = os.path.join(ROOT_DIR, "images") class InferenceConfig(coco.CocoConfig): # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 config = InferenceConfig() config.display() # Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # Load weights trained on MS-COCO model.load_weights(COCO_MODEL_PATH, by_name=True) # COCO Class names # Index of the class in the list is its ID. For example, to get ID of # the teddy bear class, use: class_names.index('teddy bear') class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'] # Load a random image from the images folder file_names = next(os.walk(IMAGE_DIR))[2] filename = os.path.join(IMAGE_DIR ,"car.jpg") #image = skimage.io.imread(filename) image = cv2.imread(filename,color) # Run detection results = model.detect([image], verbose=1) # Visualize results r = results[0] overlaps = mrcnn.utils.compute_overlaps(parked_car_boxes, result['rois']) for parking_area, overlap_areas in zip(parked_car_boxes, overlaps): max_IoU_overlap = np.max(overlap_areas) if max_IoU_overlap < 0.85: return 0 visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'])