How to transform an image into a cartoon from command line?

I found a bash script for imagemagick to do that by Fred Weinhaus. His scripts are available free of charge for non-commercial use, ONLY.

Command line usage:

USAGE: cartoon [-p pattern] [-n numlevels] [-m method] [-e edgeamount] 
[-b brightness] [-s saturation] infile outfile

USAGE: cartoon [-h or -help]

-p ... pattern ...... segmentation pattern (shape); 0<=integer<=100;
..................... default=70
-n ... numlevels .... number of desired segmentation levels; integer>=2;
..................... default=6
-m ... method ....... edge method; 1 or 2; default=1
-e ... edgeamount ... amount of edges; float>=0; default=4
-b ... brightness ... brightness of cartoon; integer>=0; default=100
-s ... saturation ... saturation of cartoon; integer>=0; default=150

PURPOSE: To create a cartoon-like appearance to an image.

(more on the site itself.) What the script does ...

(Optionally) applies a median filter to the image
Reduces the number of colors in the filtered image
Converts the original image to grayscale
(Optionally) applies a median filter to the grayscale image
Applies a gradient edge detector to the grayscale image
Thresholds the edge image to binary
Composites the edge image with the color reduced image

There are samples on his site but those are not near what your examples are. You probabaly will need to play with the settings for it to come out as what your images look like.


As you already may have found out cartoon of posterize filters from various image processing solutions may need quite a bit of tweaking to the original source before we can get results similar to your examples.

Two solutions that operate from the command line may give you results close to your examples, but the results we get still depend much on the source image used.

ImageMagick

Using the convert or mogrify tool we can apply the -paint filter for a flat-painted cartoon-like styl to our source:

convert -paint <strength> <source> <output>

Replace <strength> with an integer to specify the brush size. The smaller the more details will be preserved. On your example I used a strength of 4 for the following result:

enter image description here

Trace to vector graphics

Better results than from bitmap operations may be obtained by tracing the bitmap to a vector graphics by using e.g. Inkscape. We could then also add strokes or adapt the resulting colors to better meet our needs.

A command-line tracer can be installed with autotrace (sadly this package is in the repositories for Ubuntu 18.04 or older only).

There are many options to tune the results obtained with using autotrace. Below example was generated with these options:

autotrace -color-count 6 -filter-iterations 8 -remove-adjacent-corners -output-format svg input.png > output.svg

enter image description here