以下代码,解释为here ,有效地找到图像中对象的轮廓,并用白色填充这些轮廓,同时将背景设置为黑色。
import cv2
import numpy as np
# Read image
im_in = cv2.imread('bee-02.png', cv2.IMREAD_GRAYSCALE)
th, im_th = cv2.threshold(im_in, 250, 255, cv2.THRESH_BINARY_INV)
# Copy the thresholded image.
im_floodfill = im_th.copy()
# Mask used to flood filling.
h, w = im_th.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0,0), 255)
# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
# Combine the two images to get the foreground.
im_out = im_th | im_floodfill_inv
# Display images.
cv2.imshow("Foreground", im_out)
cv2.waitKey(0)
下面是它的作用的示例:
增强上述代码以使图像的外部轮廓平滑的好方法是什么?如果可能的话,我想使用一种可以指定平滑渐变的方法。我猜想,一种方法是在应用 mask 功能之前应用严重模糊,但大概有更好的方法。
最佳答案
我会调查morphological opening and closing运营。具体来说,我会尝试使用一个漂亮的大圆盘运算符进行形态关闭,您可能会得到接近您想要的东西。
它们将直接对您获得的二进制数据进行操作(比模糊要便宜得多),并且可能会在简化或“模糊”视觉轮廓方面实现您正在寻找的效果。
关于python - 使用 OpenCV 对图像进行 mask 和平滑处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41385609/