Skip to content

Instantly share code, notes, and snippets.

@dobrosketchkun
Last active November 17, 2023 09:18
Show Gist options
  • Save dobrosketchkun/5e4c48a636792694d9e6a11df9ceec71 to your computer and use it in GitHub Desktop.
Save dobrosketchkun/5e4c48a636792694d9e6a11df9ceec71 to your computer and use it in GitHub Desktop.
timelapse from ip web camera
import cv2
import urllib.request
import numpy as np
import ssl
import time
from datetime import datetime
COUNTER = 0
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
starttime = time.time()
sleeping_length = 10.0
# url = 'http://180.31.192.51:60001/mjpg/video.mjpg'
# url = 'http://125.206.12.114/cgi-bin/camera?resolution=640&quality=1&Language=0&1646346307'
# url = 'http://106.157.4.56/cgi-bin/faststream.jpg?stream=half&fps=15&rand=COUNTER'
# url = 'http://121.116.223.177/cgi-bin/camera?resolution=640&quality=1&Language=0&amp'
# url = 'http://113.59.228.69:8080/mjpg/video.mjpg'
# url = 'http://210.237.44.35/-wvhttp-01-/GetOneShot?image_size=640x480&frame_count=1000000000'
# url = 'http://161.72.22.244/mjpg/video.mjpg'
url = 'http://89.29.205.1:5000/mjpg/video.mjpg'
while True:
doLoop = True
try:
stream = urllib.request.urlopen(url,context=ctx)
bytes = b''# MAKE IT BYTES
while doLoop:
bytes += stream.read(1024)
a = bytes.find(b'\xff\xd8')
b = bytes.find(b'\xff\xd9')
if a != -1 and b != -1:
jpg = bytes[a:b+2]
bytes = bytes[b+2:]
i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
cv2.imwrite('./frames/' + str(COUNTER).zfill(5) + '.jpg', i)
COUNTER = COUNTER + 1
doLoop = False
# cv2.imshow('i', i)
# if cv2.waitKey(1) == 27:
# exit(0)
print(datetime.now().strftime("%H:%M:%S"),(str(COUNTER - 1).zfill(5) + '.jpg'), 'saved')
time.sleep(sleeping_length - ((time.time() - starttime) % sleeping_length))
except Exception as e:
print(datetime.now().strftime("%H:%M:%S"), e)
time.sleep(sleeping_length)
#partially rip off of https://github.com/Tom25/ipcam-timelapse
import datetime
import cv2
import os
import time
# Config
stream_url = 'http://121.101.90.232/oneshotimage1?1604747558121'
list_now = datetime.datetime.now()
list_time = list_now.strftime("%H-%M-%S")
list_date = list_now.strftime("%Y-%m-%d")
every_x_seconds = 30
def main(url):
# Determine save location
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d")
time = now.strftime("%H-%M-%S")
absolute_script_dir = os.path.dirname(os.path.realpath(__file__))
save_dir = absolute_script_dir + '/snapshots/'
save_path = save_dir + '/' + date + '_' + time + '.jpg'
print('Saving ', date + '_' + time + '.jpg')
# Capture frame from camera stream
try:
cap = cv2.VideoCapture(stream_url)
ret, frame = cap.read()
# Save frame as image
if not os.path.exists(save_dir):
os.makedirs(save_dir)
cv2.imwrite(save_path, frame)
# with open(save_dir + '/' + list_date + '_' + list_time + '.txt', 'a') as file:
with open(save_dir + 'list.txt', 'a') as file:
file.write('file \'' + date + '_' + time + '.jpg' + '\'' + '\n')
except Exception as e:
print(e)
print(date + '_' + time + '.jpg' + ' is not saved')
while True:
main(stream_url)
time.sleep(every_x_seconds)
import subprocess
import os
import shutil
def frames_to_video(input_folder, output_file, fps, speed):
# Create a temporary directory
temp_folder = 'temp_frames'
os.makedirs(temp_folder, exist_ok=True)
# Get and sort the frame files
frame_files = sorted([f for f in os.listdir(input_folder) if f.endswith(('.jpg', '.jpeg'))])
# Copy and rename files to the temp directory to create a continuous sequence
for i, filename in enumerate(frame_files):
new_filename = f"{i:05d}.jpg"
shutil.copy(os.path.join(input_folder, filename), os.path.join(temp_folder, new_filename))
# Form the ffmpeg command for video creation
input_pattern = os.path.join(temp_folder, '%05d.jpg')
# Create a video from the frames
video_cmd = [
'ffmpeg', '-r', str(fps), '-i', input_pattern,
'-vf', f'setpts={1/speed}*PTS', '-pix_fmt', 'yuv420p', '-y', 'temp_video.mp4'
]
subprocess.run(video_cmd)
# Add a silent audio track to the video
final_cmd = [
'ffmpeg', '-i', 'temp_video.mp4', '-f', 'lavfi', '-i', 'anullsrc',
'-c:v', 'copy', '-c:a', 'aac', '-shortest', output_file
]
subprocess.run(final_cmd)
# Remove the temporary files
shutil.rmtree(temp_folder)
os.remove('temp_video.mp4')
# Example usage
frames_to_video('frames', 'output_video.mp4', 30, 0.3) # Set your own values for fps and speed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment