简体   繁体   中英

Matlab's Conv2 equivalent in OpenCV

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-function/#respond but it yields correct answers only in positive cases. Is there a simple function like conv2 in Matlab for OpenCV or C++?

Here is an example:

A= [
  1 -2
  3  4
]

I want to convolve it with [-0.707 0.707]

And the result as by conv2 from Matlab is

 -0.7071    2.1213   -1.4142
 -2.1213   -0.7071    2.8284

Some function to compute this output in OpenCV or C++? I will be grateful for a response.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM