Image2Cartoon using OpenCV

Image Source- Brooklyn Willow Street,NY

Convert your image into cartoon like style using opencv and python in few lines.

Here we are going to use Sobel Filter and alpha blend.

src = cv2.imread("brookyln.jpg")  # read the source image
source image
  • apply gaussian blur
blur = cv2.GaussianBlur(src, (3, 3), 0)  
blur image
  • convert to gray
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) 
gray image
  • apply sobel filter
scale = 2
delta = 0
ddepth = cv2.CV_16S
grad_x = cv2.Sobel(
gray, ddepth, 1, 0, ksize=1, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT
)
# Gradient-Y

grad_y = cv2.Sobel(
gray, ddepth, 0, 1, ksize=1, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT
)
abs_grad_x = cv2.convertScaleAbs(grad_x)
abs_grad_y = cv2.convertScaleAbs(grad_y)
grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
src1 = cv2.filter2D(grad, -1, kernel)
# convert single channel to multi channel
src1 = cv2.cvtColor(src1, cv2.COLOR_GRAY2BGR)
sobel filter image
  • sharpen the image and blend it with blurred source image using alpha value.
sharped = cv2.filter2D(blur, -1, kernel)  # alpha blend images
cartoon_img = cv2.addWeighted(src1, 0.5, sharped, 0.7, 0)
# view result
cv2.imshow("cartoon-effect", cartoon_img)
cv2.waitKey(0)
result image

thank you 🙂 👍.

references: opencv docs- sobel derivatives

code link : https://github.com/ash11sh/hakuna-matata/tree/main/canvas-effect

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store