|
2 | 2 | __author__ = 'play4fun'
|
3 | 3 | """
|
4 | 4 | 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 | +模式。 |
5 | 15 | """
|
6 | 16 |
|
7 | 17 | import numpy as np
|
8 | 18 | import cv2
|
9 | 19 | from matplotlib import pyplot as plt
|
10 | 20 |
|
11 | 21 | img = cv2.imread('../data/messi5.jpg')
|
| 22 | + |
12 | 23 | mask = np.zeros(img.shape[:2], np.uint8)
|
13 | 24 | bgdModel = np.zeros((1, 65), np.float64)
|
14 | 25 | fgdModel = np.zeros((1, 65), np.float64)
|
15 | 26 | rect = (50, 50, 450, 290)
|
| 27 | + |
16 | 28 | # 函数的返回值是更新的 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 | + |
18 | 32 | mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
|
19 | 33 | img = img * mask2[:, :, np.newaxis]
|
| 34 | + |
20 | 35 | plt.imshow(img), plt.colorbar(), plt.show()
|
0 commit comments