如何使用OpenCV python删除背景for this image
我使用抓取剪切方法删除背景,但没有得到预期的结果。谁能帮助我找到更好的解决方案?
import cv2
import numpy as np
from matplotlib import pyplot as plt
image_bgr = cv2.imread('/home/user/sample_images/4.jpg')
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
rectangle = (0, 10, 400, 600)
mask = np.zeros(image_rgb.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
cv2.grabCut(image_rgb, # Our image
mask, # The Mask
rectangle, # Our rectangle
bgdModel, # Temporary array for background
fgdModel, # Temporary array for background
10, # Number of iterations
cv2.GC_INIT_WITH_RECT) # Initiative using our rectangle
mask_2 = np.where((mask==2) | (mask==0), 0, 1).astype('uint8')
image_rgb_nobg = image_rgb * mask_2[:, :, np.newaxis]
plt.imshow(image_rgb_nobg), plt.axis("off")
plt.show()