在一个实验中,我想展示参与者从一个数据库中画出的图画,其中包括在白色背景上绘制的黑色线条。最后,我只想展示一个特定颜色的每幅图像的“绘制部分”是什么。所以我希望图像的白色部分是灰色的,所以它和灰色背景是无法区分的。我想用其他颜色显示图像的黑色部分(实际绘图),例如红色。
我对编程很陌生,到目前为止我还没有找到答案。我已经尝试了几件事,包括下面的两个选项。
有人能给我举个例子,说明如何改变我附在这封信上的图片的颜色吗?这将是非常感谢!在这里输入图像描述
####### 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()发布于 2018-05-21 23:38:31
您在选项一中的方法基本上是正确的,但以下是一些帮助您使其正常工作的提示:
与其说if current_color == (255,255,255):,不如把
if (current_color[0]>200) and (current_color[1]>200) and (current_color[2]>200):
虽然图像的白色部分看起来是白色的,但像素可能不是完全(255,255)。
我以为你想把白色部分变成灰色,黑色部分变成红色?在选项一的代码中,行
if current_color == (255,255,255): new_color = (255,0,0)
将变成白色像素红色。要将黑色像素变为红色,应该是if current_color == (0,0,0)。
如果您的代码在进行这些更改时仍然无法工作,则可以尝试创建与原始图像相同尺寸的新图像,并将像素添加到新图像中,而不是编辑原始图像中的像素。
此外,如果您能够告诉我们在运行代码时实际发生了什么,这也会有所帮助。是否有错误信息,或是否显示了图像,但图像不正确?你能附上一个输出的例子吗?
更新:我摆弄了你的代码,让它做你想做的事情。下面是我最后得到的代码:
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()如果您将此代码复制并粘贴到脚本中,并在与图像相同的文件夹中运行,则该代码应该可以工作。
发布于 2018-05-22 10:17:50
有比循环遍历每个像素和改变其值更有效的方法来做到这一点。
因为看起来您使用的是PsychoPy,所以可以使用透明的背景将图像保存为灰度。通过使用灰度图像格式,只需更改刺激颜色设置,PsychoPy就可以将线条的颜色更改为任何您想要的颜色。通过使用透明的背景,你在线条后面看到的任何东西都会显示出来,这样你就可以选择一个白色的正方形,一个不同的正方形,或者根本没有正方形。通过这种方法,所有颜色的计算都是在显卡上进行的,并且可以在没有问题的情况下对每一个帧进行更改。
如果由于某种原因,您需要以PsychoPy本质上不允许的方式更改图像(如果处理速度很重要),那么您应该尝试在一个操作(使用numpy数组)中更改所有像素,而不是在for -循环中一次更改一个像素。
https://stackoverflow.com/questions/50457658
复制相似问题