<jupyter_start><jupyter_text>1. Set Up<jupyter_code>%%time
import sagemaker
from sagemaker import get_execution_role

role = get_execution_role()
print(role)
sess = sagemaker.Session()


import os
import urllib.request<jupyter_output>arn:aws:iam::743025358310:role/service-role/AmazonSageMaker-ExecutionRole-20210528T211254
CPU times: user 793 ms, sys: 101 ms, total: 894 ms
Wall time: 849 ms<jupyter_text>2. Defining Our Endpoints<jupyter_code>endpoint_name = 'object-detection-2021-06-25-13-00-24-424'<jupyter_output><empty_output><jupyter_text>3. Defining Our Predictor<jupyter_code>object_detector = sagemaker.predictor.Predictor(endpoint_name = endpoint_name,sagemaker_session = sess)
print(object_detector)<jupyter_output><sagemaker.predictor.Predictor object at 0x7f170c642ac8><jupyter_text>4. Defining Detection Vizualizer<jupyter_code># This is a function that helps in visualizing the detections and draws the corresponding bounding boxes

def visualize_detection(img_file, dets, classes=[], thresh=0.6):
    """
    visualize detections in one image
    Parameters:
    ----------
    img : numpy.array
        image, in bgr format
    dets : numpy.array
        ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...])
        each row is one object
    classes : tuple or list of str
        class names
    thresh : float
        score threshold
    """
    import random
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg

    img = mpimg.imread(img_file)
    plt.imshow(img)
    height = img.shape[0]
    width = img.shape[1]
    colors = dict()
    for det in dets:
        (klass, score, x0, y0, x1, y1) = det
        if score < thresh:
            continue
        cls_id = int(klass)
        if cls_id not in colors:
            colors[cls_id] = (random.random(), random.random(), random.random())
        xmin = int(x0 * width)
        ymin = int(y0 * height)
        xmax = int(x1 * width)
        ymax = int(y1 * height)
        rect = plt.Rectangle(
            (xmin, ymin),
            xmax - xmin,
            ymax - ymin,
            fill=False,
            edgecolor=colors[cls_id],
            linewidth=3.5,
        )
        plt.gca().add_patch(rect)
        class_name = str(cls_id)
        if classes and len(classes) > cls_id:
            class_name = classes[cls_id]
        plt.gca().text(
            xmin,
            ymin - 2,
            "{:s} {:.3f}".format(class_name, score),
            bbox=dict(facecolor=colors[cls_id], alpha=0.5),
            fontsize=12,
            color="white",
        )
    plt.show()<jupyter_output><empty_output><jupyter_text>5. Defining our classes and threshold<jupyter_code>object_categories = [
    'Good_Day_Butter',
    'Good_Day_Pista',
    'Patanjali_Aloevera',
    'Patanjali_Haldi_Chandan',
    'Patanjali_Neem'
]


# Setting a threshold 0.20 will only plot detection results that have a confidence score greater than 0.20.
threshold = 0.20<jupyter_output><empty_output><jupyter_text>6. Predicting With One image<jupyter_code>import json

#image name
file_name = './Test_Images/IMG_20210621_212926_DRO.jpg'

with open(file_name, 'rb') as image:
    f = image.read()
    b = bytearray(f)
    ne = open('n.txt','wb')
    ne.write(b)
results = object_detector.predict(b, initial_args={'ContentType': 'image/jpeg'})
detections = json.loads(results)
# print (detections)


# Visualize the detections.
visualize_detection(file_name, detections["prediction"], object_categories, threshold)<jupyter_output><empty_output><jupyter_text>7. Predicting a whole directory<jupyter_code>import json
import glob
threshold = 0.10
imdir = 'Test_Images/'
ext = ['jpg',]    # Add image formats here

files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
newfiles = files[:15]
for file_name in newfiles:
    with open(file_name,'rb') as image:
        f = image.read()
        b = bytearray(f)
        ne = open('n.txt','wb')
        ne.write(b)
    results = object_detector.predict(b, initial_args={'ContentType': 'image/jpeg'})
    detections = json.loads(results)
    visualize_detection(file_name, detections["prediction"], object_categories, threshold)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11620138391791936, 'fraction_numerical': 0.02934860415175376, 'mean_word_length': 3.242914979757085, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '345433', 'license': 'MIT', 'n_tokens_mistral': 1523, 'n_tokens_neox': 1437, 'n_words': 316, 'path': '2-Prediction/1-prediction.ipynb', 'repo_name': 'Vikram-Singh-Yadav/AWS-SageMaker-Object-Detection', 'size': '4191'}