13

I have a dataset that contains full width human images I want to remove all the backgrounds in those Images and just leave the full width person,

my questions:

is there any python code that does that ?

and do I need to specify each time the coordinate of the person object?

enter image description here

reham501
  • 109
  • 1
  • 1
  • 9
  • 1
    Does this answer your question? [OpenCV remove background](https://stackoverflow.com/questions/31133903/opencv-remove-background) – zteffi Jul 20 '20 at 21:05

2 Answers2

39

Here is one way to use Python/OpenCV.

  • Read the input
  • Convert to gray
  • Threshold and invert as a mask
  • Optionally apply morphology to clean up any extraneous spots
  • Anti-alias the edges
  • Convert a copy of the input to BGRA and insert the mask as the alpha channel
  • Save the results

Input:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread('person.png')

# convert to graky
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold input image as mask
mask = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY)[1]

# negate mask
mask = 255 - mask

# apply morphology to remove isolated extraneous noise
# use borderconstant of black since foreground touches the edges
kernel = np.ones((3,3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

# anti-alias the mask -- blur then stretch
# blur alpha channel
mask = cv2.GaussianBlur(mask, (0,0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT)

# linear stretch so that 127.5 goes to 0, but 255 stays 255
mask = (2*(mask.astype(np.float32))-255.0).clip(0,255).astype(np.uint8)

# put mask into alpha channel
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask

# save resulting masked image
cv2.imwrite('person_transp_bckgrnd.png', result)

# display result, though it won't show transparency
cv2.imshow("INPUT", img)
cv2.imshow("GRAY", gray)
cv2.imshow("MASK", mask)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Transparent result:

enter image description here

Innat
  • 16,113
  • 6
  • 53
  • 101
fmw42
  • 46,825
  • 10
  • 62
  • 80
  • Hi FMW42,, Here is some one asked the question which is very simalry to my question . can you check this link ;https://stackoverflow.com/q/66309487/4070307 – Govinda Raju Feb 22 '21 at 14:40
  • The background at that link is more constant (no texture) and no shadow and the contrast between the foreground and background is higher and so easier to separate – fmw42 Feb 22 '21 at 15:29
  • How can we do this . Can u share code please – Govinda Raju Feb 24 '21 at 01:35
  • What image - please provide it? Use my code above. – fmw42 Feb 24 '21 at 01:43
  • I have reached my question limit . can you please look into above link question , its very similar of my query , can you pls answer that question . – Govinda Raju Feb 25 '21 at 03:05
  • That image is hard to process by my method above because the background is too similar to the white t-shirt color. It needs AI / Deep Learning such as at http://remove.bg to remove the background. – fmw42 Feb 25 '21 at 03:32
  • Any tip on how to choose `thresh` for the `cv2.threshold()` function? I have many images and I found that changing this parameter yields a better result. – igorkf Nov 20 '21 at 00:03
  • You can measure the colors of the corner of the image and take an average and then try a threshold near that color. – fmw42 Nov 20 '21 at 00:17
  • A follow up question here: Assume the photo with white background above is instead not white but some random background, say in a city. How do I replace the noisy background with a white background? – Parseval Jan 17 '23 at 15:58
  • For non-constant color backgrounds, you would likely need to use AI/Deep Learning with training to remove the background. Can you post an example image? – fmw42 Jan 17 '23 at 17:04
  • 1
    There is an open source library which utilizes AI to remove the background from people and objects in images: [rembg](https://github.com/danielgatis/rembg) . You could utilize this in your project. @Parseval – Logan Price Jun 27 '23 at 13:26
-2

This code worked better for me:

from rembg import remove
from PIL import Image
import easygui as eg
input_path = eg.fileopenbox(title='Select image file')
output_path = eg.filesavebox(title='Save file to..')
input = Image.open(input_path)
output = remove(input)
output.save(output_path)

Add the following requirements:

pip install rembg
pip install easygui

how-to remove image backgrounds

A bit slow but quiet efficient.

Input image: enter image description here

Result image without background:

enter image description here

Regards, Ali

Ali Ait-Bachir
  • 550
  • 4
  • 9