How do I use the cv::divide function

My code:

#include <opencv2\opencv.hpp>

using namespace cv;

using namespace std;

Mat inverted(Mat image) {
	return 255 - image;
};

Mat sketch(Mat image) {

	Mat final;
	Mat blur;
	Mat grey;
	Mat inverted_blur;
	Mat sketch;


	// Making the image grey
	cvtColor(image, grey, COLOR_BGR2GRAY);
	// Make the current image blur
	GaussianBlur(image, blur, Size(21, 21), 0);
	// Inverting the image
	inverted_blur = 255 - blur;
	cv::divide(grey,inverted_blur, sketch, 256.0);

	return sketch;

};

int main() {

	Mat image;

	namedWindow("Display window");

	VideoCapture cap(0);

	char k;
	if (!cap.isOpened()) {

		cout << "cannot open camera";

	}

	while (true) {

		cap >> image;

		image = sketch(image);

		imshow("Display window", image);

		k = waitKey(1);
		if (k == 'q') {
			break;
		}

	}

	return 0;

}

It is throwing an (Memory) Execption here:

cv::divide(grey,inverted_blur, sketch, 256.0);

In sketch.
What did I do wrong?
Side notes:

  • This code has been translated from python

Orignal python code

def sketch(image):
    # converting BGR image to grayscale
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # image inversion
    inverted_image = 255 - gray_image
    blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
    inverted_blurred = 255 - blurred
    pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)
    return pencil_sketch

try-catch whatever cv::Exception happens and print its details

check image.empty() after reading from cap

your c++ code is making a gaussian from the 3 channel image, not the 1 channel gray image. so, blur has 3 channels, too, and you try to divide a 1 channel by a 3 channel image.