import cv2
import numpy as np
import os
for file in os.listdir('/home/lhq/mb'):
img1 = cv2.imread("/home/lhq/mb/{}".format(file))
img = cv2.GaussianBlur(img1,(25,25),15)
ret, thresh = cv2.threshold(img, 254, 255, 0)
thresh = cv2.cvtColor(thresh,cv2.COLOR_BGR2GRAY)
thresh = ~thresh
index = np.where(thresh == 0)
# cv2.imshow('',thresh)
# cv2.waitKey(0)
# exit()
b_channel, g_channel, r_channel = cv2.split(img1)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
# 最小值为0
# alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
alpha_channel[index] = 0
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
cv2.imwrite("/home/lhq/mb1/{}.png".format(file.split('.')[0]), img_BGRA)
import cv2
import numpy as np
import os
for file in os.listdir('/home/lhq/mb'):
img1 = cv2.imread("/home/lhq/mb/{}".format(file))
# img = cv2.GaussianBlur(img1,(25,25),15)
ret, thresh = cv2.threshold(img1, 240, 255, 0)
thresh = cv2.cvtColor(thresh,cv2.COLOR_BGR2GRAY)
thresh = ~thresh
binary = np.zeros(shape=img1.shape[:-1])
contours, heriachy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
# 最后一个参数是像素值,设为-1时,会将整个轮廓都填充为相应的颜色
cv2.drawContours(binary, contours, i, (255), -1)
# cv2.imshow('',binary)
# cv2.waitKey(0)
index = np.where(binary == 0)
b_channel, g_channel, r_channel = cv2.split(img1)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
# 最小值为0
# alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
alpha_channel[index] = 0
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
cv2.imwrite("/home/lhq/mb4/{}.png".format(file.split('.')[0]), img_BGRA)