Matlab's Conv2 equivalent in OpenCV

前端 未结 2 1993
予麋鹿
予麋鹿 2020-12-21 17:06

I have been trying to do Convolution of a 2D Matrix using OpenCV. I actually went through this code http://blog.timmlinder.com/2011/07/opencv-equivalent-to-matlabs-conv2-fun

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 17:42

    If you want an exclusive OpenCV solution, use cv2.filter2D function. But you should adjust the borderType flag if you want to get the correct output as that of matlab.

    >>> A = np.array([ [1,-2],[3,4] ]).astype('float32')
    >>> A
    array([[ 1., -2.],
           [ 3.,  4.]], dtype=float32)
    
    >>> B = np.array([[ 0.707,-0.707]])
    >>> B
    array([[ 0.707, -0.707]])
    
    >>> cv2.filter2D(A2,-1,B,borderType = cv2.BORDER_CONSTANT)
    array([[-0.70700002,  2.12100005, -1.41400003],
           [-2.12100005, -0.70700002,  2.82800007]], dtype=float32)
    

    borderType is important. To find the convolution you need values outside the array. If you want to get matlab like output, you need to pass cv2.BORDER_CONSTANT. See output is greater in size than input.

提交回复
热议问题