In our post Fun With Numpy from a few months ago, we loaded a color photo, converted it to a 3D pixel array, and edited it simply using numpy. I came across a recent Towards Data Science post on cartoonizing a photo with python using cv2 and numpy (original notebook) and tried it out to cartoonize my LinkedIn profile photo. It follows two core principles underlying a cartoon: 1) sharper, more pronounced edges and 2) fewer, more homogeneous colors.
We’ll detect edges by defining a function that converts to grayscale, reduces noise, and uses cv2.adaptiveThreshold to detect edges. We’ll reduce color palette using K-means clustering, setting the number of clusters to 7. We’ll soften using cv2.bilateralFilter, which smooths flat regions while keeping edges sharp. Lastly, we’ll combine the edge and color effects using bitwise_and and compare our original and final cartoon images. Here’s our notebook on Google Colab and Git. Try it out on your own photo!

