Home > database >  How to select/mask this object from black background
How to select/mask this object from black background

Time:09-25

I want to crop only the object not the black background. How can it be done it using python / openCV?

Image

I have used the following code, I only need object

import cv2
import numpy as np

# original image
# -1 loads as-is so if it will be 3 or 4 channel as the original
image = cv2.imread('/content/image1.jpg', -1)
# mask defaulting to black for 3-channel and transparent for 4-channel
# (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(10,10), (300,300), (10,300)]], dtype=np.int32)
# fill the ROI so it doesn't get wiped out when the mask is applied
channel_count = image.shape[2]  # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
# from Masterfool: use cv2.fillConvexPoly if you know it's convex

# apply the mask
masked_image = cv2.bitwise_and(image, mask)

# save the result
cv2.imwrite('image_masked.png', masked_image)

CodePudding user response:

You can do it using the next following code. You can play with the minimum threshold value to achieve better results (I found that 50 works great)

import cv2

image = cv2.imread(PathToYourImageFile)
imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(imageGray, 80, 255, cv2.THRESH_BINARY)
b, g, r = cv2.split(image)
rgba = [b, g, r, thresh]
imageResult = cv2.merge(rgba, 4)
cv2.imwrite("ImageResult.png", imageResult)

Result:

enter image description here

CodePudding user response:

You can make the black background transparent as follows.

import cv2

img = cv2.imread("0byhS.jpg", 1)
tmp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)
b, g, r = cv2.split(img)
rgba = [b,g,r, alpha]
dst = cv2.merge(rgba,4)
cv2.imwrite("test.png", dst)
cv2.waitKey(0)

enter image description here

  • Related