簡體   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