如何解决用透明度替换黄色背景图像
我正在尝试从一组此类图像中删除黄色背景:
并使用 opencv 库使用掩码将其替换为透明度。有我的代码:
HSV_RANGES = {
# red is a major color
'red': [
{
'lower': np.array([0,39,64]),'upper': np.array([20,255,255])
},{
'lower': np.array([161,'upper': np.array([180,255])
}
],# yellow is a minor color
'yellow': [
{
'lower': np.array([21,'upper': np.array([40,# green is a major color
'green': [
{
'lower': np.array([41,'upper': np.array([80,# cyan is a minor color
'cyan': [
{
'lower': np.array([81,'upper': np.array([100,# blue is a major color
'blue': [
{
'lower': np.array([101,'upper': np.array([140,# violet is a minor color
'violet': [
{
'lower': np.array([141,'upper': np.array([160,# next are the monochrome ranges
# black is all H & S values,but only the lower 25% of V
'black': [
{
'lower': np.array([0,0]),63])
}
],# gray is all H values,lower 15% of S,& between 26-89% of V
'gray': [
{
'lower': np.array([0,38,228])
}
],# white is all H values,& upper 10% of V
'white': [
{
'lower': np.array([0,229]),255])
}
]
}
def create_mask(hsv_img,colors):
mask = np.zeros((hsv_img.shape[0],hsv_img.shape[1]),dtype=np.uint8)
for color in colors:
for color_range in HSV_RANGES[color]:
mask += cv2.inRange(
hsv_img,color_range['lower'],color_range['upper']
)
return mask
for file_name in os.listdir(fly_dataset):
file_path = os.path.join(fly_dataset,file_name)
image = cv2.imread(file_path)
#remove background
output = image
# Create HSV Image and threshold it into the proper range.
hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV) # Converting color space from BGR to HSV
mask = create_mask(image,['red'])
cv2_imshow(mask)
# Create the output image,using the mask created above. This will perform the removal of all unneeded colors,but will keep a black background.
output = cv2.bitwise_and(image,image,mask=mask)
# Add an alpha channel,and update the output image variable
*_,alpha = cv2.split(output)
dst = cv2.merge((output,alpha))
output = dst
#save image
cv2.imwrite(fly_png + file_name.replace("jpg","png"),output)
然而,我没有成功,因为算法不智能,因此去除了部分苍蝇。有没有人知道改进这个算法的方法,甚至知道解决这个问题的更好方法?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。