How to adjust thresholding parameters to mask an image in OpenCV?

535 Views Asked by At

I am trying to do some preprocessing on this image by creating a mask to separate the foreground from the background.

enter image description here

The problem is when I use thresholding, it masks some of the background and im could not find any solution to improve this.

As it can be seen the darker sections of the background are being masked off which is not desireable.

enter image description here

Here is the code I used to produce this.

img_path="./combined.png"

combined_img=cv2.imread(img_path)

gray = cv2.cvtColor(combined_img, cv2.COLOR_BGR2GRAY)

_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

plt.imshow(combined_img)
plt.show()
plt.imshow(binary, cmap='gray')
plt.show()

Any advice on potential algorithms or resources to look into would be greatly appreciated.

1

There are 1 best solutions below

0
Finn McClusky On

Thanks, Cris Luengo for providing the answer with adaptive thresholding, it allowed for a great way to separate the foreground and background:

enter image description here

Here is the source code:

img_path="./combined.png"

combined_img=cv2.imread(img_path)

blurred_img = cv2.GaussianBlur(combined_img, (7, 7), 0)

blurredGray = cv2.cvtColor(blurred_img, cv2.COLOR_BGR2GRAY)

adaptive=cv2.adaptiveThreshold(blurredGray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 1023,5)

plt.imshow(adaptive, cmap="gray")
plt.show()