Skip to content

Instantly share code, notes, and snippets.

@sque
Last active August 29, 2015 14:01
Show Gist options
  • Save sque/e2b0e585ad900adf7bc1 to your computer and use it in GitHub Desktop.
Save sque/e2b0e585ad900adf7bc1 to your computer and use it in GitHub Desktop.
Script to manipulate image sequences generated by GoPRO camera.
#!/usr/bin/env python
"""
Script to manipulate image sequences generated by GoPRO camera.
@license GNU General Public License <https://gnu.org/licenses/gpl.html>
"""
import sys
import os
import re
import argparse
import numpy as np
def find_natural_sequences(numbers):
'''
Find all natural sequences in an given set of numbers
'''
# Find points that do not increase by one
numbers = np.sort(numbers)
dist = np.diff(numbers)
break_points = np.where(dist != 1)[0]
# Create all sets for this points
sets = []
current_set_start = 0
for break_point in break_points:
sets.append((numbers[current_set_start],
numbers[break_point]))
current_set_start = break_point + 1
# Missing the last set after the last breakpoint
sets.append((numbers[current_set_start],
numbers[-1]))
return sets
parser = argparse.ArgumentParser(
description="Reorder Go PRO image sequences.")
parser.add_argument("folder", type=str,
help="The folder to scan for sequences.")
parser.add_argument("--recursive", "-r", action="store_true",
help="Scan folders recursively.")
parser.add_argument("--dry-run", action="store_true",
help="Do not perfom any actual convertions.")
parser.add_argument("--verbose", "-v", action="store_true",
help="Verbose program output.")
args = parser.parse_args()
folder = args.folder
if not os.path.isdir(folder):
print "{0} is not folder".format(sys.argv[1])
sys.exit(1)
# Get files that fit Gopro pattern
go_fname_re = re.compile("G([\d]{7})\.JPG")
file_ids = []
for f in os.listdir(folder):
match = go_fname_re.match(f)
if match:
file_ids.append(int(match.group(1)))
if not file_ids:
print "Cannot find any Go PRO sequence files."
sys.exit(1)
# Find sequences
file_ids = np.array(file_ids)
sequences = find_natural_sequences(file_ids)
if (args.verbose):
print "Sequences discovered:"
for s in sequences:
print " {start:-7d} -> {end:-7d} ({total})".format(
start=s[0],
end=s[1],
total=s[1] - s[0] + 1)
# Rename
for seq_id, seq in enumerate(sequences):
for new_id, old_id in enumerate(range(seq[0], seq[1] + 1)):
new_name = os.path.join(
folder,
"GS{seq_id}I{id}.jpg".format(
seq_id=seq_id,
id=new_id))
old_name = os.path.join(folder, "G{:07d}.JPG".format(old_id))
if (args.verbose):
print "{0} -> {1}".format(old_name, new_name)
if (not args.dry_run):
os.rename(old_name, new_name)
print "Renamed {0} files".format(len(file_ids))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment