到目前为止,我的代码。我想裁剪图像中的白色。
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)
但是它只会产生一个空图。
答案 0 :(得分: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)
- 输入:
- 输出(“右键单击” >>“在新标签页中打开”):