Separate the contour curves and clean each one by itself.
For each contour:
- If the curve is not closed, close it with a temporary line.
- Flood-fill the contour curve to get a solid monochrome figure.
- Run contour detection on the result. The edge of a monochrome figure will be a clean line.
- Flood-fill the area outside the new contour curve.
- Run contour detection one last time to restore the original contour.
Re-assemble the contours into a single bitmap.