0
votes

How can I create my own kernel in OpenCV Python?

I'm trying to create a sobel kernel below but I get the error:

AttributeError: 'module' object has no attribute 'mat'

def sobel(src):

    kernelX = [
        [ -1, 0, 1 ],
        [ -2, 0, 2 ],
        [ -1, 0, 1 ]
    ]

    kernelY = [
        [ -1, -2, -1 ],
        [  0,  0,  0 ],
        [  1,  2,  1 ]
    ]

    kernelXMat = cv2.mat(3, 3, cv2.cv2.CV_32FC1, kernelX)
    kernelYMat = cv2.mat(3, 3, cv2.CV_32FC1, kernelY)

    horizGradient = cv2.filter2D(src, -1, kernelXMat)
    vertGradient = cv2.filter2D(src, -1, kernelYMat)

    return [horizGradient, vertGradient]
1

1 Answers

3
votes

The Python equivalent of OpenCV Mat is numpy.array. The specified kernels can be created as follows in python.

import numpy as np

kernelXMat = np.array(kernelX, dtype=float);
kernelYMat = np.array(kernelY, dtype=float);