huy
huy

Reputation: 1884

Remove background of the image

I am trying to remove the background of the image (the background can be any other color or contain noise, dust, etc)

This is the image:

enter image description here

And this is my code:

import cv2

img = cv2.imread('image.jpg', 0)

norm_img = np.zeros(img.shape)

normim = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)

_, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5,5),np.uint8)

opening = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)

mask_inv = cv2.bitwise_not(opening)

seg = cv2.add(mask_inv, normim)

Output:

enter image description here

The code is about to normalize the original image then add with the image that applied morphological which is a binary image.

Result of normalizing the original image and applying morphological the original image:

enter image description here enter image description here

So what happens with my code, how can I remove the background?

Upvotes: 3

Views: 577

Answers (2)

Alex Alex
Alex Alex

Reputation: 2018

You can try use percentile for normalization.

import cv2
from numpy import percentile
img = cv2.imread('mSEsr.jpg', cv2.IMREAD_GRAYSCALE)
cv2.normalize(img, img, 0, 255, cv2.NORM_MINMAX)
lower=percentile(img, 5)
upper=percentile(img,50)
cv2.normalize(img, img, -lower, 255+255-upper, cv2.NORM_MINMAX) # tune parameters

cv2.imwrite('finger_norm.png', img)

Result: enter image description here

Upvotes: 1

fmw42
fmw42

Reputation: 53089

You can do that using Numpy and Python/OpenCV as follows:

Input:

enter image description here

Mask:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('fingerprint.jpg')

# read mask as grayscale
mask = cv2.imread('mask.jpg', cv2.IMREAD_GRAYSCALE)

# threshold mask
thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# apply mask to image
result = img.copy()
result[thresh==0] = (255,255,255)

# save results
cv2.imwrite('fingerprint_masked.jpg', result)

cv2.imshow('masked image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()


Result:

enter image description here

Upvotes: 1

Related Questions