There are many implementations of converting the medial axis on the Internet (I personally do not use OpenCV , but I'm sure it has a decent implementation). However, you can easily implement it yourself.
To perform the transformation of the medial axis, we need to define only one term: a simple point. Point (P) is a simple point if removing P does not affect the number of connected components in either the foreground or the background. So, you have to solve connectivity (4 or 8) for the background and for the foreground - to work, select the other for both (if you're interested, look at the Jordan property on google).

The axis of the medial transformation can be implemented by sequentially deleting simple points. You get the last skeleton if there are no simpler points. You get a curved skeleton (I donβt know which English name is rare for it, please correct me) if you have only endpoints or difficult points. You have provided examples of the latter in your question.
The search for simple points can be easily implemented using morphological operators or a lookup table. Hint: dot is a simple dot if the number of connected components in the background is 1 and the number of connected components in the foreground is 1 in the local 3x3 window.
source share