python和opencv实现抠图

时间:2022-11-23 13:38:39

本文实例为大家分享了python实现抠图的具体代码,供大家参考,具体内容如下

其中使用了opencv中的grabcut方法

直接上代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# encoding:utf-8
# 图像提取
# create by
 
import numpy as np
import cv2
from matplotlib import pyplot as plt
 
img = cv2.imread('1.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
 
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
 
rect = (20, 20, 413, 591)
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 10, cv2.GC_INIT_WITH_RECT)
 
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
img += 255 * (1 - cv2.cvtColor(mask2, cv2.COLOR_GRAY2BGR))
# plt.imshow(img)
# plt.show()
img = np.array(img)
mean = np.mean(img)
img = img - mean
img = img * 0.9 + mean * 0.9
img /= 255
plt.imshow(img)
plt.show()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/sinat_32547403/article/details/53611336