python實現IOU計算案例
計算兩個矩形的交并比,通常在檢測任務里面可以作為一個檢測指標。你的預測bbox和groundtruth之間的差異,就可以通過IOU來體現。很簡單的算法實現,我也隨便寫了一個,嗯,很簡單。
1. 使用時,請注意bbox四個數字的順序(y0,x0,y1,x1),順序不太一樣。
#!/usr/bin/env python# encoding: utf-8 def compute_iou(rec1, rec2): ''' computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU ''' # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # computing the sum_area sum_area = S_rec1 + S_rec2 # find the each edge of intersect rectangle left_line = max(rec1[1], rec2[1]) right_line = min(rec1[3], rec2[3]) top_line = max(rec1[0], rec2[0]) bottom_line = min(rec1[2], rec2[2]) # judge if there is an intersect if left_line >= right_line or top_line >= bottom_line: return 0 else: intersect = (right_line - left_line) * (bottom_line - top_line) return (intersect / (sum_area - intersect))*1.0 if __name__==’__main__’: rect1 = (661, 27, 679, 47) # (top, left, bottom, right) rect2 = (662, 27, 682, 47) iou = compute_iou(rect1, rect2) print(iou)
補充知識:基于Python實現的IOU算法---最簡單易懂的代碼實現
概念介紹:
交并比:(Intersection over Union)
如上圖所示,IOU值定位為兩個矩形框面積的交集和并集的比值。即:
交并比的實現也是非常簡單的,執行過程如下:
1. 交集形狀的寬度計算為:
IOU_W = min(x1,x2,x3,x4)+w1+w2-max(x1,x2,x3,x4)
2. 交集形狀的高度計算為:
IOU_H = min(y1,y2,y3,y4)+h1+h2-max(y1,y2,y3,y4)
其實是很簡單的幾何關系變換,上面的圖可以幫助你很好的理解這個意思。
代碼實現:001-IOU計算
以上這篇python實現IOU計算案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: