繁体   English   中英

使用OpenCV遮罩并平滑图像

[英]Mask and smooth an image using OpenCV

下面的代码,如所解释这里 ,有效地发现一个图像中的对象的轮廓,并且填充那些与轮廓白色,而设置背景为黑色。

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)

这是它的一个例子:

蜜蜂的形象 =>

在此处输入图片说明

扩展上述代码以使图像的外部轮廓平滑的好方法是什么? 如果可能的话,我想使用一种可以指定平滑度等级的方法。 我猜想,一种方法是在应用遮罩功能之前先进行大量模糊处理,但是大概有更好的方法了。

我将研究形态学的开盘和闭盘操作。 具体来说,我会尝试使用不错的大型光盘运算符进行形态学封闭,您可能会得到接近所需的结果。

它们将直接对您拥有的二进制数据进行操作(比模糊处理要便宜得多),并且可能会在简化或“模糊”视觉轮廓方面达到您想要的效果。

在阈值化之前,您还可以使用大内核(例如7x7或15x15)使高斯模糊。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM