簡體   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