2d – Marching squares – image border

I have implemented Marching squares algorithm. All is OK, except the problem with image borders.

Currently, I enlarge the image (8bit) on each side by 1 pixel and set its value to either 0 or 255. However, this way the contours are sometimes incorrectly closed.

On the left, the contour is correctly closed. However, the result is sometimes as on the right, where the contour encloses “the other way”. How to properly solve this?

enter image description here