Skip to content

Commit c802254

Browse files
authored
Add files via upload
1 parent f0f7b26 commit c802254

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# -*- coding: utf-8 -*-
2+
#By:Eastmount CSDN 2021-08-20
3+
import cv2
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
import matplotlib
7+
8+
#读取图像
9+
img = cv2.imread('nv.png')
10+
11+
#灰度化处理图像
12+
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
13+
14+
#设置掩码、fgbModel、bgModel
15+
mask = np.zeros(img.shape[:2], np.uint8)
16+
bgdModel = np.zeros((1,65), np.float64)
17+
fgdModel = np.zeros((1,65), np.float64)
18+
19+
#矩形坐标
20+
rect = (100, 100, 500, 800)
21+
22+
#图像分割
23+
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5,
24+
cv2.GC_INIT_WITH_RECT)
25+
26+
#设置新掩码:0和2做背景
27+
mask2 = np.where((mask==2)|(mask==0), 0, 1).astype('uint8')
28+
29+
#设置字体
30+
matplotlib.rcParams['font.sans-serif']=['SimHei']
31+
32+
#显示原图
33+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
34+
plt.subplot(1,2,1)
35+
plt.imshow(img)
36+
plt.title(u'(a)原始图像')
37+
plt.xticks([]), plt.yticks([])
38+
39+
#使用蒙板来获取前景区域
40+
img = img*mask2[:, :, np.newaxis]
41+
plt.subplot(1,2,2)
42+
plt.imshow(img)
43+
plt.title(u'(b)目标图像')
44+
plt.colorbar()
45+
plt.xticks([]), plt.yticks([])
46+
plt.show()

0 commit comments

Comments
 (0)