0
I’m a beginner in programming and have some problems trying to remove the background of the image using cv2. The program below runs, however the result is not as expected. I would like to help improve..
import numpy as np
import cv2
img = cv2.imread('001.tif')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray,5)
_,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
contours, hierarchy =
cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cnt = max(contours, key=cv2.contourArea)
h, w = img.shape[:2]
mask = np.zeros((h, w), np.uint8)
cv2.drawContours(mask, [cnt],-1, 255, -1)
res = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite('002.png', res)
cv2.imshow('img', res)
cv2.waitKey(0)
cv2.destroyAllWindows()