Python 如何使用PIL去除RGB中基于发光的像素?

Python 如何使用PIL去除RGB中基于发光的像素?,python,image,colors,python-imaging-library,Python,Image,Colors,Python Imaging Library,我正试图写一个小故障的艺术程序,让我的图片像沙子一样掉落,我让它为灰度(L)工作。我正在尝试将其转换为颜色,但无法使此代码正常工作。这是我的颜色 #! /usr/bin/python from PIL import Image from random import randint # Sorts img kinda randomly source = Image.open("test.jpg") threshold = 150 img = source.load() blackandwhi

我正试图写一个小故障的艺术程序,让我的图片像沙子一样掉落,我让它为灰度(L)工作。我正在尝试将其转换为颜色,但无法使此代码正常工作。这是我的颜色

#! /usr/bin/python
from PIL import Image
from random import randint

# Sorts img kinda randomly
source = Image.open("test.jpg")
threshold = 150

img = source.load()

blackandwhite = source.convert("L").load()

canvas = Image.new("RGB", source.size)

newimg = canvas.load()
count = source.size[0]

print (source.format)
print (source.size)
print (source.mode)
print ("Threshold: ", threshold)
print ("============================================")

counter = 0 #counter
# do the loop twice because we want to make em fall!
counter = 0
for i in range(0, source.size[0]-1): # loop through every x value
    vert_list = [] #list of this column
    for pix in range(0, source.size[1]-1): #make a list of the column from the b&w img
        color = blackandwhite[i, pix] #for being in color ^^
        vert_list.append( color )

    counter += 1
    if counter % 10 == 0:
        print(counter, "/", count)
    #now remove all pixels brighter than the threshold

    color_vert_list = []
    for x in range(0, len(vert_list)-1):
        if vert_list[x] < threshold:
            color_vert_list.append(img[i, pix]) #add colors darker than something to the color list

    top_spacing = source.size[1] - len(color_vert_list) #height
    for pixel in range(0, len(color_vert_list)):
        newimg[i,pixel + top_spacing] = color_vert_list[pixel] #add em


canvas.save("fall.png") #save

看起来您的问题是您试图从灰度值的索引中获取颜色值(已丢弃),但如果您已丢弃以前的灰度值,且索引不再匹配,则该操作将不起作用

让我们重新开始。与其保留灰度顶点列表和颜色顶点列表并尝试匹配它们,不如保留(灰度,颜色)对列表。像这样:

for pix in range(0, source.size[1]-1): #make a list of the column from the b&w img
    grey = blackandwhite[i, pix]
    color = img[i, pix]
    vert_list.append((grey, color))
现在,您只需更改过滤器以使用灰值对:

vert_list[:] = (x for x in vert_list if threshold > x[0])
newimg[i,pixel + top_spacing] = vert_list[pixel][1]
…并更改
newimg
分配以使用该对中的颜色值:

vert_list[:] = (x for x in vert_list if threshold > x[0])
newimg[i,pixel + top_spacing] = vert_list[pixel][1]
而且(除了更改
画布的模式之外,您已经做对了),这就是您需要做的所有事情


我已经发布了一个完整的实现(在三行上有注释)。

你说的“我让它为RGB工作。我正在尝试将它转换为颜色”是什么意思?RGB是一种颜色格式。我不是。所以,如果你让它为RGB工作,你就完成了。我让它在灰度下工作,只有亮度值。我试图获得相同的结果,但最终的图像使用原始的RGB值。编辑我的帖子来反映这一点。好吧,它做错了什么(理想情况下,哪里出了问题,以及你期望那里发生什么不同)?我不确定哪里出了问题。如果我使用灰度版本,我会得到预期的结果,但这是我在颜色模式下运行它时得到的结果:,尽管我预期的结果与原始输出相同,但颜色相同。我认为它做了某种颜色转换错误?