Python OpenCV:将图像裁剪为内容,并使背景透明

Python OpenCV:将图像裁剪为内容,并使背景透明,python,numpy,opencv,Python,Numpy,Opencv,我有以下图像: 我想将图像裁剪成实际内容,然后使背景(后面的空白)透明。我看到了以下问题:,在查看答案并尝试之后,我得到了以下代码: img=cv.imread(“tmp/”+img+“.png”) 掩码=np.0(img.shape[:2],np.uint8) bgdModel=np.zero((1,65),np.float64) fgdModel=np.zero((1,65),np.float64) rect=(55,55110110) cv.grabCut(img,mask,rect,b

我有以下图像:

我想将图像裁剪成实际内容,然后使背景(后面的空白)透明。我看到了以下问题:,在查看答案并尝试之后,我得到了以下代码:

img=cv.imread(“tmp/”+img+“.png”)
掩码=np.0(img.shape[:2],np.uint8)
bgdModel=np.zero((1,65),np.float64)
fgdModel=np.zero((1,65),np.float64)
rect=(55,55110110)
cv.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv.GC_INIT_WITH_rect)
mask2=np.where((mask==2)|(mask==0),0,1).astype('uint8')
img=img*mask2[:,:,np.newaxis]
plt.imshow(img),plt.colorbar(),plt.show()
但当我尝试此代码时,我得到以下结果:

这不是我要搜索的结果,预期结果:


在Python/OpenCV中,有一种方法可以实现这一点

正如我在评论中提到的,您提供的图像在奶牛周围有一个白色圆圈,然后是一个透明的背景。我已将背景设置为全白色作为输入

输入:


阈值图像:

遮罩:

具有透明背景的裁剪结果:


您的图像在奶牛周围有一个白色圆圈,然后是一个透明背景。这真的是你想要的开始吗?白圈是否要保留?
import cv2
import numpy as np

# read image
img = cv2.imread('cow.png')

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# invert gray image
gray = 255 - gray

# threshold
thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)[1]

# apply close and open morphology to fill tiny black and white holes and save as mask
kernel = np.ones((3,3), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# get contours (presumably just one around the nonzero pixels) 
contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
cntr = contours[0]
x,y,w,h = cv2.boundingRect(cntr)

# make background transparent by placing the mask into the alpha channel
new_img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
new_img[:, :, 3] = mask

# then crop it to bounding rectangle
crop = new_img[y:y+h, x:x+w]

# save cropped image
cv2.imwrite('cow_thresh.png',thresh)
cv2.imwrite('cow_mask.png',mask)
cv2.imwrite('cow_transparent_cropped.png',crop)

# show the images
cv2.imshow("THRESH", thresh)
cv2.imshow("MASK", mask)
cv2.imshow("CROP", crop)
cv2.waitKey(0)
cv2.destroyAllWindows()