Akash Dhar
Akash Dhar

Reputation: 171

Background removal using opencv python

Can some one help me with background removal using OpenCV Python? I Am trying to use it for my OCR project.

The expected sample image is : sample_image

Upvotes: 2

Views: 731

Answers (2)

Alex Alex
Alex Alex

Reputation: 2018

Use inRange function for select:

import cv2 as cv
low_H = 0
low_S = 0
low_V = 220
high_H = 255
high_S = 30
high_V = 255
frame = cv.imread('EQsBj.jpg')
frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V))
cv.imwrite('out_3.png', frame_threshold)

Result: enter image description here

Upvotes: 2

Ankur De
Ankur De

Reputation: 141

You can Try this sample code for background removal.

Reading image file

img = cv2.imread(Image1.jpg)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

Convert to grayscale

img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

Apply the thresholding

we are taking a constant threshold for simplicity.

thresh = 127   
im_b = cv2.threshold(img_gray, thresh, 255, cv2.THRESH_BINARY)[1]

Find the contour of the figure

contours, hierarchy = cv2.findContours(image = im_b, mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE)

Sort the contours

contours = sorted(contours, key = cv2.contourArea, reverse= True)

Masking the object based on contour

mask = np.ones(img.shape[:2], np.uint8)
mask.fill(255)
cv2.drawContours(mask, contours, contourIdx =0 , color =0, thickness = -1)
new_img = cv2.add(im_b, mask)
cv2.imwrite('masked.jpg',new_img)
cv2.imshow('masked.jpg')

Given your sample image, I have aimed to crop out a single detected object, based on contour area.

I hope it helps. Cheers Mate !!!

Upvotes: 2

Related Questions