python - 如何从黑色背景中选择/屏蔽此对象
问题描述
我只想裁剪对象而不是黑色背景。如何使用 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)
解决方案
您可以使用以下代码来执行此操作。您可以使用最小阈值来获得更好的结果(我发现 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)
结果:
推荐阅读
- laravel - 将 laravel sanctum 与 nuxt js 集成
- mysql - 在 mysql 查询中组合结果
- python - 电子邮件地址中的特殊字符名称存在问题
- face-recognition - face_recognition 错误:列表索引超出范围
- android - 为什么电容器将所有内容都保存到 IndexedDB 而不是 Android 上的 sdcard 上?
- python - 从本地主机发送电子邮件时,有什么方法可以更改或隐藏我的设备 IP?
- php - 如何在 php 表单的查询中使用 nullif()
- c# - 安装我的应用程序后无法加载 dll 'SQLite.interop.dll'。该 dll 存在并且安装 Visual Studio 神秘地修复它
- javascript - 我想用相同的但使用reduce完成的替换这个forEach函数。你能说我哪里做错了吗?
- symfony - 如何在 symfony 中使用 api-platform 来编辑帖子数据?