Code Monkey home page Code Monkey logo

pyllusion's Introduction

Tests

A Parametric Framework to Generate Visual Illusions using Python

Overview

Visual illusions are fascinating phenomena that have been used and studied by artists and scientists for centuries, leading to important discoveries about how conscious perception is generated by the brain. Instead of crafting them by hand, Pyllusion offers a framework to manipulate and generate illusions in a systematic way.

The parametric approach implemented in this software proposes to describe illusions using a set of parameters, such as for instance the difference and illusion strength. These two parameters can be modulated to independently impact either the objective difference of the core components of the illusion (e.g., the difference between the two segments in the Müller-Lyer illusion) or the intensity of the illusion effect (e.g., the angle of the “distractors” arrows).

Describing illusions using a set of parameters aims at fostering reproducible science, allowing neuroscientists to easily report, generate and manipulate similar stimuli regardless of the display format and software.

Installation

pip install https://github.com/RealityBending/Pyllusion/zipball/master

You can also find the installation instructions for Python 3 here.

Contribution

You have some ideas? Want to improve things, add new illusions, and help us shake people’s brain? Let us know, we would be very happy to have you on board ☺️.

Share Your Data

If you have used Pyllusion in your experiments, and have made your scripts and data open access, feel free to also reference the link to your data by opening an issue with the Experiment Report template.

Citation

You can cite the package as follows:

Features

Delboeuf Illusion

The Delboeuf illusion is an optical illusion of relative size perception, where circles of identical size appear as different because of their surrounding context. The illusion was named for the Belgian philosopher, mathematician, experimental psychologist, hypnotist, and psychophysicist Joseph Remi Leopold Delboeuf (1831–1896), who created it in 1865.

import pyllusion

delboeuf = pyllusion.Delboeuf(illusion_strength=3)
delboeuf.to_image()

Ebbinghaus Illusion

The Ebbinghaus illusion is an optical illusion of relative size perception, where circles of identical size appear as different because of their surrounding context (the right red circle appears as smaller because its surrounding circle is larger). The illusion was named after its creator the German psychologist Hermann Ebbinghaus (1850–1909), though it got popularized by Edward B. Titchener in a 1901 textbook of experimental psychology.

The Ebbinghaus illusion is considered a high-level integration illusion (King et al., 2017) which has been considered relatively unaffected amongst schizophrenics (as compared to healthy controls), who have problems in contextual processing of visual stimuli. Specifically, greater disorganized schizophrenia symptoms are related to a higher resistance towards the Ebbinghaus illusion (Uhlhaas et al., 2006). Reduced sensitivity of schizophrenics to this illusion has been used to reflect how prior knowledge influences perceptual organization to a lesser extent, i.e., reduced top-down influence, in schizophrenia (Silverstein & Keane, 2011).

ebbinghaus = pyllusion.Ebbinghaus(illusion_strength=2)
ebbinghaus.to_image()

Müller-Lyer Illusion

The Müller-Lyer illusion is an optical illusion causing the participant to perceive two segments as being of different length depending on the shape of the arrows. The illusion was named after its creator the erman sociologist Franz Carl Müller-Lyer (1857–1916) in 1889.

The Müller-Lyer illusion is a high-level integration illusion requiring contextual processing by the brain (King et al., 2017). The effect of this illusion in schizophrenics appears to be more mixed, with some studies finding greater resistance to it (e.g., Parnas et al., 2001) and others showing increased susceptibility (e.g., Kantrowitz et al., 2009). There is some evidence that susceptibility to the Müller-Lyer illusion is negatively correlated with autistic traits in the typical population (but not with the Ebbinghaus nor the Ponzo illusion) (Chouinard et al., 2013).

mullerlyer = pyllusion.MullerLyer(illusion_strength=30)
mullerlyer.to_image()

Ponzo Illusion

The Ponzo illusion is an optical illusion of relative size perception, where horizontal lines of identical size appear as different because of their surrounding context (the top line appear as longer, as it is interepreted as being in the distance). The illusion was named after its creator the Italian psychologist Mario Ponzo (1882–1960) in 1911, who suggested that the human mind judges an object’s size based on its background.

Ponzo illusion is considered a high-level integration illusion as it is cognitively demanding in the sense that depth cues have to be correctly interpreted to signal changes in visual distance (King et al., 2017), requiring higher-level cortical processes (Song et al., 2011). Similar to the Ebbinghaus illusion, it is also shown to have less effect in biasing perception in schizophrenic subjects (Kantrowitz et al., 2009).

ponzo = pyllusion.Ponzo(illusion_strength=20)
ponzo.to_image()

Vertical–horizontal Illusion

The vertical–horizontal illusion illustrates the tendency for observers to overestimate the length of a vertical line relative to a horizontal line of the same length (Shipley et al., 1949).

verticalhorizontal = pyllusion.VerticalHorizontal(illusion_strength=-90)
verticalhorizontal.to_image()

Zöllner Illusion

The Zöllner illusion is an optical illusion, where horizontal lines are perceived as not parallel because of their background. It is named after its discoverer, the German astrophysicist Johann Karl Friedrich Zöllner in 1860.

zollner = pyllusion.Zollner(illusion_strength=75)
zollner.to_image()

Rod and Frame Illusion

The Rod and frame illusion is an optical illusion causing the participant to perceive the rod to be oriented congruent with the orientation of the frame.

rodframe = pyllusion.RodFrame(illusion_strength=-11)
rodframe.to_image()

Poggendorff Illusion

The Poggendorff illusion is an optical illusion that involves the misperception of the position of one segment of a transverse line that has been interrupted by the contour of an intervening structure. It is named after Johann Christian Poggendorff who discovered in Zöllner’s illusion after 1860. The magnitude of the illusion depends on the properties of the obscuring pattern and the nature of its borders.

poggendorff = pyllusion.Poggendorff(illusion_strength=-50)
poggendorff.to_image()

Simultaneous Contrast illusion

A neutral gray target will appear lighter or darker than it does in isolation when compared to, respectively, a dark gray or light gray target. Simultaneous contrast, identified by Michel Eugène Chevreul, refers to the manner in which the colors of two different objects affect each other.

In the image here, the two inner rectangles are exactly the same shade of grey, but the upper one appears to be a lighter grey than the lower one due to the background provided by the outer rectangles.

contrast = pyllusion.Contrast(illusion_strength=-50)
contrast.to_image()

White Illusion

White’s illusion is a brightness illusion in which rectangles of the same grey color are perceived of different luminance depending on their background.

white = pyllusion.White(illusion_strength=100)
white.to_image()

Kanizsa Square

The Kanizsa Square is an illusory contour illusion. See Keane et al., 2019.

Some studies have tested the effect of the Kanizsa Square in individuals with schizophrenia, but the finding of greater resistance to the illusion is not robust (King et al., 2017).

  • TO DO (consider helping!)

Autostereograms

Autostereograms are images made of a pattern that is horizontally repeated (with slight variations) which, when watched with the appropriate focus, will generate an illusion of depth.

For instance, in the image below, the autostereogram automatically adds a guide (you can disable it by setting guide=False), the two red dots. Look at them and relax your eyes until you see a new red dot between them two. Then, try focusing on this new red dot until it gets very sharp and until your eyes stabilize. You should then be able to perceive the letters 3D as carved in the figure

It can take a bit of time to “get there”, but once you are used to it, it’s a mind-blowing experience 🤯

autostereograms = pyllusion.Autostereogram(stimulus="3D", width=1600, height=900)
autostereograms.draw()

The function is highly customisable, and we can use a black and white image as a depth mask (in this case, the picture of a skull that you will see as emerging from the background), and customise the pattern used by providing another function (here, the image_circles() function to which we can provide additional arguments like blackwhite, the number of circles n, their size range and their transparency with alpha).

autostereograms = pyllusion.Autostereogram(stimulus="docs/img/depthmask.png",
                   pattern=pyllusion.image_circles,
                   color="blackwhite",
                   alpha=0.75,
                   size_min=0.005,
                   size_max=0.03,
                   n=1000)
autostereograms.draw()

Pareidolia

Pareidolia is the tendency to incorrectly perceive of a stimulus as an object pattern or meaning known to the observer. Liu et al. (2014), in their study “Seeing Jesus in toast”, famously (the study got awarded an Ignobel prize) investigated the correlates of face pareidolia by blending images of faces with noise-like images.

Blending of images can be achieved: as followed

pareidolia = pyllusion.Pareidolia(pattern="docs/img/snake.png",
                                 n=[20, 300, 4000],
                                 sd=[4, 2, 1],
                                 weight=[3, 2, 1],
                                 alpha=80,
                                 blur=0.5)
pareidolia.draw()

Transparency From Motion (TFM)

In visual perception, the kinetic depth effect refers to the phenomenon whereby the three-dimensional structural form of an object can be perceived when the object is moving (Wallach & O’Connell, 1953; Mamassian & Wallace, 2010). One of its derivative is the Transparency-From-Motion illusion, consisting in the superposition of two dot clouds moving in different directions that results in the perception of two transparent layers (See ; Schütz, 2014; Wexler et al., 2015; Schütz & Mamassian, 2016 and http://lab-perception.org/demo/p/tfm for a demo).

parameters = pyllusion.motiontransparency_parameters(angle=45)
images = pyllusion.motiontransparency_images(parameters)

pyllusion.images_to_gif(images, path="Transparency_From_Motion.gif", fps=parameters["FPS"])

Pinna illusion

See also Zeljic et al., 2021.

  • TO DO (consider helping!)

Monnier-Shevell illusion

See also David Novick’s tweets here, and here.

  • TO DO (consider helping!)

PsychoPy Integration

Pyllusion can be easily integrated into PsychoPy for running experiments as well!

# Load packages
import pyllusion
from psychopy import visual, event

# Create parameters
delboeuf = pyllusion.Delboeuf(illusion_strength=1, difference=2)

# Initiate Window
window = visual.Window(size=[1920, 1080], winType='pygame',
                       color='white', fullscr=False)

# Display illusion
delboeuf.to_psychopy(window)

# Refresh and close window
window.flip()
event.waitKeys()  # Press any key to close
window.close()

References

Bertamini, M. (2017). Programming visual illusions for everyone. Springer.

Chouinard, P. A., Noulty, W. A., Sperandio, I., & Landry, O. (2013). Global processing during the Müller-Lyer illusion is distinctively affected by the degree of autistic traits in the typical population. Experimental Brain Research, 230(2), 219–231.

Kantrowitz, J. T., Butler, P. D., Schecter, I., Silipo, G., & Javitt, D. C. (2009). Seeing the world dimly: The impact of early visual deficits on visual experience in schizophrenia. Schizophrenia Bulletin, 35(6), 1085–1094. doi:10.1093/schbul/sbp100

King, D. J., Hodgekins, J., Chouinard, P. A., Chouinard, V. A., & Sperandio, I. (2017). A review of abnormalities in the perception of visual illusions in schizophrenia. Psychonomic bulletin & review, 24(3), 734-751.

Parnas, J., Vianin, P., Saebye, D., Jansson, L., Volmer-Larsen, a, & Bovet, P. (2001). Visual binding abilities in the initial and advanced stages of schizophrenia. Acta Psychiatrica Scandinavica, 103(3), 171–180. doi:10.1034/j.1600-0447.2001.00160.x

Silverstein, S. M., & Keane, B. P. (2011). Perceptual organization impairment in schizophrenia and associated brain mechanisms: Review of research from 2005 to 2010. Schizophrenia Bulletin, 37(4), 690–699. doi:10.1093/schbul/sbr052

Song, C., Schwarzkopf, D. S., & Rees, G. (2011). Interocular induction of illusory size perception. BMC Neuroscience 27, 12(1).

Uhlhaas, P. J., Phillips, W. A., Schenkel, L. S., & Silverstein, S. M. (2006b). Theory of mind and perceptual context‐processing in schizophrenia. Cognitive Neuropsychiatry, 11(4), 416–436.

pyllusion's People

Contributors

dominiquemakowski avatar tam-pham avatar zen-juen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyllusion's Issues

Practical considerations when using Illusions

regarding limitations I think we could help with the aim of standardising things by including a ‘log/lab book’ feature in PyIllusion. For example, if someone is running the rod and frame experiment best practice would dictate that the centre of the display should be surrounded with a round occluder (imagine a cardboard cut-out of a doughnut shape) so that no straight edges are in the field of vision. Also, it would potentially be of interest if the room where the experiment was conducted was dimly lit, or what was the viewing distance and was there a chinrest used, or record the measured luminance etc. So, I’m thinking for each given illusion already packaged with PyIllusion we could have a small checklist that could be altered with ease in script (or via check boxes on the display). That way parameters that cannot be controlled for by PyIllusion may be documented. I guess this should be made optional for a given user so as to not put people off using the package but we could encourage and recommend it be used. It’d be not dissimilar to methods in a manuscript but would be nice if this information was contained in script/output. It could be cross-referenced against the methods and indeed would save having to dig through the manuscript for details too. Just a thought. We could even include a list of considerations for each illusion as a function call in Python.

Ponzo Illusion errors

I considered raising this as a bug but not sure it should be classed as one since it makes sense that it is happening.

The Ponzo illusion: anything > 25 for the 'illusion_strength' parameter sees either the top target line draw over the flanker contextual lines, or as the number increases further, sees the contextual lines dip below the top target line. It would be cool if the flanker lines moved up the y-axis (or the target lines moved down the y-axis) to accommodate these extreme values.

I'd imagine it would be a relatively easy adjustment to make?

Additionally, when the 'illusion_strength' value is set to '90' it returns an error whereas >90 does not.

This is the error t returns: 'SystemError: <method 'draw_lines' of 'ImagingDraw' objects> returned a result with an error set'

Brilliant job all round with this package. Keep up the good work!

Provide full example to get image

It is perhaps an user issue. I am using Spyder 4.0.1 with Python 3.7.9 on Windows 10. I am trying to create the images provided by you to analyze optical illusion. I have installed pyllusion and executed this code from your sample. It runs without error but I do not see any images. Can you provide a complete example on how to use this library?

import pyllusion as ill

parameters = ill.delboeuf_parameters(illusion_strength=3)
ill.delboeuf_image(parameters)

Manuscript Revision Checklist - Minor

  • p.1 l.13: "Helmholtz" is written twice, and "1856" three times
  • p.1 l.44: "more practical utility" understates goal of the paper, rephrase/elaborate
    • Zen: "illusions can serve a more practical utility" to "illusions are a fundamental basis for several scientific explorations"
  • p.2 l.19-23: add transition from sentence regarding neurocognitive disturbances (no ref attached) to next line
    • Zen: started paragraph with: 'These neurocognitive deficits have been widely investigated using visual illusions as illusory paradigms demonstrate different contextual influences on visual perception. Visual illusions are thus valuable tools for revealing core features of pathological conditions, such as atypical integration processes in schizophrenia.'
  • p.6 l.44-55: at least three things missing in the caption (“illusion strength”, “difference”, and “size of the smallest rod”)
    • Zen: this was a problem with the knitted markdown - somehow \textit{} (to italicize captions) works with pdf but not docx. need to investigate
  • p.10: names of different illusions sometimes overlap with the illusions.
    • Zen: hard to fit all in one image, try generating again
  • Page 11 line 38 – syntax error: parameters = ill.(illusion_strength=2) Missing function name after ill.
  • Clarify the units images are generated in and if there is flexibility to use different units (this could do with adding to the docstrings)
    • Zen: Added sentence "The final images are rendered at 800 x 600 pixels (default)". We also already mention in our manuscript that images can be easily post-processed using the PIL library. Added a sentence after: "For example, to see what other image file formats can be saved, refer to PIL's documentation. Will mention these in the docstrings too - in addition to the possibility of resizing the images using the PIL library - resizing is arguably less important in this context (and hence not mentioned in manuscript) as it is unlikely to happen especially when images are generated on the go in an experimental setting.
  • update release version!!
  • Page 18 line 27: Since porting pyllusion to javascript might be a much longer term goal (and it is challenging to port whole python libs to JS!) it might be worth highlighting that one could easily use the pyllusion generated .png images and make the wider framework of the experiment in a software like PsychoPy builder to use the Pyllusion generated stimuli online.
    • It's true that porting Python dependencies to JS is an issue. That said, it might be feasible to add directly a JS extension that converts the parameters into the physical properties (as this is essentially basic maths operations). Then, drawing these primitives would require some extensions indeed.

R2 - Manuscript Revision

Putting this here so it's easier to track 😄 mainly, we'll need to:

  • Switch to class-based programming (and update docstrings)
  • Make a stronger argument in the introduction for why pyllusion
    • I've made some slight changes on top of @cratlagh 's changes in paper_tracked.docx in dropbox and updated the Rmd file (but not knitted yet). imo this is a much more concise version and reads well so far
    • to be updated again after switching to class
  • Address display (pixels, degree angles etc) issues
  • update README
  • Add link to python 3 distribution installation
  • Add excel sheet for database storage

to_psychopy() problems

Question and context
Dear authors: this semester I am teaching 'exploring illusions' in a high school in Tainan, Taiwan. We adopt your pyllusion codes with psychopy.yml+spyder environment, and it worked great. But we noticed that, when we tried to change some of the output from to_image() to to_psychopy(with some parameters), not all the codes worked as well as in to_image(). The examples include: Poggendorff, Simultaneous contrast, White and possibly other follow-up illusions. We just wonder why is these the cases, and how to make them work as well as in to_psychopy() as in to_image(). Thank you!
chun-chia kung

Idea for an web application (contribution)

A webapp for pyillusion

I discovered the PyIllusion library while researching optical illusions. I have an idea for a web app that could showcase these illusions, allowing users to interact with and manipulate various parameters.

How could we do it?
I've already developed a prototype using Streamlit. You can find it here: GitHub Repository. The trial version of the app is hosted here: PyIllusion Web App.

Fixed Delboeuf

For the record, the latest update (4ee0c33) changed the behavior of Delboeuf illusion to prevent an artifact where the difficulty at illusion strength of 0 is easier than it should due to the presence of the outlines that make the difference easier to spot

Past behavior:

ill.Delboeuf(illusion_strength=-1.8, difference=1.40).to_image(width=800, height=600)

Delboeuf_Demo

New behavior:

ill.Delboeuf(illusion_strength=-1.8, difference=1.40).to_image(width=800, height=600)

image

Pyllusion manuscript for JOSS

The manuscript for Pyllusion is now initiated to later be submitted to JOSS 😄

For now, I've structured the paper as so:

  1. Theoretical background about visual illusions

    • Some introduction about what visual illusions are
    • Example of psychological research using illusions
    • Aim of the software
  2. Installing Pyllusion

  3. Examples of Features

    • Illusion display to be run in Python (shows just a display of a visual illusion)
    • Running a PsychoPy experiment using Pyllusion
  4. End (Statement of conflict of interest, licensing & availability, acknowledgements)

Find it at manuscript.Rmd under the paper folder!

Manuscript Revision Checklist - Major

Manuscript

Introduction

  • Define Pyllusion scope, reduce discussion of clinical contexts and increase discussion of studies showing that differences in stimulus parameters/features systematically alter illusions leading to a need to reproducible stimuli (hence emphasizing the gap pyllusion is filling)
    • E.g. Role/impact of color, lightness contrast, size, line weighting, orientation on different types of illusions
    • Zen: the intro is refined to retain just a short summary of visual illusions in clinical studies before moving on to elaborating how theoretical understanding of the fundamental parameters underlying the various illusions is still lacking, and referencing studies showing systematic effects of manipulating parameters (e.g., colour contrast, proximity etc) on the perceived illusions. Also explained the importance of manipulating these parameters for practical applications (e.g., Delboeuf illusion for perceived food portions) and how they tap on neurocognitive processes in schizophrenia/ASD - which currently faces low replication rates due to inconsistent methodologies and hence (the gap the pyllusion is filling) the need for experimental paradigms where results can be consistently interpreted with respect to the parametric properties of the visual illusion.

Discussion

  • Current strengths and limitations of pyllusion
  • Considerations needed for researchers when using pyllusion (e.g., accurate control of contrast luminance and color will still require a properly calibrated monitor, viewing distance will still influence size, moving into the temporal domain will require consideration of refresh rates) especially to make an entire illusion based experiment (e.g., gathering responses)
    • Zen: Elaborated on additional practical considerations such as viewing conditions and presentation timings which have specific effects on each illusion. Second last paragraph

Code

  • Consideration of class-based API (see here)
  • Clarify need for psychopy_circles psychopy_line and psychopy_rectangle vs using the ShapeStim class in PsychoPy itself
  • Reconsider choice of ill as abbreviation
  • Either remove or explain syntax import as as it might be obscure for people not experienced in programming
    • Zen: Added sentence in installation section: "In the example script below, the line import pyllusion as ill is used so that it stores the Pyllusion module locally and makes functions accessible as ill (this effectively binds any module to a convenient local name)."
  • Provide greater clarification on the meanings of numbers assigned to illusion_strength and difference parameters
    • Zen: see two paras at "Note the two main parameters,..."

Illusion Effect Reference

Where could I find the papers for the implemented illusion effect? I am specifically looking for the Ponzo and the Simultaneous Contrast illusion. (like which paper states that inclined lines would give a stronger effect than vertical lines in the Ponzo illusion)

Thank you for the awesome package!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.