<jupyter_start><jupyter_text>``` This is formatted as code```Testing model deteksi chihuahua<jupyter_code>import warnings
warnings.filterwarnings('ignore')
# !pip install tensorflow-gpu==2.0.0
# %tensorflow_version 2.0.0
# !pip install keras==2.3.1
import os
import sys
import json
import datetime
import numpy as np
import skimage.draw
from google.colab import drive
drive.mount('/content/drive')
# Root directory dari project
ROOT_DIR = os.path.abspath("/content/drive/MyDrive/Deep Learning/Tugas Kelompok DL/Tugas Implementasi Mask RCNN/Colab/Mask_RCNN-master")
print(ROOT_DIR)
# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, utils

# Directory to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
class ChihuahuaConfig(Config):
    """Configuration for training on the balloon dataset.
    Derives from the base Config class and overrides some values.
    """
    # Give the configuration a recognizable name
    NAME = "chihuahua"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Number of classes (including background)
    NUM_CLASSES = 1 + 1  # Background + balloon

    # Number of training steps per epoch
    STEPS_PER_EPOCH = 100

    # Skip detections with < 90% confidence
    DETECTION_MIN_CONFIDENCE = 0.9
class CihuahuaDataset(utils.Dataset):
  def image_reference(self, image_id):
        """Return the path of the image."""
        info = self.image_info[image_id]
        if info["source"] == "cihuahua":
            return info["path"]
        else:
            super(self.__class__, self).image_reference(image_id)
def color_splash(image, mask):
    """Apply color splash effect.
    image: RGB image [height, width, 3]
    mask: instance segmentation mask [height, width, instance count]

    Returns result image.
    """
    # Make a grayscale copy of the image. The grayscale copy still
    # has 3 RGB channels, though.
    gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
    # Copy color pixels from the original color image where mask is set
    if mask.shape[-1] > 0:
        # We're treating all instances as one, so collapse the mask into one layer
        mask = (np.sum(mask, -1, keepdims=True) >= 1)
        splash = np.where(mask, image, gray).astype(np.uint8)
    else:
        splash = gray.astype(np.uint8)
    return splash


def detect_and_color_splash(model, image_path=None, video_path=None):
    assert image_path or video_path

    # Image or video?
    if image_path:
        # Run model detection and generate the color splash effect
        print("Running on {}".format(image_path))
        # Read image
        image = skimage.io.imread(image_path)
        # Detect objects
        r = model.detect([image], verbose=1)[0]
        # Color splash
        splash = color_splash(image, r['masks'])
        # Save output
        file_name = ROOT_DIR + "/splash_{:%Y%m%dT%H%M%S}.png".format(datetime.datetime.now())
        skimage.io.imsave(file_name, splash)
    elif video_path:
        import cv2
        # Video capture
        vcapture = cv2.VideoCapture(video_path)
        width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = vcapture.get(cv2.CAP_PROP_FPS)

        # Define codec and create video writer
        file_name = "splash_{:%Y%m%dT%H%M%S}.avi".format(datetime.datetime.now())
        vwriter = cv2.VideoWriter(file_name,
                                  cv2.VideoWriter_fourcc(*'MJPG'),
                                  fps, (width, height))

        count = 0
        success = True
        while success:
            print("frame: ", count)
            # Read next image
            success, image = vcapture.read()
            if success:
                # OpenCV returns images as BGR, convert to RGB
                image = image[..., ::-1]
                # Detect objects
                r = model.detect([image], verbose=0)[0]
                # Color splash
                splash = color_splash(image, r['masks'])
                # RGB -> BGR to save image to video
                splash = splash[..., ::-1]
                # Add image to video writer
                vwriter.write(splash)
                count += 1
        vwriter.release()
    print("Saved to ", file_name)
#Path Image baloon yang mau di splash
images_path = ROOT_DIR + '/datasets/chihuahua-test.jpg'

#Path Weight baloon, menggunakan weights yang sudah di training
weights_path = ROOT_DIR + '/logs/chihuahua20210518T0511/mask_rcnn_chihuahua_0030.h5'
# weights_path = ROOT_DIR + '/mask_rcnn_balloon.h5'


logs = DEFAULT_LOGS_DIR

class InferenceConfig(ChihuahuaConfig):
    # 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()

model = modellib.MaskRCNN(mode="inference", config=config,
                                  model_dir=logs)



# Load weights
print("Loading weights ", weights_path)
model.load_weights(weights_path, by_name=True)

#Splash images
detect_and_color_splash(model, image_path=images_path,)
# detect_and_color_splash(model, image_path=images_path,
#                                 video_path=video)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09514316781442551, 'fraction_numerical': 0.012685755708590069, 'mean_word_length': 2.7164983164983165, 'pattern_counts': {'":': 1, '<': 6, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '115890', 'license': 'MIT', 'n_tokens_mistral': 1780, 'n_tokens_neox': 1680, 'n_words': 478, 'path': 'samples/chihuahua/test-chihuaha.ipynb', 'repo_name': 'tomytw/Mask-RCNN-TF2.0', 'size': '5518'}