Advertisement
DuboisP

Untitled

Mar 22nd, 2022
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.67 KB | None | 0 0
  1. """
  2.    Purpose     : launch a video by an Arduino connected by serial and activated by ultrasound sensor
  3.    Author      : Patrick Dubois
  4.    Date        : 2022-03-22
  5.    Copyright   : Public Domain
  6.    Usage       : COMx speed parity bits stopbit video_path_filename
  7.            ex. : COM12 9600 N 8 1 "D:\Data\Videos\GOPR0366.MP4"
  8.                : serial baud must the same for Arduino serial port
  9.                : to complete
  10.    ToDo        : fullscreen - close VLC - pass video filename in Arduino Serial
  11. """
  12.  
  13. import sys
  14. import time
  15.  
  16. import cv2 as cv                                    # opencv-python https://opencv.org/
  17. import keyboard                                     # keyboard      https://pypi.org/project/keyboard/
  18. import numpy as np
  19. import serial as portcomm                           # pyserial      https://pyserial.readthedocs.io/en/latest/pyserial.html
  20. import serial.tools.list_ports
  21. import vlc                                          # python-vlc    https://wiki.videolan.org/Python_bindings/  https://www.olivieraubert.net/vlc/python-ctypes/
  22. from PIL import Image                               # https://pypi.org/project/Pillow/
  23. from ffpyplayer.player import MediaPlayer           # https://pypi.org/project/ffpyplayer/
  24.  
  25.  
  26. def ffplayer_play(my_movie):                        # have a look at cvplayer https://github.com/addyett/cvplayer/
  27.  
  28.     player = MediaPlayer(my_movie)
  29.     window_name = "Movie"
  30.     cv.namedWindow(window_name)
  31.  
  32.     val = ''
  33.     while val != 'eof':
  34.         frame, val = player.get_frame()
  35.         if val != 'eof' and frame is not None:
  36.             image, pts = frame
  37.             x, y = image.get_size()
  38.             data = image.to_bytearray()[0]
  39.             image = Image.frombytes("RGB", (x, y), bytes(data))
  40.             image = cv.cvtColor(np.array(image), cv.COLOR_RGB2BGR)
  41.             cv.imshow('Movie', image)
  42.             cv.setWindowProperty(window_name, cv.WND_PROP_TOPMOST, cv.WINDOW_NORMAL)
  43.             del image
  44.             # Press ESC on keyboard to stop video. windows must have the focusq
  45.             if cv.waitKey(20) == 27:
  46.                 break
  47.  
  48.     cv.destroyWindow(window_name)
  49.  
  50.  
  51. def opencv_play(my_movie):
  52.  
  53.     window_name = "Movie"
  54.     video = cv.VideoCapture(my_movie)
  55.     cv.namedWindow(window_name)
  56.     fps = video.get(cv.CAP_PROP_FPS)                # frames per second, doesn't work for webcam
  57.     if fps > 144 or fps is None or fps == 0:
  58.         fps = 25
  59.     ms_waitkey = int(1000 / fps)
  60.     nb_frame_grabbed = 0
  61.     while video.isOpened():
  62.         ret, frame = video.read()
  63.         if ret:
  64.             nb_frame_grabbed = 0
  65.             cv.imshow(window_name, frame)
  66.             cv.setWindowProperty(window_name, cv.WND_PROP_TOPMOST, cv.WINDOW_NORMAL)
  67.             # cv.setWindowProperty(window_name, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
  68.             # Press ESC on keyboard to stop video. windows must have the focus
  69.             if cv.waitKey(ms_waitkey) == 27:
  70.                 break
  71.         else:    # elif frame is None:
  72.             # break
  73.             nb_frame_grabbed += 1
  74.             if nb_frame_grabbed > 2:
  75.                 break
  76.  
  77.     video.release()
  78.     cv.destroyWindow(window_name)
  79.     # cv.destroyAllWindows()
  80.  
  81.  
  82. def vlc_play(my_movie):
  83.  
  84.     vlc_instance = vlc.Instance()
  85.     media = vlc_instance.media_new(my_movie)
  86.     player = vlc_instance.media_player_new()
  87.     player.set_media(media)
  88.     # player.set_fullscreen(b_fullscreen=True)
  89.     player.play()
  90.     while player.is_playing():
  91.         time.sleep(1)
  92.     # player.close()                                # no way. must be in a windows to get the handle and manage it
  93.  
  94.  
  95. if __name__ == '__main__':
  96.     args = sys.argv[1:]
  97.  
  98.     ports = serial.tools.list_ports.comports()
  99.     commports_liste = [comport.device for comport in ports]
  100.  
  101.     if len(args) != 6:
  102.         # print(len(args), " ", args)
  103.         print("Arguments de communication incorrects")
  104.         print("ex: COM3 9600 N 8 1 video_path_filename")
  105.         exit(1)
  106.     else:
  107.         serial_port = args[0]
  108.         serial_baud = int(args[1])
  109.         serial_parity = args[2]
  110.         serial_bits = int(args[3])
  111.         serial_stop = int(args[4])
  112.         movie = args[5]
  113.  
  114.     try:
  115.         com_portx = portcomm.Serial(port=serial_port, baudrate=serial_baud, parity=serial_parity,
  116.                                     stopbits=serial_stop, bytesize=serial_bits)
  117.  
  118.         bFlag = True
  119.         while bFlag:
  120.             if com_portx.in_waiting:
  121.                 sline_byte = com_portx.readline()
  122.                 sline_utf8 = sline_byte.decode('UTF-8')
  123.                 if sline_utf8[:12] == 'LAUNCH_VIDEO':
  124.                     # print("video launched")
  125.                     ffplayer_play(movie)
  126.  
  127.             if keyboard.is_pressed("f"):            # F is also working play movie by ffplayer / opencv
  128.                 ffplayer_play(movie)
  129.  
  130.             if keyboard.is_pressed("o"):            # O is also working play movie by opencv
  131.                 opencv_play(movie)
  132.  
  133.             elif keyboard.is_pressed("q"):          # Q is also working
  134.                 print("q or Q")
  135.                 bFlag = False
  136.  
  137.             elif keyboard.is_pressed("v"):          # V is also working  play movie by VLC
  138.                 vlc_play(movie)
  139.                 time.sleep(1)
  140.  
  141.         com_portx.close()
  142.  
  143.     except portcomm.PortNotOpenError:
  144.         print("Cannot open serial port")
  145.     except portcomm.SerialTimeoutException:
  146.         print("Timeout on serial port")
  147.     except portcomm.SerialException:
  148.         print("Other problem on serial port, as non-existing port or bad settings")
  149.         print("Available ports are " + " ".join(commports_liste))
  150.  
  151.     finally:
  152.         print("\r\nExit")
  153.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement