Find boolean mask by pattern

前端 未结 2 1948
一生所求
一生所求 2020-12-11 07:37

I have array:

arr = np.array([1,2,3,2,3,4,3,2,1,2,3,1,2,3,2,2,3,4,2,1])
print (arr)
[1 2 3 2 3 4 3 2 1 2 3 1 2 3 2 2 3 4 2 1]

I would like

2条回答
  •  猫巷女王i
    2020-12-11 07:53

    We can simplify things at the end with Scipy supported binary-dilation -

    from scipy.ndimage.morphology import binary_dilation
    
    m = (rolling_window(arr, len(pat)) == pat).all(1)
    m_ext = np.r_[m,np.zeros(len(arr) - len(m), dtype=bool)]
    out = binary_dilation(m_ext, structure=[1]*N, origin=-(N//2))
    

    For performance, we can bring in OpenCV with its template matching capability, as we are basically doing the same here, like so -

    import cv2
    
    tol = 1e-5
    pat_arr = np.asarray(pat, dtype='uint8')
    m = (cv2.matchTemplate(arr.astype('uint8'),pat_arr,cv2.TM_SQDIFF) < tol).ravel()
    

提交回复
热议问题