Python-OpenCV中的圖像處理-GrabCut算法交互式前景提取
cv2.grabCut(img: Mat, mask: typing.Optional[Mat], rect, bgdModel, fgdModel, iterCount, mode=…)文章來源:http://www.zghlxwxcb.cn/news/detail-658584.html
- img:輸入圖像
- mask:掩模圖像,用來確定那些區(qū)域是背景,前景,可能是前景/背景等。
可以設(shè)置為: cv2.GC_BGD,cv2.GC_FGD,cv2.GC_PR_BGD,cv2.GC_PR_FGD,或者直接輸入 0,1,2,3 也行。 - rect :包含前景的矩形,格式為 (x,y,w,h)
- bdgModel, fgdModel:算法內(nèi)部使用的數(shù)組. 你只需要創(chuàng)建兩個大小為 (1,65),數(shù)據(jù)類型為 np.float64 的數(shù)組。
- iterCount :算法的迭代次數(shù)
- mode :可以設(shè)置為 cv2.GC_INIT_WITH_RECT 或 cv2.GC_INIT_WITH_MASK,也可以聯(lián)合使用。這是用來確定我們進行修改的方式,矩形模式或者掩模模式。
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = img = cv2.imread('./resource/opencv/image/messi5.jpg', cv2.IMREAD_COLOR)
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (50, 50, 450, 450)
# 函數(shù)返回值是更新的 mask, bgdModel, fgdModel
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2) | (mask==0), 0, 1).astype('uint8')
img = img*mask2[:, :, np.newaxis]
plt.imshow(img), plt.colorbar(), plt.show()
文章來源地址http://www.zghlxwxcb.cn/news/detail-658584.html
到了這里,關(guān)于OpenCV-Python中的圖像處理-GrabCut算法交互式前景提取的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!