删除黑色背景并使python open cv中的grabcut输出透明 [英] Removing black background and make transparent from grabcut output in python open cv

查看:48
本文介绍了删除黑色背景并使python open cv中的grabcut输出透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 python opencv 从抓取输出中删除黑色背景.

I have been trying to remove the black background from the grabcut output using python opencv.

import numpy as np
import cv2

img = cv2.imread(r'myfile_1.png')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (1,1,665,344)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]

cv2.imshow('img',img)
cv2.imwrite('img.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

以上代码是我为保存抓取输出而编写的.请建议,如何去除黑色背景并使其透明?

Above code I had written to save the grabcut output. Please suggest, How I can remove the black background and make it transparent?

推荐答案

我使用以下代码段实现了这一点.

I have achieved this by using the following snippet.

import cv2
file_name = "grab.png"

src = cv2.imread(file_name, 1)
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
b, g, r = cv2.split(src)
rgba = [b,g,r, alpha]
dst = cv2.merge(rgba,4)
cv2.imwrite("test.png", dst)

这篇关于删除黑色背景并使python open cv中的grabcut输出透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆