def Mouse_Loop(Directory): #Lists otherList = ['o', 'O', 'other', 'Other', 'OTHER'] quitList = ['q', 'Q', 'quit', 'Quit', 'QUIT'] yesList = ['y', 'Y', 'yes', 'YES', 'Yes'] noList = ['n', 'N', 'No', 'nO', 'NO', 'no'] text_file = open(Directory + '/Mice List.txt', "r") chosen_mouse = None miceDict = {} print "MOUSE MENU:" mouse = text_file.readline() mouse = mouse.rstrip() number = 1 while not (mouse == ''): print " Enter '%i' for mouse: "%number + mouse miceDict[number] = mouse mouse = text_file.readline() mouse = mouse.rstrip() number += 1 text_file.close() print " Enter 'Other' to enter a new mouse" print " Enter 'Quit' to quit mouse selection" while True: input = extras.getUserInput("Input:") try: input = int(input) except: pass if type(input) == int and (input > 0) and (input < number): chosen_mouse = miceDict[input] return chosen_mouse elif input in quitList: return None if input in otherList: while True: input = extras.getUserInput("Mouse Name: ") if input in noList: return None while True: print "You are about to add the mouse '"+input+"' to the list of mice" answer = extras.getUserInput("Is this correct? (Y/N):") if answer in yesList: text_file = open(Directory + '/Mice List.txt', "a") text_file.write('\n'+input) chosen_mouse = input return chosen_mouse elif answer in noList: return None else: print "Please enter a valid response" else: print "Please enter a valid response"
def getSaveFrameCount(self): while True: input = extras.getUserInput("Frames per Video:") if input in self.quitList: return False try: self.File_Saving_Dict["Frames_In_Saved_Video"] = int(input) return True except: print "Please enter a valid response. Enter 'q' to quit." return False
def autoRecord(self): #Ask user for minimum time between trials sleep_time = None while sleep_time is None: input = extras.getUserInput("Seconds between trials:") if input in self.quitList: return None try: sleep_time = float(input) except: print "Please enter a valid number" # Setup interface dir = os.listdir(self.File_Saving_Dict["File_PG_Initial_Save_Location"]) if not len(dir) == 0: n = 1 while os.path.exists('C:/Data/%i'%n): n += 1 os.mkdir('C:/Data/%i'%n) for file in dir: os.rename('C:/tmp/'+file, os.path.join('C:/Data/%i'%n,file)) text_file = open('C:/Data/%i'%n+'/NOTES', "w") text_file.write(str(pytime.localtime())) text_file.close() print "You may press start recording on the Point Grey Camera Now" print "Do not set the mask until the Point Grey Camera has begun recording" pl.ion() self.fig = pl.figure() self.ax = self.fig.add_subplot(111) self.ax.set_ylim([-1, 255]) self.plotdata = self.ax.plot(np.arange(self.monitor_vals_display),np.zeros(self.monitor_vals_display), 'r-')[0] self.plotline, = self.ax.plot(np.arange(self.monitor_vals_display), np.repeat(self.params['movement_std_threshold'], self.monitor_vals_display), 'r--') self.window = 'Camera' self.control = 'Status' cv2.namedWindow(self.window, cv.CV_WINDOW_NORMAL) cv2.namedWindow(self.control, cv.CV_WINDOW_AUTOSIZE) cv2.moveWindow(self.window, 0, 0) cv2.moveWindow(self.control, 600, 0) for pn in self.param_names: cv2.createTrackbar(pn,self.control,int(self.params[pn]), 200, self.update_windows) self.update_windows(self) #autoRecord waits for the mouse to begin moving, and then calls the run function to begin recording if self.cameraReady: print "Auto Recording..." self.set_masks() text_file = open(self.File_Saving_Dict["File_Complete_Target_Location"]+"\Parameters.txt", "w") for parameter in self.Imaging_Dict: text_file.write(str(parameter) + ": " + str(self.Imaging_Dict[parameter]) +"\n") text_file.write("Suspend Time: %d\n"%sleep_time) text_file.write("Time Began: %i"%pytime.began("%c")) text_file.close() while self.cameraReady: if not self.currentlyRecording: input = extras.getStreamingUserInput() #Allows user to pause, unpause, quit, or manually trigger a run self.cameraReady = self.handleUserInput(input) if self.isSuspended and (pytime.time() - sleep_begin > sleep_time): if self.isPaused: print "Trial Paused, but no longer suspended. Press the 'g' key to resume" else: print "Trial Resumed" self.isSuspended = False if not self.isPaused and not self.isSuspended: thisFrame = self.grabFrame() if self.mouseMovement(thisFrame) > self.Imaging_Dict["Movement_STD_Threshold"]: self.run() self.monitor_img_set = np.empty((self.Imaging_Dict["PS3_Resolution"][1],self.Imaging_Dict["PS3_Resolution"][0],self.movement_query_frames)) self.monitor_img_set[:] = None self.monitor_vals = np.empty(self.monitor_vals_display) for m in self.monitor_vals: self.monitor_vals[:] = None if sleep_time >= 1: self.isSuspended = True sleep_begin = pytime.time() print "Trial temporarily suspended" else: self.updatePS3Viewer(thisFrame) self.update_windows(self) while True: input = extras.getUserInput("Would you like to save these videos now? (Y/N):") if input in self.yesList: while True: print "Type 'Done' when the Point Grey Camera recording has stopped and the buffer has cleared" input = extras.getUserInput("") if input in self.doneList: break else: print "Unrecognised Command" print "Saving Videos..." self.savingProcess = Organizer(self.File_Saving_Dict) print "Please do not destroy the process or turn off the machine." self.savingProcess.saveFiles() print "Saving Complete" while True: input = extras.getUserInput("Would you like to sync these videos now? (Y/N):") if input in self.yesList: print "Synchronizing Videos..." print "Please do not destroy the process or turn off the machine." self.savingProcess.syncFiles() print "Synchronization Complete" elif input in self.noList: break else: print "Please enter a valid response" break elif input in self.noList: break else: print "Please enter a valid response." else: print "Error in Auto Recording." return None text_file = open(self.File_Saving_Dict["File_Complete_Target_Location"]+"\Parameters.txt", "a") text_file.write("Time Finished: %i"%pytime.began("%c")) text_file.close() cv2.destroyWindow(self.window) cv2.destroyWindow(self.control)
def maskedPlotRMS(self): #Private Constants analyze_video_type = None video_type_dict = {1:self.File_Saving_Dict["PS3_Target_SaveName"], 2:self.File_Saving_Dict["PG_Target_SaveName"]} allVideos = False while True: input = extras.getUserInput("Analyze Trial Number:") try: input = int(input) except: pass if (type(input) == int and os.path.isdir(self.File_Saving_Dict["File_Complete_Target_Location"],'Trial%i'%self.trialNum)): self.trialNum = input break else: print "Please enter a valid number" print " " print "Would you like to analyze PS3 Videos or Point Grey Videos?" print "Enter either 'PS3' or 'PG'" while True: input = extras.getUserInput("Type of Video:") input = int(input) if input in self.quitList: return None if (input in self.ps3List): self.savename = self.PS3_SaveName print 'Analyzing playstation videos...' break elif (input in self.pgList): self.savename = self.pgFileName print 'Analyzing point grey videos...' break else: print "Please enter a valid response" print " " print "Which video number would you like to image?" print "If you would like to image them all, enter 'a'" while True: input = extras.getUserInput("Input:") input = int(input) if input in self.quitList: return None if (type(input) == int and os.path.isfile(os.path.join(self.fileTargetLocation,'\Trial%i'%self.trialNum,video_type_dict[analyze_video_type]+'%i'%input))): self.videoNum = input break elif input in self.allList: allVideos = True else: print "Please enter a valid number" Continue == True while Continue: m=0 success, frame = self.camera.vc.read() #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #frame = frame.astype(np.uint8) #frame, timestamp = self.camera.read() pl.figure() pl.title("Select mask number: %s."%str(m+1)) pl.imshow(frame, cmap=mpl_cm.Greys_r) pts = [] while not len(pts): pts = pl.ginput(0) pl.close() path = mpl_path.Path(pts) mask = np.ones(np.shape(frame), dtype=bool) for ridx,row in enumerate(mask): for cidx,pt in enumerate(row): if path.contains_point([cidx, ridx]): mask[ridx,cidx] = False self.mask_pts[m] = np.array(pts, dtype=np.int32) self.masks[m] = mask self.mask_idx[m] = np.where(mask==False) while True: input = extras.getUserInput("Mask Name:") if type(input) == str: self.mask_name[m] = input break else: print "Please enter a valid name" #np.save(os.path.join(self.fileTargetLocation,'Analysis_mask_'+self.mask_name[m]), np.atleast_1d([self.masks])) while True: input = extras.getUserInput("Enter Another Mask? (Y/N):") if input in self.yesList: break elif input in self.noList: Continue = False break elif input in self.quitList: return None else: print "Please enter a valid response." pl.ion() self.fig = pl.figure() self.ax = self.fig.add_subplot(111) self.ax.set_ylim([-1, 255]) self.plotdata = {m:self.ax.plot(np.arange(self.monitor_vals_display),np.zeros(self.monitor_vals_display), c)[0] for m,c in zip(self.mask_name,['r-'])} self.plotline, = self.ax.plot(np.arange(self.monitor_vals_display), np.repeat(self.params['movement_std_threshold'], self.monitor_vals_display), 'r--') if not allVideos: dir = os.listdir(self.fileTargetLocationRoot+str(self.trialNum)) if not len(dir) == 0: n = 1 while os.path.isfile(os.path.join(self.fileTargetLocationRoot+str(self.trialNum),self.savename + str(self.videoNum)+'.avi')): n += 1 for self.VideoNum in range(n): self.std_dev_plot(os.path.join(self.fileTargetLocationRoot+str(self.trialNum), self.savename+str(self.videoNum)+'.avi')) else: self.std_dev_plot(os.path.join(self.fileTargetLocationRoot+str(self.trialNum), self.savename+str(self.videoNum)+'.avi')) # cap = cv2.VideoCapture(os.path.join(self.fileTargetLocationRoot+str(self.trialNum), self.savename+str(self.videoNum)+'.avi')) # fourcc = cv2.cv.CV_FOURCC(*'XVID') # width = int(cap.get(3)) # height = int(cap.get(4)) # numFramesInMovie = int(cap.get(cv.CV_CAP_PROP_FRAME_COUNT)) # fps = int(cap.get(cv.CV_CAP_PROP_FPS)) out = cv2.VideoWriter(os.path.join(self.fileTargetLocationRoot+'%i'%self.sortNum,self.pgFileName+vidNumStr+'.avi'),fourcc, fps, (width,height)) f, img = cap.read() frameCounter = 1 frames = self.camera.get(vc.VC_CAP_PROP_FRAME_COUNT) for counter in range(frames): pass
def Menu_Loop(Imaging_Dict, File_Saving_Dict, Constants_Dict, Camera): #Acceptable entries for performing a certain command saveCommandList = ['s','S','Sort','sort'] quitCommandList = ['q', 'Q', 'quit', 'Quit'] runCommandList = ['run', 'go', 'record', 'g', 'G'] viewCommandList = ['v', 'V', 'view', 'View'] recordCommandList = ['r', 'R', 'record', 'Record', 'Record', 'autorecord'] analyzeCommandList = ['a', 'A', 'analyze', 'Analyze', 'ANALYZE'] syncCommandList = ['y', 'Y', 'sync', 'Sync', 'SYNC'] changeCommandList = ['c', 'C', 'Change', 'change', 'CHANGE'] while True: print " " print "MENU: (Current Mouse: " + File_Saving_Dict["Mouse_Name"] +")" print " Enter 'Quit' to Quit" print " Enter 'Go' to manually start recording one video (unstable)" #print " Enter 'View' to view saved videos" print " Enter 'Sort' to move and rename all Point Grey files to the Data folder" print " Enter 'Record' to have the software automatically record mouse movement" print " Enter 'Analyze' to begin analyzing the data" print " Enter 'Sync' to begin synchronizing the videos" print " Enter 'Change' to select a different mouse" print " Enter 'View' to see from the Playstation 3 Camera without recording anything" input = extras.getUserInput("Input:") if (input in saveCommandList): savingProcess = Organizer(File_Saving_Dict) if savingProcess.getInfo(): if savingProcess.getSaveFrameCount(): savingProcess.saveFiles() savingProcess = None elif (input in viewCommandList): extras.View(Camera,File_Saving_Dict["File_Target_Location_Root"]) elif (input in quitCommandList): break elif (input in runCommandList): if not Recording.currentlyRecording: Recording.run() else: print "->Camera is currently recording" print " Please wait a moment to manually trigger it" elif (input in recordCommandList): Recording = Record(Imaging_Dict, File_Saving_Dict, Constants_Dict, Camera) Recording.autoRecord() Recording = None File_Saving_Dict["Trial_Number"] += 1 elif (input in analyzeCommandList): Analysis = analyze(File_Saving_Dict) if Analysis.getInfo(): Analysis.menu() pass elif (input in syncCommandList): savingProcess = Organizer(File_Saving_Dict) savingProcess.getLocation() savingProcess.syncFiles() savingProcess = None elif (input in changeCommandList): Mouse_Loop(File_Saving_Dict["File_Target_Location_Root"]) else: print "->Did not recognize user input." print " Please enter a valid command."