I have a binary image with contour lines and need to purify each contour line of all unnecessary pixels, leaving behind a minimally connected line.

Can somebody give me a source, code example or further information for this kind of problem and where to search for help, please?