experiencor / keras-yolo2

Easy training on custom dataset. Various backends (MobileNet and SqueezeNet) supported. A YOLO demo to detect raccoon run entirely in brower is accessible at https://git.io/vF7vI (not on Windows).
MIT License
1.73k stars 787 forks source link

iou calculation #426

Open vcvishal opened 5 years ago

vcvishal commented 5 years ago

thank you for your good code. how to calculate iou ? please guide me

krzysztofpal commented 4 years ago

Hi there!

IOU is intersection over union, so first question is how to calculate intersection?

Let's presume, that you have two boxes of coordinates [x1, y1, x2, y2] and [x'1, y'1, x'2, y'2]. Intersection is a field where two of those intersect themself. It means that intersection is a figure within both first and second rectangle.

Two of it's corners belong first rectangle and last two to the second rectangle. Now which one where? The ones that will make "smallest" intersection.

Let's call intersection parameters [ix1, iy1, ix2, iy2]

ix1 is equal to x1 if x1 is bigger than x'1. Otherwise it is equal to x'1. Why? Because intersection is a field inside two other fields, so both rectangles must exist in the same coordinates of Cartessian system.

iy1 is equal to max from [y1, y'1] because of the same logic.

Now what about ix2? Intersection "ends", when at least one figure "ended". So, it means that ix2 is THE SMALLEST among x2 and x'2. Same with iy2 which is the smallest among y2 and y'2.

So, now we have [ix1, iy1, ix2, iy2]. Calculating intersection field is easy now. intersection = (ix2 - ix1) * (iy2 - iy1)

Now it is time to calculate union. Union is area created by both figures. If we would add rectangle 1 and rectangle 2 we would have union with intersection, because intersection overlaps. So you need to remove intersection to have union.

union = (x2 - x1) (y2 - y1) + (x'2 - x'1) (y'2 - y'1) - intersection

Now iou = intersection / union

Hope it helps!