首页 > 解决方案 > 如何从黑色背景中选择/屏蔽此对象

问题描述

我只想裁剪对象而不是黑色背景。如何使用 python / openCV 来完成它?

图片

我使用了以下代码,我只需要对象

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)

标签: pythonopencvimage-processing

解决方案


您可以使用以下代码来执行此操作。您可以使用最小阈值来获得更好的结果(我发现 50 效果很好)

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)

结果:

在此处输入图像描述


推荐阅读