def getFrameNum(self, filename): video = VideoStream(filename) frameNum = -1 while frameNum != video.frameNbr(): frameNum = video.frameNbr() video.nextFrame() return frameNum
def change_sources(self): self.source_number += 1 if self.source_number == len(self.change_list): self.source_number = 0 self.vs.close() self.vs = VideoStream(self.change_list[self.source_number]) self.vs.run()
def open_stream(self): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((self.ip_address, XiaoYiActionCamera.DEFAULT_PORT)) server.send(b'{"msg_id":257,"token":0}') data = str(server.recv(512)) while "rval" not in data: data = str(server.recv(512)) token = re.findall('"param": (.+) }', data)[0] stop_stream = bytes('{"msg_id":260,"token":%s}' % token, encoding='ascii') server.send(stop_stream) start_stream = bytes('{"msg_id":259,"token":%s,"param":"none_force"}' % token, encoding='ascii') server.send(start_stream) def drain_camera_socket(): ignored = server.recv(512) while ignored: ignored = server.recv(512) drain = threading.Thread(target=drain_camera_socket, args=()) drain.setDaemon(True) drain.start() return VideoStream( FFmpegVideoCapture(XiaoYiActionCamera.STREAM_URL % self.ip_address, self.stream_width, self.stream_height, 'bgr24'))
def getServerInfo(self): self.serverInfo = {} for file in os.listdir(VIDEO_DIR): if file.endswith(VIDEO_FILE_EXT): videoSream = VideoStream(file) videoSream.countFrame() self.serverInfo[file] = videoSream.frameCnt
def __enter__(self): if self.isWebcam: # The VideoStream class always gives us the latest frame from the webcam. It uses another thread to read the frames. self.vs = VideoStream(int(self.videoPath)).start() # needed to load at least one frame into the VideoStream class time.sleep(1.0) #self.capture = cv2.VideoCapture(int(self.videoPath)) else: # In the case of a video file, we want to analyze all the frames of the video thus are not using VideoStream class self.capture = cv2.VideoCapture(self.videoPath) return self
def create_video_handle(self, cam_type="video_file", cam_source="/sample_video/video.mp4"): global stream_handle print("cam_source:: " + cam_source + " cam_type :: " + cam_type) if cam_type == "video_file": video_dir = "sample_video" # By default video file name should be video.mp4/avi if os.path.exists(str(video_dir) + "/video.mp4"): #if cam_source: self.video_handle = str(str(video_dir) + "/video.mp4") elif os.path.exists(str(video_dir) + "/video.avi"): #if cam_source: self.video_handle = str(str(video_dir) + "/video.avi") else: print("\n ERROR: Camera source Not Found...!!!") print("\n Exiting inference...") sys.exit(0) elif cam_type == "rtsp_stream": if cam_source: self.video_handle = str(cam_source) print("settin cam_source to value :: " + cam_source) else: print("\n ERROR: Camera source Not Found...!!!") print("\n Exiting inference...") sys.exit(0) else: web_cam_found = False for i in range(4): if os.path.exists("/dev/video" + str(i)): web_cam_found = True break if web_cam_found: self.video_handle = "/dev/video" + str(i) else: print("\n Error: Input Camera device not found/detected") print("\n Exiting inference...") sys.exit(0) self.vs = VideoStream(self.video_handle).start() # Reading widht and height details self.img_width = int(self.vs.stream.get(cv2.CAP_PROP_FRAME_WIDTH)) self.img_height = int(self.vs.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)) stream_handle = True
def processRtspRequest(self, data): #Process RTSP request from the client. request = data.split('\n') #print(request) param = request[0] line = param.split(' ') seq = request[1].split(' ')[1] # addr = request[2] # List = param.split(' ') # seqList = seq.split(' ') # addrList = addr.split(' ') requestType = line[0] if requestType == 'SETUP': self.clientInfo['videoStream'] = VideoStream(line[1]) self.clientInfo['seqNum'] = 0 self.clientInfo['rtpPort'] = request[2].split(' ')[3] self.state = OK self.clientInfo['session'] = randint(100000, 999999) # 随机生成session self.RtspResponse(seq) elif requestType == 'PLAY': if self.state == OK: self.state = PLAYING self.clientInfo['rtpSocket'] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.RtspResponse(seq) self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread(target=self.sendRtp) self.clientInfo['worker'].start() #开始播放 elif requestType == 'PAUSE': if self.state == PLAYING: self.state = OK self.clientInfo['event'].set() #停止播放 self.RtspResponse(seq) elif requestType == 'TEARDOWN': self.clientInfo['event'].set() self.RtspResponse(seq) self.clientInfo['rtpSocket'].close()
def __init__(self): """ Constructor """ global SVM_PATH self.my_x = 0 self.my_y = 0 self.my_theta = 0 self.other_x = 0 self.other_y = 0 self.other_theta = 0 self.speed = 0 rospy.init_node('g3') self.i2c = I2CHandler() self.vs = VideoStream().start() self.posData = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [ -1, -1 ]] #-1 represents no data --> from the start no data has received self.followingData = [ -1, -1, -1, -1, -1 ] #-1 represents leader --> from start everyone is the leader self.fanOutData = [-1, -1, -1, -1, -1] #-1 represents no data has received self.laneToGoTo = -1 self.fanOutFlag = False self.foundLaneTime = -1 self.robot_follower = RobotFollower(100, k_p=0.5) #self.serial = SerialHandler('/dev/ttyUSB0', 9600) self.turnC = TurnCheck([640, 480], "segImage.png") #self.gps_other = GpsClient(self.position_callback_other, color='green') self.heartbeat = Heartbeat(self.heartbeat_callback, self.platoon_pos_callback, self.fan_out_callback, self.lane_change_callback) self.gps = GpsClient(self.position_callback) self.image_recognizer = ImageRecognizer(SVM_PATH) self.get_ultrasound() time.sleep(2)
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file DBid filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("processing SETUP") try: absName = filename[:filename.__len__() - (filename.split(".")[filename.split(".").__len__() - 1].__len__() + 1)] self.clientInfo['videoStream'] = VideoStream("./contents/" + filename)# it must be a path self.waveFile = wave.open('./contents/' + absName + '.wav', 'rb') self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print("processing PLAY") self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.clientInfo["waveSocket"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker']= threading.Thread(target=self.sendRtp) self.clientInfo['wave'] = threading.Thread(target=self.sendWave) self.clientInfo['wave'].start() self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE") self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Process TEARDOWN request elif requestType == self.TEARDOWN: print("processing TEARDOWN") self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Close the RTP socket self.clientInfo['rtpSocket'].close() self.mainSock.send(pickle.dumps("out," + str(self.agentSeqNum)))
import cv2 import imutils import numpy as np from VideoStream import VideoStream from KeyClipWrite import KeyClipWriter outputfile = "Ash" write = None vs = VideoStream(src=0).start() fourcc = "MJPG" fps = 20 (h, w) = (None, None) #kcw=KeyClipWriter(32,1.0) #frame=vs.read() #frame=imutils.resize(frame,width=600) #kcw.update(frame) while True: frame = vs.read() frame = imutils.resize(frame, width=300) if write is None: out = "{}.avi".format(outputfile) (h, w) = frame.shape[:2] write = cv2.VideoWriter(out, cv2.VideoWriter_fourcc(*fourcc), fps, (w * 2, h * 2), True) zeros = np.zeros(frame.shape[:2], dtype="uint8") (B, G, R) = cv2.split(frame) R = cv2.merge([zeros, zeros, R]) G = cv2.merge([zeros, G, zeros]) B = cv2.merge([B, zeros, zeros])
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("processing SETUP\n") try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[0]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[0]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print("processing PLAY\n") self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[0]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE\n") self.state = self.READY try: self.clientInfo['event'].set() except: sys.exit(0) self.replyRtsp(self.OK_200, seq[0]) # Process TEARDOWN request elif requestType == self.TEARDOWN: print("processing TEARDOWN\n") try: self.clientInfo['event'].set() except: pass self.replyRtsp(self.OK_200, seq[0]) # Close the RTP socket try: self.clientInfo['rtpSocket'].close() except: pass
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') #line1 = request[0].split(' ') #requestType = line1[0] requestType, url, ver = re.split(r'\s+', request[0].strip()) # Get the media file name #filename = line1[1] hdr = {} for r in request[1:]: if len(r.strip()) == 0: continue arr = r.split(":") if len(arr) == 2: hdr[arr[0].strip().upper()] = arr[1].strip() else: print "not ok:", r, arr # Get the RTSP sequence number #Cseq=hdr['CSEQ'] # Process SETUP request if requestType == self.OPTIONS: if self.state == self.INIT: print "processing OPTIONS\n" self.replyOption(self.OK_200, hdr) elif requestType == self.DESCRIBE: if self.state == self.INIT: print "processing DESCRIBE\n" # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) v = VideoStream() self.clientInfo['videoStream'] = v sdp = v.getSdp() self.replyDescribe(self.OK_200, hdr, sdp) print "processing DESCRIBE Done\n" elif requestType == self.SETUP: if self.state == self.INIT: # Update state print "processing SETUP\n" self.state = self.READY s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 0)) self.udpPort = s.getsockname()[1] self.clientInfo["rtpSocket"] = s self.clientInfo['rtpPort'] = int( hdr['TRANSPORT'].split(';')[2].split('=')[1].split("-")[0]) # Send RTSP reply self.replySetup(self.OK_200, hdr) print "processing SETUP Done\n" # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print "processing PLAY\n" self.state = self.PLAYING # Create a new socket for RTP/UDP #self.clientInfo["rtpSocket"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.replyPlay(self.OK_200, hdr) print "processing PLAY Done\n" # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print "processing PAUSE\n" self.state = self.READY self.clientInfo['event'].set() self.replyPause(self.OK_200, hdr) print "processing PAUSE Done\n" # Process TEARDOWN request elif requestType == self.TEARDOWN: print "processing TEARDOWN\n" self.clientInfo['event'].set() self.replyTeardown(self.OK_200, hdr) print "processing TEARDOWN Done\n" # Close the RTP socket self.clientInfo['rtpSocket'].close()
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("processing SETUP\n") try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY # set rtpError to 0 self.rtpError = 0 self.frame_Number =0 except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print("processing PLAY\n") self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE\n") self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Process TEARDOWN request elif requestType == self.TEARDOWN: print("processing TEARDOWN\n") self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) #print statics rtpLossRate = self.rtpError*100/float(self.frame_Number) print("RTP packet loss rate is: %.3f %%" %(rtpLossRate)) # Close the RTP socket self.clientInfo['rtpSocket'].close() # Process TEARDOWN request elif requestType == self.SWITCH: if not self.state == self.PLAYING: print("processing SWITCH\n") self.replyRtsp(self.OK_200, seq[1]) elif requestType == self.CHOOSE: if not self.state == self.PLAYING: print("processing CHOOSE\n") try: if not self.clientInfo['videoStream'].file.closed: self.clientInfo['videoStream'].terminate() self.clientInfo['videoStream'] = VideoStream(filename) except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) elif requestType == self.STOP: if self.state == self.PLAYING or self.state == self.READY: print("processing STOP\n") self.state = self.INIT self.clientInfo['event'].set() if not self.clientInfo['videoStream'].file.closed: self.clientInfo['videoStream'].terminate() self.replyRtsp(self.OK_200, seq[1]) self.clientInfo['rtpSocket'].close() elif requestType == self.DESCRIBE: print("processing DESCRIBE\n") # create dict description = {} description['session'] = self.clientInfo['session'] description['encoding'] = filename.split('.')[1] reply = 'RTSP/1.0 200 OK\nCSeq: ' + seq[1] + '\nSession: ' + \ str(self.clientInfo['session']) + \ '\n' + json.dumps(description) self.clientInfo['rtspSocket'][0].send(reply.encode())
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name self.filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("processing SETUP\n") try: self.clientInfo['videoStream'] = VideoStream(self.filename) self.state = self.READY # TODO Get FPS, total time, number of frames of the video to send back to the client # # # self.clientInfo['videoStream'].calTotalTime() self.totalTime = self.clientInfo['videoStream'].totalTime self.fps = self.clientInfo['videoStream'].fps self.noFrames = self.clientInfo['videoStream'].numFrames ####################################################### # Find all media files except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print("processing PLAY\n") self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE\n") self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # TODO: ################################ # # # Process FORWARD request # elif requestType == self.FORWARD: # if self.state == self.PLAYING: # print("processing FORWARD\n") # self.state = self.PLAYING # self.forward = 1 # self.replyRtsp(self.OK_200, seq[1]) # Process BACKWARD request # elif requestType == self.BACKWARD: # if self.state == self.PLAYING: # print("processing BACKWARD\n") # self.state = self.PLAYING # self.backward = 1 # self.replyRtsp(self.OK_200, seq[1]) ######################################## # Process DESCRIBE request elif requestType == self.DESCRIBE: print("processing DESCRIBE\n") self.replyRtsp(self.OK_200, seq[1]) ######################################## # Process SWITCH request elif requestType == self.SWITCH: print("processing SWITCH\n") # If the state is READY if self.state == self.READY: self.clientInfo['videoStream'] = VideoStream(self.filename) # TODO # Get FPS, total time, number of frames of the video to send back to the client # # # self.clientInfo['videoStream'].calTotalTime() self.totalTime = self.clientInfo['videoStream'].totalTime self.fps = self.clientInfo['videoStream'].fps self.noFrames = self.clientInfo['videoStream'].numFrames ####################################################### # If the state is PLAYING switch to READY first # Required the user to pause the video to switch self.replyRtsp(self.OK_200, seq[1]) ######################################## # Process TEARDOWN request elif requestType == self.TEARDOWN: print("processing TEARDOWN\n") self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Close the RTP socket self.clientInfo['rtpSocket'].close() # process stop request elif requestType == self.STOP: print("processing STOP\n") if self.state == self.PLAYING or self.state == self.READY: self.clientInfo['event'].set() self.clientInfo['videoStream'].resetFrame() self.state = self.READY self.replyRtsp(self.OK_200, seq[1])
def set_Video_Source(self, newVideoPath): if self.verbose: logging.info('>> ' + self.__class__.__name__ + "." + sys._getframe().f_code.co_name + '()') retVal = False realVideoPath = newVideoPath if self.videoPath == newVideoPath and self._videoSourceState == CaptureDeviceState.Running: return True if self.imageStreamHandler != None: statusMsg = '{{\"DeviceStatus\":\"Connecting to {}\",\"isSuccess\":{}}}'.format( self._remove_credential(newVideoPath), 1) self.imageStreamHandler.submit_write(statusMsg) self._videoSourceState = CaptureDeviceState.Stop if self._capture_in_progress: # wait for queue to drain and loop to exit time.sleep(1.0) self._capture_in_progress = False self._set_Video_Source_Type(realVideoPath) if self._videoSourceType == CaptureDevice.Unknown: self._videoSourceState = CaptureDeviceState.ErrorNotSupported logging.error('>> ' + self.__class__.__name__ + "." + sys._getframe().f_code.co_name + '() : Unsupported Video Source {}'.format( self._videoSourceType)) else: self._videoSourceState = CaptureDeviceState.Init if self._videoSourceType == CaptureDevice.Hololens: strHololens = realVideoPath.split('?') # disable audio realVideoPath = '{}?holo=true&pv=true&mic=false&loopback=false'.format( strHololens[0]) self.videoStream = VideoStream(videoCapture=self, path=realVideoPath) fps_override = 30 if not self.videoStream.videoCapture == None: # get resolution cameraH1 = int( self.videoStream.videoCapture.get( cv2.CAP_PROP_FRAME_HEIGHT)) cameraW1 = int( self.videoStream.videoCapture.get( cv2.CAP_PROP_FRAME_WIDTH)) cameraFPS1 = int( self.videoStream.videoCapture.get(cv2.CAP_PROP_FPS)) if self._videoSourceType == CaptureDevice.Webcam: if not cameraH1 == self._displayH: self.videoStream.videoCapture.set( cv2.CAP_PROP_FRAME_HEIGHT, self._displayH) if not cameraW1 == self._displayW: self.videoStream.videoCapture.set( cv2.CAP_PROP_FRAME_WIDTH, self._displayW) elif self._videoSourceType == CaptureDevice.Rtsp: if not cameraH1 == self._displayH: self.videoStream.videoCapture.set( cv2.CAP_PROP_FRAME_HEIGHT, self._displayH) if not cameraW1 == self._displayW: self.videoStream.videoCapture.set( cv2.CAP_PROP_FRAME_WIDTH, self._displayW) elif self._videoSourceType == CaptureDevice.Hololens: holo_w = 1280 holo_h = 720 if 'live_med.mp4' in realVideoPath: holo_w = 854 holo_h = 480 elif 'live_low.mp4' in realVideoPath: holo_w = 428 holo_h = 240 fps_override = 15 self.videoStream.videoCapture.set( cv2.CAP_PROP_FRAME_HEIGHT, holo_h) self.videoStream.videoCapture.set(cv2.CAP_PROP_FRAME_WIDTH, holo_w) self.videoStream.videoCapture.set(cv2.CAP_PROP_FPS, fps_override) self._cameraH = int( self.videoStream.videoCapture.get( cv2.CAP_PROP_FRAME_HEIGHT)) self._cameraW = int( self.videoStream.videoCapture.get( cv2.CAP_PROP_FRAME_WIDTH)) self._cameraFPS = int( self.videoStream.videoCapture.get(cv2.CAP_PROP_FPS)) logging.info( '===============================================================' ) logging.info( 'Setting Video Capture with the following parameters:') logging.info(' - Video Source Type : {}'.format( self._videoSourceType)) logging.info(' - Display Resolution : {} x {}'.format( self._displayW, self._displayH)) logging.info(' Original : {} x {} @ {}'.format( cameraW1, cameraH1, cameraFPS1)) logging.info(' New : {} x {} @ {}'.format( self._cameraW, self._cameraH, self._cameraFPS)) logging.info( '===============================================================' ) if self.videoStream.start(): self._videoSourceState = CaptureDeviceState.Running retVal = True else: self._videoSourceState = CaptureDeviceState.ErrorRead else: if self._videoSourceType == CaptureDevice.Hololens or self._videoSourceType == CaptureDevice.Rtsp: url_parsed = urlparse(realVideoPath) if url_parsed.password != None or url_parsed.username != None: url_parsed = url_parsed._replace( netloc="{}".format(url_parsed.hostname)) ipAddress = url_parsed.netloc ping_ret = subprocess.call( ['ping', '-c', '5', '-W', '3', ipAddress], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) if ping_ret == 0: self._videoSourceState = CaptureDeviceState.ErrorOpen else: self._videoSourceState = CaptureDeviceState.ErrorNoNetwork logging.error('>> ' + self.__class__.__name__ + "." + sys._getframe().f_code.co_name + '() : Failed to open Video Capture') self.videoPath = realVideoPath if retVal == False: self.set_Wallpaper(self._frame_wp_no_video) else: self._videoReadyEvent.set() self.sendCurrentVideoPath(realVideoPath) return retVal
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type # SETUP video.mjpeg\n1\n RTSP/1.0 RTP/UDP 5008 # print("data type: %s: %s" % (type(data), data)) if type(data) == bytes: request = data.split(b'\n') line1 = request[0].split(b' ') requestType = line1[0].decode() # Get the media file name filename = line1[1].decode() # Get the RTSP sequence number seq = request[1].split(b' ') if type(seq) == list: seq = [x.decode('utf-8') for x in seq] else: request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("SETUP Request received\n") try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp( self.OK_200, seq[0]) #seq[0] the sequenceNum received from Client.py print("sequenceNum is " + seq[0]) # Get the RTP/UDP port from the last line if sys.version_info[0] < 3: self.clientInfo['rtpPort'] = request[2].split(' ')[3] else: self.clientInfo['rtpPort'] = request[2].split( b' ')[3].decode() print('-' * 60 + "\nrtpPort is :" + self.clientInfo['rtpPort'] + "\n" + '-' * 60) print("filename is " + filename) # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print('-' * 60 + "\nPLAY Request Received\n" + '-' * 60) self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[0]) print('-' * 60 + "\nSequence Number (" + seq[0] + ")\nReplied to client\n" + '-' * 60) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process RESUME request elif self.state == self.PAUSE: print('-' * 60 + "\nRESUME Request Received\n" + '-' * 60) self.state = self.PLAYING # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print('-' * 60 + "\nPAUSE Request Received\n" + '-' * 60) self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) # Process TEARDOWN request elif requestType == self.TEARDOWN: print('-' * 60 + "\nTEARDOWN Request Received\n" + '-' * 60) self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) # Close the RTP socket self.clientInfo['rtpSocket'].close() else: print("Unknown requestType: %s (%s)" % (requestType, type(requestType)))
def __enter__(self): self.vs = VideoStream(int(self.videoPath)).start() # needed to load at least one frame into the VideoStream class time.sleep(1.0) return self
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') self.requestType = line1[0] # Get the media file name self.filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if self.requestType == self.SETUP: if self.state == self.INIT or self.state == self.SWITCHING: # Update state print("processing SETUP\n") try: self.clientInfo['videoStream'] = VideoStream(self.filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] # Initialize a frame counter self.frameCnt = 0 # Process DESCRIBE request elif self.requestType == self.DESCRIBE: print("processing DESCRIBE\n") self.replyRtsp(self.OK_200, seq[1]) # Process PLAY request elif self.requestType == self.PLAY: if self.state == self.READY: print("processing PLAY\n") self.state = self.PLAYING requestedFrame = int(request[3].split(' ')[1]) frameCnt = self.serverInfo[self.filename] if requestedFrame >= frameCnt: requestedFrame = frameCnt - 1 self.clientInfo['requestedFrame'] = requestedFrame # Create a new socket for RTP/UDP self.clientInfo['rtpSocket'] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif self.requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE\n") self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Process TEARDOWN request elif self.requestType == self.TEARDOWN: print("processing TEARDOWN\n") self.state = self.INIT self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Close the RTP socket self.clientInfo['rtpSocket'].close() # Process SWITCH request elif self.requestType == self.SWITCH: print("processing SWITCH\n") self.state = self.SWITCHING self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Close the RTP socket self.clientInfo['rtpSocket'].close() # Process GET_LIST request elif self.requestType == self.GET_LIST: print("processing GET_LIST\n") self.replyRtsp(self.OK_200, seq[1])
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print "processing SETUP\n" try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) print "RTSP/1.0 200 OK\nCSeq: " + seq[1] + "\nSession: " + str( self.clientInfo['session']) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print "\nprocessing PLAY\n" self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) print "\nRTSP/1.0 200 OK\nCSeq: " + seq[ 1] + "\nSession: " + str(self.clientInfo['session']) + "\n" # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: self.state = self.READY print "\nprocessing PAUSE\n" self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) print "\nRTSP/1.0 200 OK\nCSeq: " + seq[ 0] + "\nSession: " + str(self.clientInfo['session']) + "\n" # Process TEARDOWN request elif requestType == self.TEARDOWN: print "\nprocessing TEARDOWN\n" self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) print "\nRTSP/1.0 200 OK\nCSeq: " + seq[0] + "\nSession: " + str( self.clientInfo['session']) + "\n" # Close the RTP socket self.clientInfo['rtpSocket'].close() #calc and display avg. jitter frameNumber = self.clientInfo['videoStream'].frameNbr() rate = float(self.jitcount) / frameNumber print("Jitter: %.6f" % rate) + " s"
import cv2 import imutils from VideoStream import VideoStream from MotionClass import Motion import time import numpy as np import datetime vs1=VideoStream(src=0).start() vs2=VideoStream(src=1).start() time.sleep(15.0) motion1=Motion() motion2=Motion() image=cv2.imread("MUNA.jpg") total=0 while True: frames=[] for (stream,motion) in zip((vs1,vs2),(motion1,motion2)): frame=stream.read() gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) gray=cv2.GaussianBlur(gray,(21,21),0) locs=motion.update(gray) if total>32: frames.append(frame) if len(locs)>0: (max_x,max_y)=(-np.inf,-np.inf) (min_x,min_y)=(np.inf,np.inf) for l in locs: (x,y,w,h)=cv2.boundingBox(l) (minx,maxx)=(min(min_x,x),max(max_x,x+w)) (miny,maxy)=(min(min_y,y),max(max_y,y+h))
from KeyClipWrite import KeyClipWriter import cv2 import imutils import numpy as np from VideoStream import VideoStream import datetime import time import argparse vid=VideoStream(0).start() time.sleep(2.0) output="AshirTestVid" fourcc="MJPG" fps=20 i=0 buffersize=64 kwc=KeyClipWriter(buffersize,1.0) green1=(29,86,6) green2=(64,255,255) ap = argparse.ArgumentParser() #ap.add_argument("-o", "--output", required=True, #help="path to output directory") ap.add_argument("-c", "--codec", type=str, default="MJPG", help="codec of output video") args = vars(ap.parse_args()) frame=vid.read() frame=imutils.resize(frame,width=600) kwc.update(frame) while True:
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("processing SETUP\n") try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] #Change # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print("processing PLAY\n") self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread( target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE\n") self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Process STOP request elif requestType == self.STOP: print("processing STOP\n") if self.state == self.PLAYING: #note self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Close the RTP socket if self.state == self.PLAYING: #note self.clientInfo['rtpSocket'].close() elif requestType == self.DESCRIBE: print("processing DESCRIBE\n") file_path = 'information.txt' with open(file_path, 'w') as f: info = "v=0\n" + \ "m=video " + str(int(self.clientInfo['rtpPort'])) + " RTP/AVP " + "26\n" + \ "a=control:streamid=" + str(self.clientInfo['session']) + "\n" + \ "a=mimetype:string;\"video/MJPEG\"\n" general_info = "RTSP/1.0 200 OK\nCSeq: " + str(seq[1]) + "\n" + \ "Content-Base: " + filename + "\n" + \ "Content-Type: " + "application/sdp\n" + \ "Content-Length: " + str(len(info)) + "\n" general_info += info f.write(general_info) with open(file_path, "rb") as f: connSocket = self.clientInfo['rtspSocket'][0] l = f.read(1024) while (l): connSocket.send(l) l = f.read(1024) self.replyRtsp(self.OK_200, seq[1])
import cv2 from imutils.video import VideoStream import datetime import argparse from Stepper import Stepper # defaults to using the PiCamera ap = argparse.ArgumentParser() ap.add_argument("-p", "--picamera", type=int, default=-1, help="whether the PiCamera being used") args = vars(ap.parse_args()) vs = VideoStream(usePiCamera=args["picamera"] > 0).start( ) # starts video capture using PiCamera time.sleep(2.0) def main(argv): bright_values = {} # creates an array of the brightest values count = 0 while True: if count == 7: # looks for 7 different spots break frame = vs.read() # reads the frame from the OpenCV object frame = imutils.resize( frame, width=400 ) # resizing the frame in case frame was changed previously
import cv2 from imutils.video import VideoStream import datetime import argparse from Stepper import Stepper from Servo import Servo ap = argparse.ArgumentParser() ap.add_argument("-p", "--picamera", type=int, default=-1, help="whether the PiCamera being used") args = vars(ap.parse_args()) vs = VideoStream(usePiCamera=args["picamera"] > 0).start() time.sleep(2.0) def main(argv): bright_values = {} # creates an array of the brightest values count = 0 while True: if count == 7: # looks for 7 different spots break frame = vs.read() # reads the frame from the OpenCV object frame = imutils.resize( frame, width=400
def recvRtspRequest(self): connSocket, (clientAddr, clientPort) = self.clientInfo['rtspSocket'] self.clientAddr = clientAddr while True: data = connSocket.recv(1024) if data: print "\nData Recieve\n" + data #get the info from the data content = data.split("\n") array_1 = content[0].split(" ") # requst type: setup, play, pause, teardown reqType = array_1[0] # the filename filename = array_1[1] # seq number seq = content[1].split(" ")[1] if reqType == self.SETUP_REQ: if self.state == self.INIT: print "set up the movie" array_3 = content[2].split(" ") # get hte rtp port number self.clientrtpPort = int(array_3[3]) try: self.clientInfo['videoStream'] = VideoStream( filename) except: self.replyRtsp(self.FILE_NOT_FOUND_404, seq) self.state = self.READY self.session = randint(111, 777) self.replyRtsp(self.OK_200, seq) elif reqType == self.PLAY_REQ: if self.state == self.READY: self.state = self.PLAYING print "playing the movie" self.replyRtsp(self.OK_200, seq) # when get the play movie socket, establish the socket and be ready to send the video data if self.rtpSocket == None: self.rtpSocket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.rtpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65535) # start a even to control the action of playing, pausing and teardown self.event_trigger = threading.Event() self.event_trigger.clear() # start a thread to send the video data threading.Thread(target=self.sendRtp).start() elif reqType == self.PAUSE_REQ: if self.state == self.PLAYING: print "pause the move" self.replyRtsp(self.OK_200, seq) # stop send the video to the client self.event_trigger.set() self.state = self.READY elif reqType == self.TEARDOWN_REQ: print "close the movie" self.replyRtsp(self.OK_200, seq) # stop send the video to the client self.event_trigger.set() self.state = self.INIT
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type data = data.decode() request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process LIST request if requestType == self.LIST: fileList = [] for file in os.listdir("./"): if file.endswith(".mjpeg") or file.endswith(".Mjpeg"): fileList.append(file) reply = "" for file in fileList: reply += file + "," self.replyRtsp(self.LIST_OK_200, reply) # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print("SETUP Request received\n") # fileList = [] # --------------------------------------------------- try: self.clientInfo['totalFrame'] = self.getFrameNum(filename) except Exception as e: print(e) # --------------------------------------------------- # for file in os.listdir("./"): # if file.endswith(".mjpeg") or file.endswith(".Mjpeg"): # fileList.append(file) try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY file = open(filename, "rb") self.clientInfo["videoWeight"] = str(round(len(file.read()) / 1024)) file.close() except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[0]) # seq[0] the sequenceNum received from Client.py print("sequenceNum is " + seq[0]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] print('-' * 60 + "\nrtpPort is :" + self.clientInfo['rtpPort'] + "\n" + '-' * 60) print("filename is " + filename) # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print('-' * 60 + "\nPLAY Request Received\n" + '-' * 60) self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[0]) print('-' * 60 + "\nSequence Number (" + seq[0] + ")\nReplied to client\n" + '-' * 60) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread(target=self.sendRtp) self.clientInfo['worker'].start() # Process RESUME request elif self.state == self.PAUSE: print('-' * 60 + "\nRESUME Request Received\n" + '-' * 60) self.state = self.PLAYING # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print('-' * 60 + "\nPAUSE Request Received\n" + '-' * 60) self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) # Process TEARDOWN request elif requestType == self.TEARDOWN: print('-' * 60 + "\nTEARDOWN Request Received\n" + '-' * 60) self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) # Close the RTP socket self.clientInfo['rtpSocket'].close() # Process DESCRIBE request elif requestType == self.DESCRIBE: print('-' * 60 + "\nDESCRIBE Request Received\n" + '-' * 60) self.replyRtsp(self.OK_200, seq[0]) # Process FORWARD request elif requestType == self.FORWARD: print('-' * 60 + "\nFORWARD Request Received\n" + '-' * 60) self.replyRtsp(self.OK_200, seq[0]) self.clientInfo['skipCounter'] += 10 # Process BACKWARD request elif requestType == self.BACKWARD: print('-' * 60 + "\nBACKWARD Request Received\n" + '-' * 60) self.replyRtsp(self.OK_200, seq[0]) self.clientInfo['skipCounter'] -= 10
def predict_video(self, source=0, sync=False): VideoStream(source=source, fbae=self).start()
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') #print("abcbbcaafhkjsafsa") # Process SETUP request if requestType == self.SETUP: #print("metvc") if self.state == self.INIT: # Update state print("processing SETUP\n") # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Send RTSP reply self.replyRtsp(self.OK_200, seq[1]) # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] self.countRTPSent = 0 # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print("processing PLAY\n") self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[1]) # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker'] = threading.Thread(target=self.sendRtp) self.clientInfo['worker'].start() # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print("processing PAUSE\n") self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) line4 = self.countRTPSent - eval(request[3].split(' ')[1]) print("=========================\nRTP packet loss rate: " + str(line4) + '/' + str(self.countRTPSent) + "\n=========================\n") # Process TEARDOWN request elif requestType == self.TEARDOWN: self.state = self.INIT print("processing TEARDOWN\n") self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1]) # Close the RTP socket self.clientInfo['rtpSocket'].close() elif requestType == self.DESCRIBE: print("processing DESCRIBE\n") # self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[1], 'describe')
def processRtspRequest(self, data): """Process RTSP request sent from the client.""" # Get the request type request = data.split('\n') line1 = request[0].split(' ') requestType = line1[0] # Get the media file name filename = line1[1] # Get the RTSP sequence number seq = request[1].split(' ') # Process SETUP request if requestType == self.SETUP: if self.state == self.INIT: # Update state print "SETUP Request received\n" try: self.clientInfo['videoStream'] = VideoStream(filename) self.state = self.READY except IOError: self.replyRtsp(self.FILE_NOT_FOUND_404, seq[1]) # Generate a randomized RTSP session ID self.clientInfo['session'] = randint(100000, 999999) # Send RTSP reply self.replyRtsp(self.OK_200, seq[0]) #seq[0] the sequenceNum received from Client.py print "sequenceNum is " + seq[0] # Get the RTP/UDP port from the last line self.clientInfo['rtpPort'] = request[2].split(' ')[3] print '-'*60 + "\nrtpPort is :" + self.clientInfo['rtpPort'] + "\n" + '-'*60 print "filename is " + filename # Process PLAY request elif requestType == self.PLAY: if self.state == self.READY: print '-'*60 + "\nPLAY Request Received\n" + '-'*60 self.state = self.PLAYING # Create a new socket for RTP/UDP self.clientInfo["rtpSocket"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.replyRtsp(self.OK_200, seq[0]) print '-'*60 + "\nSequence Number ("+ seq[0] + ")\nReplied to client\n" + '-'*60 # Create a new thread and start sending RTP packets self.clientInfo['event'] = threading.Event() self.clientInfo['worker']= threading.Thread(target=self.sendRtp) self.clientInfo['worker'].start() # Process RESUME request elif self.state == self.PAUSE: print '-'*60 + "\nRESUME Request Received\n" + '-'*60 self.state = self.PLAYING # Process PAUSE request elif requestType == self.PAUSE: if self.state == self.PLAYING: print '-'*60 + "\nPAUSE Request Received\n" + '-'*60 self.state = self.READY self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) # Process TEARDOWN request elif requestType == self.TEARDOWN: print '-'*60 + "\nTEARDOWN Request Received\n" + '-'*60 self.clientInfo['event'].set() self.replyRtsp(self.OK_200, seq[0]) # Close the RTP socket self.clientInfo['rtpSocket'].close()
from VideoStream import VideoStream import cv2 import imutils import numpy as np import time fps = 20 fourcc = 'MJPG' write = None vs = VideoStream().start() time.sleep(10.0) output = 'VideoforAttendance' face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def detect(frame, gray): epsilon = 50 myframe = frame faces = face_cascade.detectMultiScale(gray, 1.3, 5) for x, y, w, h in faces: cv2.rectangle(myframe, (x - epsilon, y - epsilon), (x + w + epsilon, y + h + epsilon), (255, 0, 0), 2) return myframe while True: frame = vs.read() frame = imutils.resize(frame, height=300) gray = cv2.cvtColor(