import cv2
import numpy as np
numDownSamples = 2 # number of downscaling steps
numBilateralFilters = 7 # number of bilateral filtering steps
img_rgb = cv2.imread("testimg.jpg")
# -- STEP 1 --
# downsample image using Gaussian pyramid
img_color = img_rgb
for _ in range(numDownSamples):
img_color = cv2.pyrDown(img_color)
# repeatedly apply small bilateral filter instead of applying
# one large filter
for _ in range(numBilateralFilters):
img_color = cv2.bilateralFilter(img_color, 9, 9, 7)
# upsample image to original size
for _ in range(numDownSamples):
img_color = cv2.pyrUp(img_color)
# -- STEPS 2 and 3 --
# convert to grayscale and apply median blur
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, 7)
# -- STEP 4 --
# detect and enhance edges
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 9, 2)
# -- STEP 5 --
# convert back to color so that it can be bit-ANDed with color image
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
toon = cv2.bitwise_and(img_color, img_edge)
cv2.imwrite('cartoon.jpg', toon)
OpenCV Error: Sizes of input arguments do not match (The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array') in cv::binary_op, file C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp, line 225
Traceback (most recent call last):
File "cartoonify.py", line 38, in <module>
toon = cv2.bitwise_and(img_color, img_edge)
cv2.error: C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:225: error: (-209) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function cv::binary_op