PIL最佳方式替换颜色? [英] PIL Best Way To Replace Color?

查看:1666
本文介绍了PIL最佳方式替换颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的图片中删除某种颜色,但它不工作,我希望。我试图做同样的事情,如这里所示使用PIL使所有白色像素透明?然而,图像质量是有点有损,所以它留下一个奇怪的彩色像素周围的地方,什么被删除的小鬼。如果所有三个值都低于100,但是因为图像的质量很差,周围的像素甚至不是黑色的,我尝试像改变像素。



有人知道更好的方式与PIL在Python中替换颜色和周围的任何东西?这可能是我可以想到的完全删除对象的唯一可靠的火,但我不能想到一个方法来做到这一点。



图片有一个白色背景和文本是黑色的。让我们只是说,我想从图像中删除文本,而不留下任何文物。



真的会感谢某人的帮助!感谢

解决方案

您需要将图像表示为二维数组。这意味着要么制作像素列表的列表,要么通过一些聪明的数学将1维数组视为2d。然后,对于每个目标像素,您需要找到所有周围的像素。你可以用一个python生成器这样做:

  def targets(x,y):
yield y)#center
yield(x + 1,y)#Left
yield(x-1,y)#Right
yield(x,y + 1)#Above
yield(x,y-1)#低于
yield(x + 1,y + 1)#上面和右边
yield
yield(x-1,y + 1)#上面和左边
yield(x-1,y-1)#左下方



所以,你会这样使用:

  for x in range(width):
for y in range(height):
px = pixels [x] [y]
if px [0] == 255 and px [ 1] == 255 and px [2] == 255:
for i,j in targets(x,y):
newpixels [i] [j] = replacementColor


I am trying to remove a certain color from my image however it's not working as well as I'd hoped. I tried to do the same thing as seen here Using PIL to make all white pixels transparent? however the image quality is a bit lossy so it leaves a little ghost of odd colored pixels around where what was removed. I tried doing something like change pixel if all three values are below 100 but because the image was poor quality the surrounding pixels weren't even black.

Does anyone know of a better way with PIL in Python to replace a color and anything surrounding it? This is probably the only sure fire way I can think of to remove the objects completely however I can't think of a way to do this.

The picture has a white background and text that is black. Let's just say I want to remove the text entirely from the image without leaving any artifacts behind.

Would really appreciate someone's help! Thanks

解决方案

You'll need to represent the image as a 2-dimensional array. This means either making a list of lists of pixels, or viewing the 1-dimensional array as a 2d one with some clever math. Then, for each pixel that is targeted, you'll need to find all surrounding pixels. You could do this with a python generator thus:

def targets(x,y):
    yield (x,y) # Center
    yield (x+1,y) # Left
    yield (x-1,y) # Right
    yield (x,y+1) # Above
    yield (x,y-1) # Below
    yield (x+1,y+1) # Above and to the right
    yield (x+1,y-1) # Below and to the right
    yield (x-1,y+1) # Above and to the left
    yield (x-1,y-1) # Below and to the left

So, you would use it like this:

for x in range(width):
    for y in range(height):
        px = pixels[x][y]
        if px[0] == 255 and px[1] == 255 and px[2] == 255:
            for i,j in targets(x,y):
                newpixels[i][j] = replacementColor

这篇关于PIL最佳方式替换颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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