view scripts/manual-video-analysis.py @ 889:4ea296ee1ae2

work in progress
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Fri, 24 Mar 2017 14:20:01 -0400
parents d2eb8c93f7de
children 85bcc758ee5b
line wrap: on
line source

#! /usr/bin/env python

import sys, argparse, cv2

parser = argparse.ArgumentParser(description=''''The program replays the video and allows to manually id vehicles and mark instants, eg when they cross given areas in the scene. Use this program in combination with a screen marker program (For example, Presentation Assistant) to draw multiple lines on the screen.''',
                                 epilog = '''The output should give you a .csv file with the same name as your video file with columns in this format:
vehicle number, frame number
You can easily spot mistakes in the csv file for a line with number, SKIP. If this happens, just delete the previous vehicle observation.''',
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-i', dest = 'videoFilename', help = 'name of the video file', required = True)
parser.add_argument('-o', dest = 'outputFilename', help = 'name of the output file (csv file)')
parser.add_argument('-f', dest = 'firstFrameNum', help = 'number of first frame number to display', default = 0, type = int)

args = parser.parse_args()

print('''Commands:
u: New vehicle crossing the first line
i: Vehicle crossing subsequent lines
o: Press o when you make a mistake in input
p: Press p for a new pedestrian event (eg crossing)
d: Skip 100 frames
s: Skip 10 frames
c: Go back 100 frames
x: Go back 10 frames
Spacebar: Go forward one frame
l: Skip to frame number
q: Quit and end program''')
# configuration of keys and user types (see moving)
userTypeNames = ['unknown',
                 'car',
                 'pedestrian',
                 'motorcycle',
                 'bicycle',
                 'bus',
                 'truck']
class UserConfiguration(object):
    def __init__(self, name, keyNew, keyAddInstant):
        self.name = name
        self.keyNew = ord(keyNew)
        self.keyAddInstant = ord(keyAddInstant)
        self.userNum = 0
        self.userInstant = 0

    def isKeyNew(self, k):
        return (k == self.keyNew)

    def isKeyAddInstant(self, k):
        return (k == self.keyAddInstant)
    
    def isKey(self, k):
        return self.isKeyNew() or self.isKeyAddInstant()

    @staticmethod
    def isKey(configurations):
        for c in configurations:
            if c.isKey():
                return c
        return None

userConfigurations = [UserConfiguration(userTypeNames[1],1,'u','i'),
                      UserConfiguration(userTypeNames[2],2,'j','k')]

# start of program
cap = cv2.VideoCapture(args.videoFilename)
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, args.firstFrameNum)
cv2.namedWindow('Video', cv2.WINDOW_NORMAL)

# output filename
if args.outputFilename is None:
    i = args.videoFilename.rfind('.')
    if i>0:
        outputFilename = args.videoFilename[:i]+'.csv'
    else:
        outputFilename = args.videoFilename+'.csv'
else:
    outputFilename = args.outputFilename
vehNumber = 0
lineNum = -1
out = open(outputFilename, 'a')

while(cap.isOpened()):
    ret, frame = cap.read()
    frameNum = int(cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES))
    cv2.putText(frame, str(frameNum), (1,20), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0,0))
    cv2.imshow('Video',frame)

    key= cv2.waitKey(0)

    if key == ord('q'):
        break
    else:
        config = UserConfiguration.isKey(userConfigurations)
        if config is not None:
            if c.isKeyNew():
                pass # increment userNum
            elif c.isKeyAddInstant():
                pass # increment userInstant
            # print/write
        
    elif key == ord('u') or key == ord('i'):
        if key == ord('u'):
            vehNumber += 1
            lineNum = 0
            print('New Vehicle')
        out.write('{},{}\n'.format(vehNumber,frameNum))        
        if vehNumber >= 1 and key == ord('i'):
            lineNum = lineNum+1
            print('Line number {}'.format(lineNum))
    elif key == ord('o'):
        out.write('{},SKIP\n'.format(vehNumber))
        print('SKIPPED')
    elif key == ord('p'):
        print("New Pedestrian")
        out.write('Pedestrian,{}\n'.format(frameNum))
#Change the number of frames skipped or the keys in this section
    elif key == ord('d'):
        cap.set(1,frameNum+100)
    elif key == ord('s'):
        cap.set(1,frameNum+10)
    elif key == ord('a'):
        cap.set(1,frameNum+1)
    elif key == ord('x'):
        cap.set(1,frameNum-10)
    elif key == ord('c'):
        cap.set(1,frameNum-100)
    elif key == ord('l'):
        frameNum = int(raw_input("Please enter the frame number you would like to skip to\n"))
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,frameNum-5)
    

cap.release()
cv2.destroyAllWindows()

#97a
#115s
#100d
#102f
#103g
#104h
#106j
#107k
#108l