Skip to content

Commit 6107d70

Browse files
committed
update ch28
1 parent 2e840b6 commit 6107d70

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

ch28-使用GrabCut算法进行交互式前景提取/grabCut.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,34 @@
22
__author__ = 'play4fun'
33
"""
44
create time:15-10-25 下午12:20
5+
6+
7+
img - 输入图像
8+
• mask-掩模图像 用来确定 些区域是背景 前景 可能是前景/背景等。 可以 置为 cv2.GC_BGD,cv2.GC_FGD,cv2.GC_PR_BGD,cv2.GC_PR_FGD 或者直接 入 0,1,2,3 也 。
9+
• rect - 包含前景的矩形 格式为 (x,y,w,h)
10+
• bdgModel, fgdModel - 算法内 使用的数组. 你只 创建两个大
11+
小为 (1,65) 数据类型为 np.float64 的数组。
12+
• iterCount - 算法的迭代次数
13+
• mode可以 置为cv2.GC_INIT_WITH_RECT或cv2.GC_INIT_WITH_MASK 也可以联合使用。 是用来确定我们 修改的方式 矩形模式或者掩模
14+
模式。
515
"""
616

717
import numpy as np
818
import cv2
919
from matplotlib import pyplot as plt
1020

1121
img = cv2.imread('../data/messi5.jpg')
22+
1223
mask = np.zeros(img.shape[:2], np.uint8)
1324
bgdModel = np.zeros((1, 65), np.float64)
1425
fgdModel = np.zeros((1, 65), np.float64)
1526
rect = (50, 50, 450, 290)
27+
1628
# 函数的返回值是更新的 mask, bgdModel, fgdModel
17-
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
29+
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, iterCount=5, mode=cv2.GC_INIT_WITH_RECT)
30+
#迭代 5 次
31+
1832
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
1933
img = img * mask2[:, :, np.newaxis]
34+
2035
plt.imshow(img), plt.colorbar(), plt.show()

ch28-使用GrabCut算法进行交互式前景提取/grabCut2.py

+11-5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22
__author__ = 'play4fun'
33
"""
44
create time:15-10-25 下午12:20
5+
实 上我是怎么做的呢 我们使用图像编 件打开 入图像
6+
添加一个 图层
7+
使用笔刷工具在 的地方使用白色绘制 比如头发 子 球等
8+
使 用 色笔刷在不 的地方绘制 比如 logo 草地等 。
9+
然后将其他地方用灰 色填充 保存成新的掩码图像。
10+
在 OpenCV 中导入 个掩模图像 根据新的 掩码图像对原来的掩模图像 编 。
511
"""
612

713
import numpy as np
@@ -20,12 +26,12 @@
2026
plt.imshow(img), plt.colorbar(), plt.show()
2127

2228
# newmask is the mask image I manually labelled
23-
newmask = cv2.imread('../data/newmask.jpg',0)
29+
newmask = cv2.imread('../data/newmask.jpg', 0)
2430
# whereever it is marked white (sure foreground), change mask=1
2531
# whereever it is marked black (sure background), change mask=0
2632
mask[newmask == 0] = 0
2733
mask[newmask == 255] = 1
28-
mask, bgdModel, fgdModel = cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)
29-
mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
30-
img = img*mask[:,:,np.newaxis]
31-
plt.imshow(img),plt.colorbar(),plt.show()
34+
mask, bgdModel, fgdModel = cv2.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK)
35+
mask = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
36+
img = img * mask[:, :, np.newaxis]
37+
plt.imshow(img), plt.colorbar(), plt.show()

0 commit comments

Comments
 (0)