gpt4 book ai didi

python-3.x - 如何使用OpenCV将白色像素设置为透明

转载 作者:行者123 更新时间:2023-12-02 17:31:05 26 4
gpt4 key购买 nike

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

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)

但这只会产生一个空的情节。

最佳答案

这应该足够了:

The background of the website is white, so "right click" the Output and "open image in new tab" and you'll see that it is transparent :)



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:


Input

  • Output ("right click" >> "open in new tab"):


Output

关于python-3.x - 如何使用OpenCV将白色像素设置为透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com