import cv2 | |
import numpy as np | |
# 读取照片 | |
img = cv2.imread('path_to_your_image.jpg') | |
# 转换为灰度图像 | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
# 创建一个掩码图像,其中物体应被标记为0 | |
mask = np.zeros(gray.shape, dtype=np.uint8) | |
# 在掩码图像中绘制物体的轮廓(用黑色填充) | |
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
for contour in contours: | |
cv2.drawContours(mask, [contour], -1, 0, -1) | |
# 应用掩码并从原始图像中删除物体 | |
result = cv2.bitwise_and(img, img, mask=mask) | |
# 显示结果 | |
cv2.imshow('Result', result) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() |
在这个示例中,我们首先将照片转换为灰度图像,然后创建一个掩码图像。我们使用cv2.findContours
函数查找物体的轮廓,并将这些轮廓绘制在掩码图像中。最后,我们将掩码应用于原始图像,以删除物体。