{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nos.listdir('/kaggle/input')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nimg='/kaggle/input/open-images-2019-object-detection/test/c2ac80e2bd0723de.jpg'\nimg=image.load_img(img,target_size=(224,224,3))\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef get_image_file_path(image_file_name):\n    return '../input/test/' + image_file_name\n\ndef get_images(n):\n\n    all_image_files = os.listdir(\"/kaggle/input/open-images-2019-object-detection/test\")\n    image_paths = list(map(get_image_file_path, all_image_files))\n    image_paths = image_paths[:n]\n    return image_paths\n\ndef get_image_id_from_path(image_path):\n    return image_path.split('../input/test/')[1].split('.jpg')[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(get_images(10))\nprint(get_image_id_from_path(get_images(1)[0]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef get_prediction_string(result):\n    with tf.device('/device:GPU:0'):\n       \n        prediction_strings = []\n        for index, score in enumerate(result['detection_scores']):\n            index = int(index)\n            single_prediction_string = \"\"\n            single_prediction_string += result['detection_class_names'][index].decode(\"utf-8\") + \" \"  + str(score) + \" \"\n            single_prediction_string += \" \".join(str(x) for x in result['detection_boxes'][index])\n            prediction_strings.append(single_prediction_string)\n\n        prediction_string = \" \".join(str(x) for x in prediction_strings)\n        return prediction_string\n\ndef get_prediction_entry(filepath, result):\n    return {\n        \"ImageID\": get_image_id_from_path(filepath),\n        \"PredictionString\": get_prediction_string(result)\n    }","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow.compat.v1 as tf\ntf.disable_v2_behavior() \nimport tensorflow_hub as hub\nimport matplotlib.pyplot as plt\n\n\nfrom six import BytesIO\n\n\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom PIL import ImageColor\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nfrom PIL import ImageOps\n\nimport time\n\n# Check available GPU devices.\nprint(\"The following GPU devices are available: %s\" % tf.test.gpu_device_name())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_image(image):\n    fig = plt.figure(figsize=(20, 15))\n    plt.grid(False)\n    plt.imshow(image)\n\n\ndef draw_bounding_box_on_image(image,\n                               ymin,\n                               xmin,\n                               ymax,\n                               xmax,\n                               color,\n                               font,\n                               thickness=4,\n                               display_str_list=()):\n   \n    draw = ImageDraw.Draw(image)\n    im_width, im_height = image.size\n    (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n                                  ymin * im_height, ymax * im_height)\n    draw.line([(left, top), (left, bottom), (right, bottom), (right, top),\n               (left, top)],\n              width=thickness,\n              fill=color)\n\n    \n    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]\n\n    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)\n\n    if top > total_display_str_height:\n        text_bottom = top\n    else:\n        text_bottom = bottom + total_display_str_height\n    for display_str in display_str_list[::-1]:\n    \n        text_width, text_height = font.getsize(display_str)\n        margin = np.ceil(0.05 * text_height)\n        draw.rectangle([(left, text_bottom - text_height - 2 * margin),\n                        (left + text_width, text_bottom)],\n                       fill=color)\n        draw.text((left + margin, text_bottom - text_height - margin),\n                  display_str,\n                  fill=\"black\",\n                  font=font)\n        text_bottom -= text_height - 2 * margin\n\n\ndef draw_boxes(image, boxes, class_names, scores, max_boxes=10, min_score=0.1):\n \n    colors = list(ImageColor.colormap.values())\n\n    try:\n        font = ImageFont.truetype(\n            \"/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf\",\n            25)\n    except IOError:\n        print(\"Font not found, using default font.\")\n        font = ImageFont.load_default()\n\n    for i in range(min(boxes.shape[0], max_boxes)):\n        if scores[i] >= min_score:\n            ymin, xmin, ymax, xmax = tuple(boxes[i].tolist())\n            #if class_names[i]=='Ambulance':\n            if(class_names[i].decode('ascii')==\"Ambulance\"):\n                display_str = \"{}: {}%\".format(class_names[i].decode(\"ascii\"),\n                                               int(100 * scores[i]))\n                color = colors[hash(class_names[i]) % len(colors)]\n                image_pil = Image.fromarray(np.uint8(image)).convert(\"RGB\")\n            \n                draw_bounding_box_on_image(\n                    image_pil,\n                    ymin,\n                    xmin,\n                    ymax,\n                    xmax,\n                    color,\n                    font,\n                    display_str_list=[display_str])\n                np.copyto(image, np.array(image_pil))\n    return image\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#!pip install Keras==2.3.1 tensorflow==2.1.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"module_handle = \"https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1\"\nimage_path = \"/kaggle/input/ambulance/final2.jpg\"\n\nwith tf.device('/device:GPU:0'):\n    with tf.Graph().as_default():\n        detector = hub.Module(module_handle)\n        image_string_placeholder = tf.placeholder(tf.string)\n        decoded_image = tf.image.decode_jpeg(image_string_placeholder)\n\n        decoded_image_float = tf.image.convert_image_dtype(\n        image=decoded_image, dtype=tf.float32)\n        module_input = tf.expand_dims(decoded_image_float, 0)\n        result = detector(module_input, as_dict=True)\n        init_ops = [tf.global_variables_initializer(), tf.tables_initializer()]\n\n        session = tf.Session()\n        session.run(init_ops)\n        \n        with tf.gfile.Open(image_path, \"rb\") as binfile:\n            image_string = binfile.read()\n\n        result_out, image_out = session.run(\n            [result, decoded_image],\n            feed_dict={image_string_placeholder: image_string})\n        print(\"Found %d objects.\" % len(result_out[\"detection_scores\"]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" ###see the sample image with bounding boxes\n    #if result_out['detection_class_entities']=='Ambulance':\nimage_with_boxes = draw_boxes(\n            np.array(image_out), result_out[\"detection_boxes\"],\n            result_out[\"detection_class_entities\"], result_out[\"detection_scores\"])\ndisplay_image(image_with_boxes)\n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}