CSiEra

CSiEra

I know I know nothing.

Psychopy Learning Notes - MovieStim

These days I need to write a movie playback solution using Psychopy. Although I have used it many times before, Psychopy has been constantly updating, and I have not been satisfied with the previous implementation. Today, I organized it.

The main class used is psychopy.visual.MovieStim, which has several useful methods.

How to check if the movie has ended?#

Use the MovieStim.isFinished method. Check if this value is True in a while loop to determine if the movie has finished playing. If it has ended, you can proceed to the next task. If it hasn't ended, continue playing.

How to exit the playback interface when testing?#

I tried adding a global exit key, but it didn't work, probably because there was an issue with my code. So I had to find an alternative solution. Currently, I check for key presses during the video playback and stop the playback if a key is pressed.

To stop playing the video, you can use the mov.stop() method.

Code for playing the video:#

while not mov.isFinished:
    mov.draw()
    win.flip()
    if len(event.getKeys())>0:
        mov.stop()
        break

Automatically adjusting the size of the video#

I prepared two videos with different frame sizes. To achieve automatic adjustment, the cv2 library is needed.

Automatically detecting the frame size of the video#

import cv2
def get_movie_frame_size(movie_path):
    cap = cv2.VideoCapture(movie_path)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    cap.release()
    return frame_width, frame_height

This code was generated using chatGPT. Initially, I tried to use Psychopy to complete the task with chatGPT, but the outputs were incorrect.

According to the API documentation I read this afternoon, Psychopy has movie.size, which should output the frame size. However, when I tested it, the output was incorrect. Initially, chatGPT also used Psychopy itself to complete the task, but it had a similar issue. It's possible that the Psychopy interface has been constantly updating, so chatGPT didn't learn it. In the end, I used OpenCV to complete this task.

Final code#

for i in range(2):  # I only have two videos
    video_used = cur_movie_path + video_names[i]
    mov = visual.MovieStim(win, video_used,
                            flipVert=False, flipHoriz=False, loop=False)
    frame_width, frame_height = \ 
        get_movie_frame_size(cur_movie_path+video_names[i])
    mov.size = (frame_width, frame_height)

    while not mov.isFinished:
       mov.draw()
       win.flip()
       if len(event.getKeys())>0:
           mov.stop()
           break

The code was copied, and the indentation is not quite correct. If you want to use it, you need to adjust the indentation to avoid errors.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.