Ignoring Background in Binarization

I’m trying to convert this grayscale image into a binary image. I’m currently using adaptive binarization, but it’s creating outlines around the edges. How can I avoid this issue?

img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

a simple threshold() call can’t do this. I suspect you’re applying more than a threshold() to the picture.

MRE please.

also: one of the pictures is a cropped screenshot. don’t do that. save the image itself, not a screenshot.

Sorry about that, I’ll add a minimal, reproducible example below.


Here’s the code and results I used after converting the grayscale image.

img = cv2.GaussianBlur(img, (11, 11), 0)
kernel = np.ones((11, 11), np.uint8)
erode = cv2.erode(img, kernel, iterations=1)
img = cv2.absdiff(img, erode)
img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
result = img

that’s where that comes from.

that operation is literally how you get outlines/borders with morphology operations.

Oh yes, I forgot to check that part of the code. Replacing the erosion operation with an opening operation yielded the desired result.

img = cv2.GaussianBlur(img, (11, 11), 0)
kernel = np.ones((11, 11), np.uint8)
morph_open = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, iterations=1)
img = cv2.absdiff(img, morph_open)
img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]