繁体   English   中英

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

[英]Python OpenCV: Crop image to contents, and make background transparent

我有以下图片:

图片 1

我想将图像裁剪为实际内容,然后使背景(后面的空白区域)透明。 我看到以下问题: How to crop image based on contents (Python & OpenCV)? ,在查看答案并尝试之后,我得到了以下代码:

img = cv.imread("tmp/"+img+".png")
mask = np.zeros(img.shape[:2],np.uint8)

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

rect = (55,55,110,110)
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()


阈值图像:

在此处输入图片说明

面具:

在此处输入图片说明

透明背景的裁剪结果:

在此处输入图片说明

鉴于要转换为透明的背景的 BGR 通道为白色(如您的图像) ,您可以执行以下操作:

import cv2
import numpy as np

img = cv2.imread("cat.png")
img[np.where(np.all(img == 255, -1))] = 0
img_transparent = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
img_transparent[np.where(np.all(img == 0, -1))] = 0

cv2.imshow("transparent.png", img_transparent)

输入图像:

在此处输入图像描述

Output 图片:

在此处输入图像描述

我们可以通过点击第二张图片来判断它是透明的; 透明背景将显示为灰色(至少在 Firefox 中)

对我有用的是:

original_image = cv2.imread(path)    
#Converting the bgr image to an image with the alpha channel
original_image = cv2.cvtColor(original_image, cv2.BGR2BGRA)
#Transforming every alpha pixel to a transparent pixel.
original_image[np.where(np.all(original_image == 255, -1))] = 0

然后写入图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM