# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import tensorflow as tf
import cv2 as cv

with tf.gfile.FastGFile('frozen_inference_graph.pb', 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

with tf.Session() as sess:
    # Restore session
    sess.graph.as_default()
    tf.import_graph_def(graph_def, name='')

    img = cv.imread('cow.jpg')
    rows = img.shape[0]
    cols = img.shape[1]
    inp = cv.resize(img, (300, 300))
    inp = inp[:, :, [2, 1, 0]]  

    # Run the model
    out = sess.run([sess.graph.get_tensor_by_name('num_detections:0'),
                    sess.graph.get_tensor_by_name('detection_scores:0'),
                    sess.graph.get_tensor_by_name('detection_boxes:0'),
                    sess.graph.get_tensor_by_name('detection_classes:0')],
                   feed_dict={'image_tensor:0': inp.reshape(1, inp.shape[0], inp.shape[1], 3)})
    
    # coco_dataset class 18 - Dog
    # coco_dataset class 20 - Sheep
    # coco_dataset class 21 - Cow

    # Visualize detected bounding boxes.
    num_detections = int(out[0][0])
    dog_count = 0
    sheep_count = 0
    cow_count = 0
    
    for i in range(num_detections):
        classId = int(out[3][0][i])
        score = float(out[1][0][i])
        bbox = [float(v) for v in out[2][0][i]]
    
        if score > 0.3:
            if (classId == 18):
                dog_count += 1
            if (classId == 20):
                sheep_count += 1
            if (classId == 21):
                cow_count += 1
            x = bbox[1] * cols
            y = bbox[0] * rows
            right = bbox[3] * cols
            bottom = bbox[2] * rows
            cv.rectangle(img, (int(x), int(y)), (int(right), int(bottom)), (0, 0, 0), thickness=2)

if (dog_count != 0):
    label = 'No of dogs ' + str(dog_count)
    cv.putText(img,label, (0,25), cv.FONT_HERSHEY_DUPLEX, 1, (0,255,0))
if (sheep_count != 0):
    label = 'No of sheeps ' + str(sheep_count)
    cv.putText(img, label, (0,25), cv.FONT_HERSHEY_DUPLEX, 1, (0,0,255))
if (cow_count != 0):
    label = 'No of cows ' + str(cow_count)
    cv.putText(img, label, (0,25), cv.FONT_HERSHEY_DUPLEX, 1, (255,255,0))
    
cv.imshow('Image', img)
cv.waitKey()
# -



StarcoderdataJupyterScriptsDedupFiltered