使用Python/PIL从图像中删除背景色 [英] Remove background colour from image using Python/PIL

查看:1033
本文介绍了使用Python/PIL从图像中删除背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力使它正常工作,但确实遇到了麻烦,因此非常感谢您的帮助.

I've been trying to get this to work and am really having trouble, so would be very grateful for some help.

使用下面的代码,我想将具有指定RGB值的特征更改为白色,并将图像中的所有其他特征更改为黑色(即,基本上从图像中提取特征.不幸的是,尽管我可以将特征设为当我尝试删除背景色时(我一直尝试使用

Using the code below, I want to change the features with the specified RGB values to white, and all the other features in the image black (i.e. basically extracting the features from the image. Unfortunately, although I can make the features I want to 'extract' fine, when I try to remove the background colours (I'd been trying to use

mask2 = ((red != r1) & (green != g1) & (blue != b1))
data[:,:,:4][mask2] = [rb, gb, bb, ab]

但这似乎选择了除红色== r1或绿色== g1等像素以外的任何像素,给我留下的背景图像非常嘈杂".指定的RGB值,还是对背景像素重新着色的更好方法?

but that seems to select any pixels except those with red == r1 OR green == g1 etc, leaving me with a background image that is quite 'noisy'.) Does anyone know a way to literally extract those pixels with the specified RGB values, or a better way to recolour the background pixels?

谢谢

import numpy as np
from PIL import Image

im = Image.open('/home/me/nh09sw.tif')
im = im.convert('RGBA')
data = np.array(im)

r1, g1, b1 = 246, 213, 139 # Original value
rw, gw, bw, aw = 255, 255, 255, 255 # Value that we want to replace features with
rb, gb, bb, ab = 0, 0, 0, 255 #value we want to use as background colour

red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]

mask = ((red == r1) & (green == g1) & (blue == b1))
data[:,:,:4][mask] = [rw, gw, bw, aw]

im = Image.fromarray(data)

im.save('/home/me/nh09sw_recol.tif')

推荐答案

使用np.all()沿第三条轴进行比较.

Use np.all() compare along the third axis.

import numpy as np
from PIL import Image

im = Image.open('my_file.tif')
im = im.convert('RGBA')
data = np.array(im)
# just use the rgb values for comparison
rgb = data[:,:,:3]
color = [246, 213, 139]   # Original value
black = [0,0,0, 255]
white = [255,255,255,255]
mask = np.all(rgb == color, axis = -1)
# change all pixels that match color to white
data[mask] = white

# change all pixels that don't match color to black
##data[np.logical_not(mask)] = black
new_im = Image.fromarray(data)
new_im.save('new_file.tif')

这篇关于使用Python/PIL从图像中删除背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆