Reputation: 33
I want to change image background to black color. I tried with some codes but it didn't work, sometime it removes the object. The backgrounds in this images may vary depends on the places. with curiosity do I need to make machine learning to remove background for this kind of images for better results?
import numpy as np
import cv2
image = cv2.imread(r'D:/IMG_6334.JPG')
r = 150.0 / image.shape[1]
dim = (150, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
lower_white = np.array([80, 1, 1],np.uint8) #lower hsv value
upper_white = np.array([130, 255, 255],np.uint8) #upper hsv value
hsv_img = cv2.cvtColor(resized,cv2.COLOR_BGR2HSV) #rgb to hsv color space
#filter the background pixels
frame_threshed = cv2.inRange(hsv_img, lower_white, upper_white)
kernel = np.ones((5,5),np.uint8)
#dilate the resultant image to remove noises in the background
#Number of iterations and kernal size will depend on the backgound noises size
dilation = cv2.dilate(frame_threshed,kernel,iterations = 2)
resized[dilation==255] = (0,0,0) #convert background pixels to black color
cv2.imshow('res', resized)
cv2.waitKey(0)
Upvotes: 1
Views: 291
Reputation: 409
This is a seperate topic on itself. Image matting is the thing you are looking for. This is used to convert your background to black and your foreground to white(which in this case you dont have to do). Check out this website http://alphamatting.com/ where all the state of the art matting algos are present and try implementing it in ur code. I would say this is really long route, so I can say better solution if you mention what exactly are you planning to do after removing the backgrounds of the image.
Upvotes: 2