python, vlc, rtsp. Screenshots doesn't work

32 Views Asked by At

I run this:

import vlc
import time

player = vlc.MediaPlayer('rtsp://NNNNNNNNNNNNNN')
player.play() 

period = 2  # Every 2 seconds I got new screenshot from camera

while True:
    time.sleep(period)
    player.video_take_snapshot(0, 'screenshot-tmp.png', 0, 0)

Once I delete player.play() - it does not work anymore. No screenshoots.

What the problem?

I don't need to open VLC player, just need to taking screens and work with them

2

There are 2 best solutions below

0
iburakov On BEST ANSWER

Try creating your player this way:

instance = vlc.Instance("--vout=vdummy")
player = instance.media_player_new("rtsp://NNNNNNNNNNNNNN")
player.play() 

(based on this)

You can't remove player.play() because this call is required for the media to start actually playing.

How the code above works? To get rid of the GUI we can use the --vout VLC CLI argument described in the docs as a way to control the video output method. We choose a special one – vdummy – so the video output is faked.

CLI-like arguments can be provided when a "libvlc instance" is created, so we do it manually (otherwise you had the default one created automatically, without the --vout=vdummy).

Then media_player_new(uri) creates a new MediaPlayer object off that "libvlc instance". It can be used like any other MediaPlayer, but its behavior will be affected by the CLI args we provided to the Instance.

1
Jordi On

By calling play from the player object, a stream starts. The video_take_snapshot method needs of a media player instance for the screenshots to be taken[1].

With other third-party libraries like OpenCV you could use something like VideoCapture of the player without the player starting: https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html

import vlc
import cv2

url = 'rtsp://NNNNNNNNNNNNNN'

instance = vlc.Instance()

media = instance.media_new(url)

player = vlc.MediaPlayer(media)

cap = cv2.VideoCapture(player) 

period = 2

while True:
  ret, frame = cap.read()
  if ret:
    cv2.imwrite('screenshot-tmp.png', frame)
    print("Screenshot captured!")  
  else:
    print("Error capturing frame")
  time.sleep(period)

[1] https://www.olivieraubert.net/vlc/python-ctypes/doc/index.html