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

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

问题描述

我正在尝试从我的图像中删除某种颜色,但是它并没有像我希望的那样工作.我试图做与这里看到的相同的事情 使用 PIL 使全白像素透明? 然而,图像质量有点有损,所以它会在被移除的地方留下一些奇怪的彩色像素的鬼影.如果所有三个值都低于 100,我尝试执行诸如更改像素之类的操作,但由于图像质量很差,周围的像素甚至都不是黑色的.

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.

有谁知道在 Python 中使用 PIL 的更好方法来替换颜色及其周围的任何东西?这可能是我能想到的完全移除物体的唯一可靠方法,但我想不出办法做到这一点.

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

推荐答案

您需要将图像表示为二维数组.这意味着要么制作一个像素列表列表,要么将一维数组视为具有一些巧妙数学的二维数组.然后,对于每个定位的像素,您需要找到所有周围的像素.您可以使用 python 生成器执行此操作:

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天全站免登陆