Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tweeting a random frame from a bunch of videos in a directory
# Run this on a timer as a cronjob or Lambda function or whatever works for you.
# I just run it as a cronjob and set the environment variables directly in the crontab.
import cv2
import os
from random import randint
import twitter
videos_directory = os.environ['VIDEOS_DIR']
twitter_consumer_key = os.environ['TWITTER_CONSUMER_KEY']
twitter_consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
twitter_access_token_key = os.environ['TWITTER_ACCESS_TOKEN_KEY']
twitter_access_token_secret = os.environ['TWITTER_ACCESS_TOKEN_SECRET']
video_files = os.listdir(videos_directory)
file_to_grab = randint(0, len(video_files) - 1)
file_name = video_files[file_to_grab]
vid = cv2.VideoCapture('{}/{}'.format(videos_directory, file_name))
total_frames = vid.get(cv2.CAP_PROP_FRAME_COUNT)
# I chop off the first and last 200 frames in case they are blank.
frame_to_grab = randint(200, total_frames - 200)
vid.set(cv2.CAP_PROP_POS_FRAMES, frame_to_grab)
ret, curframe = vid.read()
cv2.imwrite('image.jpg', curframe)
api = twitter.Api(
consumer_key=twitter_consumer_key,
consumer_secret=twitter_consumer_secret,
access_token_key=twitter_access_token_key,
access_token_secret=twitter_access_token_secret,
sleep_on_rate_limit=True
)
api.PostUpdate(status='', media='image.jpg')
vid.release()
cv2.destroyAllWindows()
# You may need to install other underlying dependencies for OpenCV.
# On a fresh Ubuntu AMI, I had to install libgl1-mesa-glx from apt.
astroid==2.4.2
certifi==2020.6.20
chardet==3.0.4
future==0.18.2
idna==2.10
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
numpy==1.19.1
oauthlib==3.1.0
opencv-python==4.4.0.40
packaging==20.4
pycodestyle==2.6.0
pylint==2.5.3
pyparsing==2.4.7
python-twitter==3.5
requests==2.24.0
requests-oauthlib==1.3.0
six==1.15.0
toml==0.10.1
urllib3==1.25.10
wrapt==1.12.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment