""" Copyright 2025 Alexander Borisov This file is part of FilmScanStabilizer. FilmScanStabilizer is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Software Version: 1.1.0 """ import cv2 import datetime import time import argparse import os import sys import numpy as np import json # Create the parser parser = argparse.ArgumentParser(usage='%(prog)s [options] path', description='Film stabilisation') # Add the arguments parser.add_argument('Path', metavar='path', type=str, help='input video file (img_%%05d.jpg)') parser.add_argument('-o', '--output-path', help='output path (correct position)') parser.add_argument('-c', '--config-file', default='config.json', help='config json file, default name: "config.json"') parser.add_argument('-k', '--offset-frame', default=0, help='offset frame number, default: 0') parser.add_argument('-r', '--frame-rate', default=24, help='sequence frame rate, default: 24') parser.add_argument('-l', '--left-offset', default=0, help='marker left offset, default: 0px') parser.add_argument('-t', '--top-offset', default=0, help='marker top offset, default: 0px') parser.add_argument('-f', action='store_true', help='force rewrite') # Execute parse_args() args = parser.parse_args() if os.path.isfile(args.config_file) : print(args.config_file) with open(args.config_file) as json_file : config = json.load(json_file) else : print('Can\'t open config file') sys.exit() #print(args.offset_frame) # open video file: (path, inputfile) = os.path.split( args.Path ) (filename, file_extension) = os.path.splitext(inputfile) if args.output_path : output_path = args.output_path else : output_path = path output_file = "ae_stabilize.jsx" # open videofile: cap = cv2.VideoCapture(path+"\\"+inputfile, cv2.CAP_IMAGES) print("Starting stabilisation:") print("Input file: {}".format(path+"\\"+inputfile)) print("Output path: {}".format(output_path)) print("Output filname: {}".format(output_file)) startframe = 1 stopframe = cap.get(cv2.CAP_PROP_FRAME_COUNT) #stopframe = 10 f = open(path+"\\"+output_file, 'w') sample = 0 totaltime = 0 fr_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) fr_cur = 0 content = "" ref_x = 0 ref_y = 0 offset_x = 0 offset_y = 0 center_pos_x = 0 center_pos_y = 0 print("offset top: " + str(args.top_offset) + "and offset left: " + str(args.left_offset)) while(1): ret, src = cap.read() frame = src.copy() fr_cur = cap.get(cv2.CAP_PROP_POS_FRAMES) if fr_cur < startframe : continue; if stopframe > 0 and fr_cur == stopframe : break (height, width, chan) = frame.shape if center_pos_x == 0 and center_pos_y == 0 : center_pos_x = width / 2 center_pos_y = height / 2 pta = (int(center_pos_x // config['factor'] - 40), int(center_pos_y // config['factor'])) ptb = (int(center_pos_x // config['factor'] + 40), int(center_pos_y // config['factor'])) frame = cv2.line(frame, pta, ptb, (255, 0, 255), 4) pta = (int(center_pos_x // config['factor']), int(center_pos_y // config['factor'] - 40)) ptb = (int(center_pos_x // config['factor']), int(center_pos_y // config['factor'] + 40)) frame = cv2.line(frame, pta, ptb, (255, 0, 255), 4) point_x = [] point_y = [] # horisontal rules: j = 0 for line in config['lines']['hr']: #left = line['left'] + config['offset_lines']['left'] #top = line['top'] + config['offset_lines']['top'] left = line['left'] + int(args.left_offset) top = line['top'] + int(args.top_offset) if len(point_x) <= j : point_x.append(0) for x in range(left,left+config['line_size']): (r, g, b) = frame[top, x] if r > 128: if "invert" in line and line['invert'] == 1 : point_x[j] += 1 else : point_x[j] -= 1 start_point = (left, top) end_point = (left+config['line_size'], top) j += 1 frame = cv2.line(frame, start_point, end_point, (0, 0, 255), 4) offset_x = sum(point_x) / len(point_x) if ref_x == 0 : ref_x = offset_x pos_x = int(ref_x - offset_x) # vertical rules j = 0 for line in config['lines']['vr']: #left = line['left'] + config['offset_lines']['left'] #top = line['top'] + config['offset_lines']['top'] left = line['left'] + int(args.left_offset) top = line['top'] + int(args.top_offset) if len(point_y) <= j : point_y.append(0) for y in range(top,top+config['line_size']): (r, g, b) = frame[y, left + pos_x] if r > 128 : if "invert" in line and line['invert'] == 1 : point_y[j] += 1 else : point_y[j] -= 1 start_point = (left + pos_x, top) end_point = (left + pos_x, top+config['line_size']) frame = cv2.line(frame, start_point, end_point, (255, 0, 255), 4) offset_y = sum(point_y) / len(point_y) if ref_y == 0 : ref_y = offset_y pos_y = int(ref_y - offset_y) j += 1 pta = (int(center_pos_x // config['factor'] + pos_x - (config['line_size'] // 2)), int(center_pos_y // config['factor'] - pos_y - 40)) ptb = (int(center_pos_x // config['factor'] + pos_x + (config['line_size'] // 2)), int(center_pos_y // config['factor']) - pos_y + 40) frame = cv2.rectangle(frame, pta, ptb, (255, 0, 0), 2) print("Frame: {:.0f} ({:.1f}%); position: [{:.0f},{:.0f}]".format(fr_cur, (fr_cur/fr_count*100), pos_x, pos_y)) content += " {:.0f}: [{:.1f}, {:.1f}],\n".format((fr_cur + float(args.offset_frame)), center_pos_x + pos_x * config['factor'], center_pos_y + pos_y * config['factor']) # escape catch if cv2.waitKey(1) & 0xFF == ord('q') or ret==False : cap.release() cv2.destroyAllWindows() break scale_percent = config['render_scale'] # percent of original size new_width = int(width * scale_percent / 100) new_height = int(height * scale_percent / 100) dim = (new_width, new_height) # resize image resized = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA) cv2.imshow('frame',resized) M = np.float32([[1,0,pos_x],[0,1,pos_y]]) stabilezed = cv2.resize(cv2.warpAffine(src, M, (width,height)), dim, interpolation = cv2.INTER_AREA) cv2.imshow('frame stabilezed',stabilezed) content = content[:-2] content = """ alert("Generate keyframes..."); keys = { """+content+""" }; var mySelectedLayers = app.project.activeItem.selectedLayers; if (mySelectedLayers.length > 0) { var myLayer = app.project.activeItem.selectedLayers[0]; var myProp = myLayer.property("Position"); for (var prop in keys) { myProp.setValueAtTime((prop-1)/"""+str(args.frame_rate)+""", keys[prop]); } } """ f.write(content) f.close() print('Operation is finished') cv2.waitKey(0) cv2.destroyAllWindows()