Image blending is also image addition, but different weights are given to the images, giving an impression of transparency. In order to do this, the cv2.addWeighted() function will be used. This function is commonly used to get the output from the Sobel operator.
The Sobel operator is used for edge detection, where it creates an image emphasizing edges. The Sobel operator uses two 3 × 3 kernels, which are convolved with the original image in order to calculate approximations of the derivatives, capturing both horizontal and vertical changes, as shown in the following code:
# Gradient x is calculated:
# the depth of the output is set to CV_16S to avoid overflow
# CV_16S = one channel of 2-byte signed integers (16-bit signed integers)
gradient_x = cv2.Sobel(gray_image, cv2.CV_16S, 1, 0, 3)
gradient_y = cv2.Sobel(gray_image, cv2.CV_16S, 0, 1, 3)
Therefore, after the horizontal and vertical changes have been calculated, they can be blended into an image by using the aforementioned function, as follows:
# Conversion to an unsigned 8-bit type:
abs_gradient_x = cv2.convertScaleAbs(gradient_x)
abs_gradient_y = cv2.convertScaleAbs(gradient_y)
# Combine the two images using the same weight:
sobel_image = cv2.addWeighted(abs_gradient_x, 0.5, abs_gradient_y, 0.5, 0)
This can be seen in the arithmetic_sobel.py script. The output of this script can be seen in the following screenshot:
In the preceding screenshot, the output of the Sobel operator is shown, including both the horizontal and vertical changes.