How to remove background using python and cv2?

Asked

Viewed 123 times

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()

With the execution of the code, this image: Antes

And after the code: Depois

1 answer

0

Chris Albon explains this process well, for your case you must specify a rectangle that will cover the image as for example:

inserir a descrição da imagem aqui

Using the following rectangle:

rectangle = (121, 66, 158, 493)

I got this result:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.