简体   繁体   English

使用OpenCV遮罩并平滑图像

[英]Mask and smooth an image using OpenCV

The following code, as explained here , effectively finds the contours of an object in an image, and fills those contours with white, while setting the background to black. 下面的代码,如所解释这里 ,有效地发现一个图像中的对象的轮廓,并且填充那些与轮廓白色,而设置背景为黑色。

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)

Here's an example of what it does: 这是它的一个例子:

Image of a bee => 蜜蜂的形象 =>

在此处输入图片说明

What's a good way to augment the above code such that the exterior contours of the image are smoothed? 扩展上述代码以使图像的外部轮廓平滑的好方法是什么? If possible, I'd like to use a method that makes it possible to specify the gradation of the smoothing. 如果可能的话,我想使用一种可以指定平滑度等级的方法。 I guess that one way to do it would be to apply heavy blurring before applying the masking function, but presumably, there's a better way. 我猜想,一种方法是在应用遮罩功能之前先进行大量模糊处理,但是大概有更好的方法了。

I would look into morphological opening and closing operations. 我将研究形态学的开盘和闭盘操作。 Specifically I would try a morphological close with a nice big disc operator and you'll probably get something close to what you want. 具体来说,我会尝试使用不错的大型光盘运算符进行形态学封闭,您可能会得到接近所需的结果。

They will operate directly on the binary data you've got (much less expensive than blurring) and will likely achieve the effect you're looking for in terms of simplifying or "blurring" the visual outline. 它们将直接对您拥有的二进制数据进行操作(比模糊处理要便宜得多),并且可能会在简化或“模糊”视觉轮廓方面达到您想要的效果。

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

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

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