我有一个橙色和白色背景的图像。我想让白色的背景透明。下面的代码使用grabcut来制作一个掩码。然后我将图像分割成rgb通道,并在alpha通道上应用遮罩。从下面的图片中可以看到,后抓取和遮罩图片都可以。我还没弄清楚如何将掩模应用到alpha通道上。感谢您的建议。在im = cv2.imread(sourceimagefile)
cv2.imshow('original',im)
mask = np.zeros(im.shape[:2],np.uint8)
rect = (box[0][0], box[0][1], box[0][2]-box[0][0], box[0][3]-box[0][1])
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
cv2.grabCut(im,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
if len(np.where((mask==3)|(mask==1))[0])>0:
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
mask2 = np.repeat(mask2[:,:,np.newaxis],3,axis=2)
else:
mask2 = np.zeros_like(im)
mask2[box[0][1]:box[0][3],box[0][0]:box[0][2],:] = 1
im2 = im*mask2
cv2.imshow('post-grabcut',im2)
minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(mask)
flag, mask = cv2.threshold(mask, maxVal-1, 255, cv2.cv.CV_THRESH_BINARY)
cv2.imshow("mask", mask)
b, g, r = cv2.split(im2)
img_RGBA = cv2.merge((b, g, r, mask))
cv2.imshow("final",img_RGBA)