Image conversion to black and white

Hi,

Does anyone know how to change the color of an image to black and white?

Do you mean true black and white (i.e. just two discrete colour levels), or greyscale (256 levels of grey between black and white)?

Greyscale - sorry for the lack of description

PsychoPy bundles the Python Imaging Library (PIL), which allows for this sort of manipulation. So let’s say you have a colour image file on disk, you could read it into a PIL Image object and convert it to greyscale. You can then pass that image object to create a PsychoPy ImageStim. e.g

from psychopy import visual, event, core
from PIL import Image

# use PIL:
img_colour = Image.open('your_image_file.jpg')
img_grey = img_colour.convert('L') # convert to greyscale
# see https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.convert

# now do the psychopy stuff:
win = visual.Window()
stim_colour = visual.ImageStim(win, image = img_colour)
stim_grey = visual.ImageStim(win, image = img_grey)

while not event.getKeys():
    
    for stimulus in [stim_colour, stim_grey]:
        stimulus.draw()
        win.flip()
        core.wait(0.5)

# more PIL magic:
img_colour.save('spider.gif', format='GIF', append_images=[img_grey], save_all=True, duration=500, loop=0)

would give you this (without the GIF dithering artefacts on-screen):

spider

You could write a script to batch convert all of your images to grey scale so that this doesn’t have to be done every time you run the experiment. i.e. open each image, convert it, and then save a copy back to disk, using this function:

img_grey.save('construct_a_greyscale_version_filename.jpg')