Matlab's Conv2 equivalent in OpenCV

前端 未结 2 1980
予麋鹿
予麋鹿 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:32

    If you are using OpenCV with Python 2 binding you can use Scipy as long as your images will be ndarrays:

    >>> from scipy import signal
    >>> A = np.array([[1,-2], [3,4]])
    >>> B = np.array([[-0.707, 0.707]])
    >>> signal.convolve2d(A,B)
    array([[-0.707,  2.121, -1.414],
          [-2.121, -0.707,  2.828]])
    

    Be sure that you use the full mode (which is set by default) if you want to achieve the same result as in matlab as long as if you use 'same' mode Scipy will center differently from Matlab.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题