"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

October 09, 2019

Day #281 - Yolo based Object Counting and Duplicate Removal

Today's learning is Yolo based object counting, duplicate removal using intersection over union metric.

import cv2
import sys
import os
#Windows 10 Setup
from darkflow.net.build import TFNet
sys.path.append(r"E:\Code_Repo\darkflow\darkflow")
options = {
'model': 'E:\\Code_Repo\\darkflow\\cfg\\yolo.cfg',
'load': 'E:\\Code_Repo\\darkflow\\yolov2.weights',
'threshold': 0.14,
'gpu': 1.0
}
tfnet = TFNet(options)
#https://github.com/tejaslodaya/car-detection-yolo/blob/master/app_utils.py
def iou(box1, box2):
"""Implement the intersection over union (IoU) between box1 and box2
Arguments:
box1 -- first box, list object with coordinates (x1, y1, x2, y2)
box2 -- second box, list object with coordinates (x1, y1, x2, y2)
"""
# Calculate the (y1, x1, y2, x2) coordinates of the intersection of box1 and box2. Calculate its Area.
xi1 = max(box1[0], box2[0])
yi1 = max(box1[1], box2[1])
xi2 = min(box1[2], box2[2])
yi2 = min(box1[3], box2[3])
inter_area = (yi2 - yi1) * (xi2 - xi1)
# Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
union_area = box1_area + box2_area - inter_area
# compute the IoU
iou = inter_area / union_area
return iou
def Object_Count_Yolo(imagefilepath):
coordinates = []
boxes = []
boxlabels = []
finalboxes = []
finalboxlabels = []
img = cv2.imread(imagefilepath, cv2.IMREAD_COLOR)
result = tfnet.return_predict(img)
for data in result:
coordinates = [data['topleft']['x'], data['topleft']['y'],data['bottomright']['x'], data['bottomright']['y']]
boxes.append(coordinates)
boxlabels.append(data['label'])
for k in range(0,len(boxes)):
selectflag = 0
for m in range(k+1,len(boxes)):
iouvalue = iou(boxes[k],boxes[m])
if iouvalue > .7:
selectflag = 1
if(selectflag==0):
finalboxes.append(boxes[k])
finalboxlabels.append(boxlabels[k])
return len(finalboxes)
def diffObjectCount(SourceImagepath, DestinationImagePath):
#Compute and Find Difference in Count
#Return %% based on Count Difference
SourceObjectCount = Object_Count_Yolo(SourceImagepath)
DestinationObjectCount = Object_Count_Yolo(DestinationImagePath)
print(SourceObjectCount)
print(DestinationObjectCount)
Happy Learning!!!

No comments: