| Reference | Downloads | Github

Inserting Pygame code in Psychopy to run webcam

Hello everyone!

I have a code that is running smoothly in Pygame. Basically I have created a webcam on Pygame and am able to take pictures with it on multiple time frames. As I am new to PsychoPy, I am not able to create such webcam results on it. I wanted to know if it is possible to insert the whole Pygame code in Psychopy? Or the other way around?
Also, if not, is there any way to install and run a webcam that records the subject’s behaviour and emotions while responding to my experiments?

I have tried to run the code of webcam given on Psychopy website, but it is showing multiple errors. And when I tried installing webcam on Pygame, it worked perfectly. Is there any easier way to do such on Psychopy or insert that Pygame code in Psychopy?

Any help will be much appreciated. Thanks in advance!

@Shardul_Shankar, PsychoPy can use one of two ‘backends’ for creating windows and drawing; pygame and pyglet - see here. Pygame is distributed with PsychoPy, so you can just import the pygame module into your script and use it.

Thank you for the answer @dvbridges!

Is there a sample code or solution that I can look into for this problem?

It sounds like you already have your own code, as well as the example PsychoPy code. So perhaps the best thing to do would be to post whatever actual code you are trying to integrate with PsychoPy, along with the full text of any error messages you receive.

Looking at the example at
it would seem that pygame is a bit of a red herring here: you should be able to display webcam output without any reference to that library at all.

Cheers @Michael, I had to change that code to get it to work. But, the following should work, at least on Python 3

from __future__ import print_function
from psychopy import visual, event
from PIL import Image
import cv2 as cv

mywin = visual.Window(allowGUI=False, monitor='testMonitor', units='norm',colorSpace='rgb',color=[-1,-1,-1], fullscr=True)

capture = cv.VideoCapture(0)
img =[1]
pi = Image.fromarray(img)
myStim = visual.GratingStim(win=mywin, tex=pi, pos=[0,0], size = [1,1], opacity = 1.0, units = 'norm')

while True:
    img =[1]
    pi = Image.fromarray(img)
    theKey = event.getKeys()
    if len(theKey) != 0: