高效NMS

xinet發表於2018-11-19

2 非極大值抑制(NMS)

我們先載入圖片:

import numpy as np
from copy import  deepcopy
from matplotlib import pyplot as plt
np.set_printoptions(2)     # 修改了 NumPy 的列印精度
# 指定預設字型, 為在 Matplotlib 中顯示中文,設定特殊字型
plt.rcParams[`font.sans-serif`] = [`SimHei`]
plt.rcParams[`axes.unicode_minus`] = False  # 解決儲存影像是負號 `-` 顯示為方塊的問題

%matplotlib inline

img_name = `../images/catdog.jpg`
img = plt.imread(img_name)

1D NMS

程式碼如下

class NMS:
    ```
    參考論文:Neubeck A, Van Gool L. Efficient Non-Maximum Suppression

    非極大值抑制
    ```

    def __init__(self, I):
        ```
        引數
        ===========
        I::1D 或者 2D 陣列
        ```
        self.I = I
        self.__pmax = deepcopy(self.I)

    def __CompPartialMax(self, from_, to):
        ```
        Compute Partial Maximum

        返回
        =========
        max{self.I[from_:to+1]}
        ```
        best = to
        # 從右往左搜尋
        while to > from_:
            to -= 1
            if self.I[to] <= self.I[best]:
                self.__pmax[to] = self.I[best]
            else:
                self.__pmax[to] = self.I[to]
                best = to
        return best

    def BlockWise(self, r):
        ```
        r 近鄰,即 (2r+1)-Neighborhood
        ```
        w = len(self.I)
        assert 3 * r < w, "鄰域半徑超出範圍"
        i = r
        self.__CompPartialMax(0, i - 1)
        chkpt = -1
        maximuns = []

        while i + 2 * r < w:
            j = self.__CompPartialMax(i, i + r)
            k = self.__CompPartialMax(i + r + 1, j + r)
            if i == j or self.I[j] > self.I[k]:  # self.I[j] 是極大值
                if (chkpt < j - r or self.I[j] >= self.__pmax[chkpt]) and (
                        j - r == i or self.I[j] >= self.__pmax[j - r]):
                    maximuns.append(j)
                if i < j:
                    chkpt = i + r + 1
                i = j + r + 1
            else:
                i = k
                chkpt = j + r + 1
                while i < w - r:
                    j = self.__CompPartialMax(chkpt, i + r)
                    if self.I[i] > self.I[j]:  # # self.I[i] 是極大值
                        maximuns.append(i)
                        i = i + r - 1
                        break
                    else:
                        chkpt = i + r - 1
                        i = j
        return maximuns


相關文章