【发布时间】:2021-09-24 05:35:13
【问题描述】:
我只想裁剪对象而不是黑色背景。 如何使用 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)
【问题讨论】:
-
我不明白你的问题。您能否从广义的角度或通过模拟示例阐明输出的外观?
-
输出应该只有对象作为图像,用于在黑色图像上绘制多个对象
-
当我运行时没有删除黑色背景
-
我还是不明白。让我们称对象为流星,所以我假设您只想要流星 - 那么输出图像中黑色当前所在的位置会是什么?
-
如果您不喜欢这两个现有答案中的任何一个......这可能是因为透明度蒙版是二进制的(是/否)。可以计算灰度透明度通道......但这有点复杂。必须(1)对对象周围逐渐消失的黑色做出反应(2)从每个像素的混合中去除黑色(或者将图片声明为“预乘 alpha”)
标签: python opencv image-processing