OpenCV remove background

opencv remove background color
image processing remove background python
remove background from image opencv-python github
background subtraction - opencv java
foreground-background segmentation python
opencv remove white background
opencv foreground segmentation
image subtraction - opencv python

I am trying to remove the background of some images, tweaking some values and using some methods like morphologyEx gives me an aceptable result but some holes still remaining, in this last case, the holes doesn't fill even iterating on every contour and drawing it with -1. I can see that threshold image is really good, making the whole shape with lines, but I don't know how to continue...

Update I've changed my code so I get better results but I'm still getting some holes... If I could fill theese holes, the script would be perfect.

def get_contrasted(image, type="dark", level=3):
    maxIntensity = 255.0 # depends on dtype of image data
    phi = 1
    theta = 1

    if type == "light":
        newImage0 = (maxIntensity/phi)*(image/(maxIntensity/theta))**0.5
        newImage0 = array(newImage0,dtype=uint8)
        return newImage0
    elif type == "dark":
        newImage1 = (maxIntensity/phi)*(image/(maxIntensity/theta))**level
        newImage1 = array(newImage1,dtype=uint8)

        return newImage1

def sharp(image, level=3):
    f = cv2.GaussianBlur(image, (level,level), level)
    f = cv2.addWeighted(image, 1.5, f, -0.5, 0)
    return f

original_image = imread('imagen.jpg')
# 1 Convert to gray & Normalize
gray_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
gray_img = sharp(get_contrasted(gray_img))
gray_img = normalize(gray_img, None, 0, 255, NORM_MINMAX, CV_8UC1)
imshow("Gray", gray_img)

# 2 Find Threshold
gray_blur = cv2.GaussianBlur(gray_img, (7, 7), 0)
adapt_thresh_im = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 1)
max_thresh, thresh_im = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
thresh = cv2.bitwise_or(adapt_thresh_im, thresh_im)

# 3 Dilate
gray = cv2.Canny(thresh, 88, 400, apertureSize=3)
gray = cv2.dilate(gray, None, iterations=8)
gray = cv2.erode(gray, None, iterations=8)
imshow("Trheshold", gray)

# 4 Flood
contours, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour_info = []
for c in contours:
    contour_info.append((
        c,
        cv2.isContourConvex(c),
        cv2.contourArea(c),
    ))
contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
max_contour = contour_info[0]
holes = np.zeros(gray_img.shape, np.uint8)
drawContours(holes, max_contour, 0, 255, -1)
imshow("Holes", holes)

mask = cv2.GaussianBlur(holes, (15, 15), 0)
mask = np.dstack([mask] * 3)  # Create 3-channel alpha mask

mask = mask.astype('float32') / 255.0  # Use float matrices,
img = original_image.astype('float32') / 255.0  # for easy blending
masked = (mask * img) + ((1 - mask) * (0,0,1))  # Blend
masked = (masked * 255).astype('uint8')

imshow("Maked", masked)
waitKey()
0 Original

1 Threshold

2 Holes

3 Final Image

Remove background of the image using opencv Python, I solved your problem using the OpenCV's watershed algorithm. You can find the theory and examples of watershed here. First I selected  Background Removal (Segmentation) with OpenCV (Take 2) April 26th, 2019 Since I last wrote my post on background removal in 2016, I’ve searched for alternative ways to get better results.

As I was tackling the same issue, and found a solution in Python (with opencv2), thought of just sharing this here as well. Hope it helps.

import numpy as np
import cv2

cv2.namedWindow('image', cv2.WINDOW_NORMAL)

#Load the Image
imgo = cv2.imread('koAl2.jpg')
height, width = imgo.shape[:2]

#Create a mask holder
mask = np.zeros(imgo.shape[:2],np.uint8)

#Grab Cut the object
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

#Hard Coding the Rect The object must lie within this rect.
rect = (10,10,width-30,height-30)
cv2.grabCut(imgo,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img1 = imgo*mask[:,:,np.newaxis]

#Get the background
background = imgo - img1

#Change all pixels in the background that are not black to white
background[np.where((background > [0,0,0]).all(axis = 2))] = [255,255,255]

#Add the background and the image
final = background + img1

#To be done - Smoothening the edges

cv2.imshow('image', final )

k = cv2.waitKey(0)

if k==27:
    cv2.destroyAllWindows()

Applications of Foreground-Background separation , Using Semantic Segmentation and DeepLab V3 in PyTorch for background removal, background changing, background blurring, and creating  Hi, your videos are really helpful. I’m trying to detect the court in a basketball game; with Canny and Hough Transform I’ve got the lines of the court but also I’ve got another no necessary lines, how can I isolate just the lines of the court ignoring the others?

@dhanushka's method works fine. Here's my pythonic version:

def get_holes(image, thresh):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    im_bw = cv.threshold(gray, thresh, 255, cv.THRESH_BINARY)[1]
    im_bw_inv = cv.bitwise_not(im_bw)

    contour, _ = cv.findContours(im_bw_inv, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
    for cnt in contour:
        cv.drawContours(im_bw_inv, [cnt], 0, 255, -1)

    nt = cv.bitwise_not(im_bw)
    im_bw_inv = cv.bitwise_or(im_bw_inv, nt)
    return im_bw_inv


def remove_background(image, thresh, scale_factor=.25, kernel_range=range(1, 15), border=None):
    border = border or kernel_range[-1]

    holes = get_holes(image, thresh)
    small = cv.resize(holes, None, fx=scale_factor, fy=scale_factor)
    bordered = cv.copyMakeBorder(small, border, border, border, border, cv.BORDER_CONSTANT)

    for i in kernel_range:
        kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (2*i+1, 2*i+1))
        bordered = cv.morphologyEx(bordered, cv.MORPH_CLOSE, kernel)

    unbordered = bordered[border: -border, border: -border]
    mask = cv.resize(unbordered, (image.shape[1], image.shape[0]))
    fg = cv.bitwise_and(image, image, mask=mask)
    return fg


img = cv.imread('koAl2.jpg')
nb_img = remove_background(img, 230)

Remove background tutorial - opencv 3.2 with python 3, As the name suggests, BS calculates the foreground mask performing a subtraction between the current frame and a background model, containing the static part  OpenCV remove background. Ask Question Asked 4 years, 10 months ago. Active 1 year, 9 months ago. Viewed 16k times How to remove background image with Opencv. 1.

@grep, according to a post by Alexander Lutsenko, for python 3.6.3, to make the code work, you need to add one more returned value to the findContours() as follows:

contour, _ = cv.findContours(im_bw_inv, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)

to

_, contour, _ = cv.findContours(im_bw_inv, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)

How to Use Background Subtraction Methods, Hi I am using opencv with python for removing background from image. code i have write is working for some image not for all. please help me  Most of the code looks similar to the Remove Background section but here we don’t create an array of white pixels. Instead, we apply a GaussianBlur of kernel width and height 7 to the foreground image and save the result in the blurredImage.

try this morphological operation for dilation and erosion removing holes in C++

Mat erodeElement = getStructuringElement(MORPH_RECT, Size(4, 4));
morphologyEx(thresh, thresh, MORPH_CLOSE ,erodeElement);
morphologyEx(thresh, thresh, MORPH_OPEN, erodeElement);
morphologyEx(thresh, thresh, MORPH_CLOSE, erodeElement);
morphologyEx(thresh, thresh, MORPH_OPEN, erodeElement);
morphologyEx(thresh, thresh, MORPH_OPEN, erodeElement);

Removing image background from image with python, Fruits 360 backgound removal¶. In this kernel you can find easy and ready-to-use way for removing backgound from images. I used OpenCV, PIL and numpy. Background Subtraction Tutorial content has been moved: How to Use Background Subtraction Methods Generated on Thu Apr 30 2020 03:27:22 for OpenCV by 1.8.13

OpenCV background removal, A couple of days ago, I was faced with a project that demanded removing the white background of sketches when they're dropped into a certain  Background subtraction (BS) is a common and widely used technique for generating a foreground mask (namely, a binary image containing the pixels belonging to moving objects in the scene) by using static cameras.

Automating Background Color Removal with Python and OpenCV, The idea here is to find the foreground, and remove the background. This is much like what a Duration: 7:31 Posted: Jan 6, 2016 Remove backgrounds 100% automatically in 5 seconds with zero clicks. There are approximately 20 million more interesting activities than removing backgrounds by hand. Thanks to remove.bg's clever AI, you can slash editing time - and have more fun! Stunning Quality. See more samples. Integrates with your Software Workflow.

GrabCut Foreground Extraction OpenCV Python Tutorial, Source code: [python lineoffset=”15″] import cv2 import numpy as np. cap = cv2 Duration: 33:11 Posted: Jun 2, 2017 Background Averaging (Background Subtraction) in OpenCV Python - Duration: 5:56. Lenny Linus 2,343 views

Comments
  • Your code is not a valid Python code. Please post code without syntax errors (namely, a code that is able to run).
  • Missing parenthesis, updated now.
  • You should look up some opencv tutorials on masking first. Also, look at this: stackoverflow.com/questions/18710428/…
  • I've read some tutorials, and that stackoverflow question too but i can't get it working.. For example some tutorials are on C++ I'm using python and I dont know how to do this in python, for example Mat(hsvImg.rows, hsvImg.cols, CV_8UC1, 200) and other things...
  • @RobertW.Hunter then look into this
  • I can't get it working on python, there are two things that I can't convert to Python: 1: bordered just became a method? When? bordered(Rect(b, b, small.cols, small.rows)) and what is Rect ? 2: resize(holes, small, Size(), .25, .25) I haven't a Size() object, I imagine that this is a Tuple??, but I can't use an empty tuple () 3: morphologyEx(bordered, bordered, MORPH_CLOSE, kernel, Point(-1, -1), 1) becomes bordered = cv2.morphologyEx(bordered, cv2.MORPH_CLOSE, kernel, (-1, -1), 1) in python but error: new style getargs format but argument is not a tuple
  • Mat mask = bordered(Rect(b, b, small.cols, small.rows)); extracts the specified ROI into mask. It's an operator of Mat class. You'll be able to get this working if you concentrate on the description I've given rather than trying to do a one-to-one mapping of the C++ code to Python. I added the code hoping that it would make the description clearer.
  • version of python? how to import cv?
  • ", line 11, in get_holes contour, _ = cv2.findContours(im_bw_inv, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) ValueError: too many values to unpack