Reputation: 171
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
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)
Upvotes: 2
Reputation: 141
You can Try this sample code for background removal.
img = cv2.imread(Image1.jpg)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
we are taking a constant threshold for simplicity.
thresh = 127
im_b = cv2.threshold(img_gray, thresh, 255, cv2.THRESH_BINARY)[1]
contours, hierarchy = cv2.findContours(image = im_b, mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key = cv2.contourArea, reverse= True)
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