如何使用OpenCV将白色像素设置为透明

问题描述 投票:0回答:1

我的代码到目前为止。我想在图像中裁剪出白色。

import cv2
import numpy as np

image = cv2.imread('myimage.jpg')
image2 = np.ones((255, 255, 4))
for i in range(255):
    for j in range(255):
        if image[i,j,0] == 255: 
            image2[i, j, :] = np.append(image[i, j, :], 1)
        else:
            image2[i, j, :] = np.append(image[i, j, :], 1)

cv2.imwrite('image2.png', image2)

但它只会产生一个空图。

python-3.x opencv
1个回答
0
投票

这应该足够了:

网站的背景是白色的,所以“右键单击”输出和“在新标签中打开图像”,你会发现它是透明的:)

import cv2
import numpy as np

# read the image
image_bgr = cv2.imread('image_bgr.png')
# get the image dimensions (height, width and channels)
h, w, c = image_bgr.shape
# append Alpha channel -- required for BGRA (Blue, Green, Red, Alpha)
image_bgra = np.concatenate([image_bgr, np.full((h, w, 1), 255, dtype=np.uint8)], axis=-1)
# create a mask where white pixels ([255, 255, 255]) are True
white = np.all(image_bgr == [255, 255, 255], axis=-1)
# change the values of Alpha to 0 for all the white pixels
image_bgra[white, -1] = 0
# save the image
cv2.imwrite('image_bgra.png', image_bgra)
  • 输入:

Input

  • 输出(“右键单击”>>“在新标签页中打开”):

Output

© www.soinside.com 2019 - 2024. All rights reserved.