更改图像的背景和像素颜色

时间:2018-05-21 23:07:05

标签: colors pixel psychopy

对于实验,我想向参与者展示数据库中的绘图,其中包括白色背景上的黑色绘制线条。最后,我只希望以某种颜色显示每个图像的“绘制部分”。所以我希望图像的白色部分变成灰色,因此它与灰色背景无法区分。我想用其他颜色显示图像的黑色部分(实际绘图),例如红色。

我对编程很新,到目前为止我找不到答案。我尝试过几件事,包括下面的两个选项。

有人可以向我展示一个如何更改我附加到此消息的图像颜色的示例吗? 非常感谢! [在此输入图像说明] [1]

    ####### OPTION 1, not working
#picture = Image.open(fname)
fname = exp.get_file('PICTURE_1.png')
picture = Image.open(fname)

# Get the size of the image
width, height = picture.size

# Process every pixel
for x in range(width):
   for y in range(height):
       current_color = picture.getpixel( (x,y) )
       if current_color == (255,255,255): 
           new_color = (255,0,0)
           picture.putpixel( (x,y), new_color)
       elif current_color == (0,0,0):
           new_color2 = (115,115,115)
           picture.putpixel( (x,y), new_color2)
           picture.show()

#picture.show()
win.flip()
clock.sleep(1000)
按照建议的方式实现了更改:TypeError:'int'对象没有属性' getitem '
for x in range(width):
   for y in range(height):
       current_color = picture.getpixel( (x,y) )
       if (current_color[0]<200) and (current_color[1]<200) and (current_color[2]<200):
           new_color = (255,0,0)
           picture.putpixel( (x,y), new_color)
       elif (current_color[0]>200) and (current_color[1]>200) and (current_color[2]>200):
           new_color2 = (115,115,115)
           picture.putpixel( (x,y), new_color2)
           picture.show()

2 个答案:

答案 0 :(得分:1)

您在方案一中的方法基本上是正确的,但这里有一些提示可帮助您使其正常工作:

不应该说if current_color == (255,255,255):,而应该使用 if (current_color[0]>200) and (current_color[1]>200) and (current_color[2]>200):
即使图像的白色部分看起来白色,但像素可能不是正好(255,255,255)。

我以为你想把白色部分变成灰色而黑色部分变成红色?在您的选项一的代码中,行为
if current_color == (255,255,255): new_color = (255,0,0)
将白色像素变为红色。要将黑色像素变为红色,它应为if current_color == (0,0,0)

如果在进行这些更改后代码仍然无效,您可以尝试创建与原始图像尺寸相同的新图像,并为新图像添加像素,而不是编辑原始图像中的像素。 / p>

此外,如果您能告诉我们您运行代码时实际发生的情况,将会有所帮助。是否有错误消息,或是显示的图像但图像不正确?你能附上一个例子输出吗?

更新: 我摆弄你的代码,让它做你想做的事。这是我最终得到的代码:

import PIL
from PIL import Image

picture = Image.open('image_one.png')

# Get the size of the image
width, height = picture.size

for x in range(width):
   for y in range(height):
       current_color = picture.getpixel( (x,y) )
       if (current_color[0]<200) and (current_color[1]<200) and (current_color[2]<200):
           new_color = (255,0,0)
           picture.putpixel( (x,y), new_color)
       elif (current_color[0]>200) and (current_color[1]>200) and (current_color[2]>200):
           new_color2 = (115,115,115)
           picture.putpixel( (x,y), new_color2)
picture.show()

如果您将此代码复制并粘贴到脚本中并在与图像相同的文件夹中运行它,它应该可以正常工作。

答案 1 :(得分:1)

除了循环每个像素并更改其值之外,还有更有效的方法。

由于您似乎正在使用PsychoPy,因此您可以将图像保存为具有透明背景的灰度图像。通过使用灰度图像格式,您可以让PsychoPy通过改变刺激颜色设置将线条的颜色更改为您想要的任何颜色。通过使用透明背景,您在线条后面看到的任何内容都将显示出来,因此您可以选择使用白色正方形,不同正方形或无正方形。通过这种方法,所有颜色的计算都在显卡上完成,并且每帧都可以更改,没有任何问题。

如果出于某种原因你需要以PsychoPy本身不允许的方式改变图像(如果处理速度很重要)那么你应该尝试在一次操作中改变所有像素(使用numpy数组) )而不是for循环中一次只有一个像素。

相关问题