Beispiel #1
0
    def __init__(self):
        super(Code1, self).__init__()

        # Do what is necessary to start the process
        # and to leave gloriously
        self.arm()

        self.sub = subs.Subs()
        self.pub = pubs.Pubs()
        self.pub.subscribe_topic('/act', Custom)
        self.pub.subscribe_topic('/mavros/rc/override', OverrideRCIn)
        self.pub.subscribe_topic('/mavros/setpoint_velocity/cmd_vel',
                                 TwistStamped)
        self.pub.subscribe_topic('/BlueRov2/body_command', JointState)
        self.pub.subscribe_topic('/Location2', Odometry)
        self.sub.subscribe_topic('/joy', Joy)
        self.sub.subscribe_topic('/odom', Odometry)
        self.sub.subscribe_topic('/mavros/battery', BatteryState)
        self.sub.subscribe_topic('/mavros/rc/in', RCIn)
        self.sub.subscribe_topic('/mavros/rc/out', RCOut)
        self.sub.subscribe_topic('/mavros/imu/static_pressure', FluidPressure)
        self.sub.subscribe_topic('/mavros/imu/diff_pressure', FluidPressure)
        self.sub.subscribe_topic('/mavros/imu/data', Imu)
        self.sub.subscribe_topic('/depth', Float32)
        self.sub.subscribe_topic('/odometry/filtered', Odometry)
        self.cam = None
        try:
            video_udp_port = rospy.get_param("/user_node/video_udp_port")
            rospy.loginfo("video_udp_port: {}".format(video_udp_port))
            self.cam = video.Video(video_udp_port)
        except Exception as error:
            rospy.loginfo(error)
            self.cam = video.Video()
Beispiel #2
0
    def __init__(self):
        super(ROV_control, self).__init__()

        # Do what is necessary to start the process
        # and to leave gloriously
        self.arm()

        self.sub = subs.Subs()
        self.pub = pubs.Pubs()

        self.pub.subscribe_topic('/mavros/rc/override', OverrideRCIn)
        self.pub.subscribe_topic('/mavros/setpoint_velocity/cmd_vel', TwistStamped)
        self.pub.subscribe_topic('/BlueRov2/body_command', JointState)

        self.sub.subscribe_topic('/joy', Joy)
        self.sub.subscribe_topic('/mavros/battery', BatteryState)
        self.sub.subscribe_topic('/mavros/rc/in', RCIn)
        self.sub.subscribe_topic('/mavros/rc/out', RCOut)

        self.cam = None
        try:
            video_udp_port = rospy.get_param("/user_node/video_udp_port")
            rospy.loginfo("video_udp_port: {}".format(video_udp_port))
            self.cam = video.Video(video_udp_port)
        except Exception as error:
            rospy.loginfo(error)
            self.cam = video.Video()
Beispiel #3
0
    def __init__(self):
        super(Code, self).__init__()

        # Do what is necessary to start the process
        # and to leave gloriously
        rospy.wait_for_service('/mavros/cmd/arming')
        self.arm_service = rospy.ServiceProxy('/mavros/cmd/arming', CommandBool)
        self.disarm()
        self.is_armed = False

        self.sub = subs.Subs()
        self.pub = pubs.Pubs()

        self.pub.subscribe_topic('/mavros/rc/override', OverrideRCIn)
        self.pub.subscribe_topic('/mavros/setpoint_velocity/cmd_vel', TwistStamped)
        self.pub.subscribe_topic('/BlueRov2/body_command', JointState)

        self.sub.subscribe_topic('/joy', Joy)
        self.sub.subscribe_topic('/mavros/battery', BatteryState)
        self.sub.subscribe_topic('/mavros/rc/in', RCIn)
        self.sub.subscribe_topic('/mavros/rc/out', RCOut)
        self.sub.subscribe_topic('/imu_pose', Pose)

        self.cam = None
        self.bridge = CvBridge()

        self.image_pub = rospy.Publisher("BlueRov2/image",Image)
        try:
            video_udp_port = rospy.get_param("/user_node/video_udp_port")
            rospy.loginfo("video_udp_port: {}".format(video_udp_port))
            self.cam = video.Video(video_udp_port)
        except Exception as error:
            rospy.loginfo(error)
            self.cam = video.Video()
Beispiel #4
0
def save_video_attributes(inputFilepath="video_search.txt",
                          outputFilepath="videos.csv",
                          overwrite=True):
    """
	TODO: C++ pandas integration?
	:param inputFilepath:
	:param outputFilepath:
	"""
    attributeList = vi.Video.getAttributeList()
    videos = pd.read_csv(inputFilepath,
                         sep=',',
                         names=['filePath'],
                         index_col=None).head(10)
    videos = pd.DataFrame(videos, columns=['filePath'].extend(attributeList))
    (totalRows, _) = videos.shape
    if ((os.path.exists(outputFilepath) and overwrite)
            or not os.path.exists(outputFilepath)):
        file = open(outputFilepath, 'wb')
        attributesHeader = ','.join(['filePath'].extend(attributeList))
        file.write(attributesHeader + '\n')
    else:
        file = open(outputFilepath, 'ab')

    for index, videoLine in videos.iterrows():
        print videoLine['filePath']
        video = vi.Video(videoLine['filePath'], videos=videos)
        for attributeName in attributeList:
            # print '\t' + str(video[attribute])
            read = video[attributeName]
        file.write(','.join([
            str(video[attributeName])
            for attributeName in ['filePath'].extend(attributeList)
        ]) + '\n')
Beispiel #5
0
    def openMedia(self):
        #if hasattr(self, "player"):#Удаляет медиаплеер
        #self.player.deleteLater()
        #del self.player

        if hasattr(self, "hbox"):  #Удаляет отрисовку
            self.hbox.deleteLater()
            del self.hbox

        self.pathSourceObject = self.path[:self.path.rfind(".")]
        self.fileType = self.path[self.path.rfind(".") + 1:]
        if self.fileType in {"png", "jpg", "JPG"}:
            self.mediaObject = photo.Photo(self.path)
            self.mediaQt.MediaStackedWidget.setCurrentIndex(1)
            self.mediaQt.editPanelStacked.setCurrentIndex(3)
            self.mediaQt.controlPanelStacked.setCurrentIndex(2)
            self.startMedia()
        if self.fileType in {"mp4"}:
            self.mediaObject = video.Video(self.path)
            self.mediaQt.MediaStackedWidget.setCurrentIndex(0)
            self.mediaQt.editPanelStacked.setCurrentIndex(0)
            self.mediaQt.controlPanelStacked.setCurrentIndex(0)

            self.startMedia()
        elif self.fileType in {"mp3"}:
            self.mediaObject = audio.Audio(self.path)
            self.mediaQt.MediaStackedWidget.setCurrentIndex(2)
            self.mediaQt.editPanelStacked.setCurrentIndex(1)
            self.mediaQt.controlPanelStacked.setCurrentIndex(0)
            self.startMedia()
def test(vid_filename):

    video_capture = video.Video(vid_filename)
    video_capture.start()
    detector = face_detection_modified.FaceDetection()
    facecount = 0
    framecount = 0

    while True:

        frame = video_capture.get_frame()
        framecount += 1

        if frame is None:
            print("facecount:" + str(facecount))
            print("framecount:" + str(framecount))
            break

        frame, face_frame, ROI1, ROI2, status, mask = detector.face_detect(frame)
        if status:
            facecount += 1

        # Display the resulting image
        cv2.imshow('Video', frame)

        # Hit 'q' on the keyboard to quit!
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break


    video_capture.stop()
    cv2.destroyAllWindows()
    def __init__(self):
        #On prépare un fichier temporaire tant que le script est lancé
        #pid = str(os.getpid())
        #pidfile = "/tmp/controleur.pid"

        #try:
        #	#On teste si le fichier existe déja
        #	if os.path.isfile(pidfile):
        #		os.link(pidfile,"daemon_python")
        #	else:
        #		file(pidfile, 'w').write(pid)
        #		os.link(pidfile,"daemon_python")
        #except IOError as e:
        #	message = "I/O error("+str(e.errno)+"): "+str(e.strerror)
        #	print(message)
        #On effectue le vrai travail ici
        #On instancie les classes principales
        self.stop_event = threading.Event()
        self.surveillance_serveur = surveillance_serveur.Surveillance_serveur(
            self, self.stop_event)
        self.surveillance_serie = surveillance_serie.Surveillance_serie(
            self, self.stop_event)
        self.traitement = traitement.Traitement(self, self.stop_event)
        self.video = video.Video(self.stop_event)
        self.led = LED.LED(self.stop_event)

        #On met les threads en mode daemon, quand le controleur est tué, on tue tous les threads
        self.surveillance_serveur.daemon = True
        self.surveillance_serie.daemon = True
        self.traitement.daemon = True
        self.video.daemon = True
        self.led.daemon = True
Beispiel #8
0
def from_video(cap, out=None):
    """Read data from a video file

    Arguments:
        cap {cv2.VideoCapture} -- The video capture from CV2

    Keyword Arguments:
        out {string} -- The output location if recording (default: {None})
    """
    frame = 0
    log.debug("resolution: %s", (int(cap.get(3)), int(cap.get(4))))
    if out:
        out = cv2.VideoWriter(out, cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'),
                              10, (int(cap.get(3)), int(cap.get(4))))
    vid = video.Video(cap, out)
    ret = 1
    while (vid.cap.isOpened and ret == 1):
        start = time.perf_counter()
        log.info("frame: %s", frame)
        ret = vid.shoelace_finding(frame)
        log.info(ret)
        if ret == 0:
            exit()
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        frame += 1
        end = time.perf_counter()
        log.info("Current Total time is %s resulting in frame rate of %s",
                 end - start, 1 / (end - start))
    cap.release()
    cv2.destroyAllWindows()
Beispiel #9
0
    def test_diff_weights(self):
        fs = frame_grabber.FrameGrabber(mode=video_mode.VideoMode.DHGR)
        v = video.Video(fs,
                        ticks_per_second=10000.,
                        mode=video_mode.VideoMode.DHGR)

        frame = screen.MemoryMap(screen_page=1)
        frame.page_offset[0, 0] = 0b1111111
        frame.page_offset[0, 1] = 0b1010101

        target_pixelmap = screen.DHGRBitmap(palette=palette.Palette.NTSC,
                                            main_memory=v.memory_map,
                                            aux_memory=frame)
        self.assertEqual(0b0000000000101010100000001111111000,
                         target_pixelmap.packed[0, 0])

        pal = palette.NTSCPalette

        diff = target_pixelmap.diff_weights(v.pixelmap, is_aux=True)

        # Expect byte 0 to map to 0b0001111111000
        expect0 = target_pixelmap.edit_distances(pal.ID)[0][0b0001111111000]

        # Expect byte 2 to map to 0b0001010101000
        expect2 = target_pixelmap.edit_distances(pal.ID)[2][0b0001010101000]

        self.assertEqual(expect0, diff[0, 0])
        self.assertEqual(expect2, diff[0, 1])

        # Update aux frame
        v.aux_memory_map.page_offset = frame.page_offset
        v.pixelmap._pack()
        self.assertEqual(0b0000000000101010100000001111111000,
                         v.pixelmap.packed[0, 0])

        # Encode new aux frame
        frame = screen.MemoryMap(screen_page=1)
        frame.page_offset[0, 0] = 0b1101101
        frame.page_offset[0, 1] = 0b0110110

        target_pixelmap = screen.DHGRBitmap(main_memory=v.memory_map,
                                            aux_memory=frame,
                                            palette=pal.ID)
        self.assertEqual(0b0000000000011011000000001101101000,
                         target_pixelmap.packed[0, 0])

        diff = target_pixelmap.diff_weights(v.pixelmap, is_aux=True)

        # Masked offset 0 changes from 0001111111000 to 0001101101000
        expect0 = target_pixelmap.edit_distances(
            pal.ID)[0][0b00011111110000001101101000]

        # Masked offset 2 changes from 0001010101000 to 0000110110000
        expect2 = target_pixelmap.edit_distances(
            pal.ID)[2][0b00010101010000000110110000]

        self.assertEqual(expect0, diff[0, 0])
        self.assertEqual(expect2, diff[0, 1])
Beispiel #10
0
    def __init__(self):
        load = loader.Loader("TETRIS")
        load.read()

        memory = mmu.MMU(load.data)
        processor = cpu.CPU(memory)
        display = video.Video()

        display.mainloop(processor.step)
Beispiel #11
0
def generate_video_list(items):

    # returns list of video objects

    video_list = []

    for item in items:
        title = item['snippet']['title']
        v = video.Video(title)
        video_list.append(v)
    return video_list
Beispiel #12
0
 def record(self):
     if self._RECORDING:
         self.video.close()
         self._RECORDING = False
         self.rec_action.setIcon(
             QtGui.QIcon(ICONPATH + "button_black_rec.png"))
     else:
         w, h = self.view.proi._w, self.view.proi._h
         self.video = video.Video(w, h)
         self._RECORDING = True
         self.rec_action.setIcon(
             QtGui.QIcon(ICONPATH + "button_red_rec.png"))
Beispiel #13
0
def submit():
    form = SubmitForm(csrf_enabled = False)
    if form.validate_on_submit():
	vid = video.Video()
	vid.title = form.title.data
	vid.link = form.link.data
	vid.submitter = form.submitter.data
	vid.author = form.author.data
	mongo.db.test_data.insert(vid.__dict__)
	return redirect(url_for('videos'))
    else:
	return render_template('submit.htmljinja', form=form)
Beispiel #14
0
 def video_processing(self):
     if not os.path.exists(r'C:\Temp\afr'):
         self.infopopup_class.open_popup(self.info1)
         return None
     if int(self.interval.text) <= 0:
         self.interval.text = ''
         self.infopopup_class.open_popup(self.info2)
         return None
     vid = video.Video(int(self.fps.text), int(self.start.text), int(self.interval.text), self.to_num.text, self.pdftitle.text)
     vid.main(self.mainpath)
     self.files.markup = True
     self.files.text = "[b]Done![/b]"
     self.files.font_size = '50sp'
     self.run_time += 1
def videoStart():
    myvideo = video.Video()
    time.sleep(1)
    myvideo.nextFrame()
    myvideo.testBackgroundFrame()

    while 1:
        myvideo.nextFrame()
        myvideo.testBackgroundFrame()
        myvideo.updateBackground()
        myvideo.compare()
        myvideo.showFrame()
        myvideo.testSettings()
        if myvideo.testDestroy():
            sys.exit()
Beispiel #16
0
 def recvid(self, Nframes, fps):
     self.pause()
     self.framerate(fps)
     t = []  #list for frametimes:
     w, h = self.view.proi._w, self.view.proi._h
     self.vid = video.Video(w, h, fps=fps)
     self.stream()
     for i in range(Nframes):
         f = self.capture()
         self.vid.append(f.data)
         t += [f.time]
     self.stop()
     dt = (diff(array(t)) / self.cps())
     fps_real = round(1. / dt.mean())
     print "fps achieved: " + str(fps_real)
     self.vid.close()
Beispiel #17
0
def video_test():
    issues = list()
    passed = True
    correctNumberOfFrames = 162
    correctNumberOfRows = 368
    correctNumberOfColumns = 640
    pathToTestVideo = r"testFiles\SampleVideo_640x360_1mb.mp4"
    videoTest = video.Video(pathToTestVideo)
    if videoTest.numberOfFrames != correctNumberOfFrames:
        issues.append("Number of frames is not correct")
    if videoTest.numberOfRows != correctNumberOfRows:
        issues.append("Number of rows is not correct")
    if videoTest.numberOfColumns != correctNumberOfColumns:
        issues.append("Number of columns is not correct")
    if len(issues) > 0:
        passed = False
    return (passed, issues)
Beispiel #18
0
def from_camera(cap, out=None):
    """Take input from webcam
    Arguments:
        cap {cv2.VideoCapture} -- The input videon  stream in this case
                                  a webcam
    Keyword Arguments:
        out {string} -- An output video file location (default: {None})
    """
    vid = video.Video(cap, out)
    frame = 0
    while True:
        vid.shoelace_finding(frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        frame += 1
    cap.release()
    cv2.destroyAllWindows()
Beispiel #19
0
def demo():

    # Inicializar video para mostrado en pantalla
    v = video.Video()
    v.set_mode_2d()

    # Inicializar webcam
    video_capture = cv2.VideoCapture(prm["camera_device_index"])
    cam_width = video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)
    cam_height = video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)

    # Inicializar detector de cara
    face_detector = FaceDetector()

    def loop(screen, delta_t, window_w, window_h):

        # Obtener frame de video
        _, cam_frame = video_capture.read()

        # No se bien por que pero hay que espejar la imagen para que las
        # coordenadas sean las que esperamos
        cam_frame = cv2.flip(cam_frame, 1)

        # Detectar caras
        face_rect = face_detector.detect(cam_frame)

        # Dibujar rectangulos sobre caras
        if face_rect is not None:
            face_rect_draw(cam_frame, face_rect)

        # Convertir color, necesario para dibujado en pygame
        cam_frame = cv2.cvtColor(cam_frame, cv2.COLOR_BGR2RGB)

        # Intercambiar filas por columnas de la imagen, necesario para dibujado
        # en pygame
        cam_frame = cam_frame.swapaxes(0,1)

        # Dibujar en pantalla de pygame
        surf = pygame.surfarray.make_surface(cam_frame)
        surf = pygame.transform.scale(surf, (window_w, window_h))
        screen.blit(surf, (0, 0))

    v.start_loop(loop)

    video_capture.release()
Beispiel #20
0
    def editor_setup(self, source):
        self.source = source

        # load the video
        self.video = video.Video(source)

        # destroy the placeholder text since we have the video
        if self.placeholder:
            self.placeholder.destroy()

        # create a canvas to put the loaded video
        self.video_canvas = tkinter.Canvas(self.window,
                                           width=self.video.width,
                                           height=self.video.height)
        self.video_canvas.pack()

        # create a slider to control the preview of the video
        self.scale = tkinter.Scale(self.window,
                                   from_=0,
                                   to=1,
                                   resolutio=-1,
                                   orient=tkinter.HORIZONTAL,
                                   length=self.video.width,
                                   sliderlength=10)
        self.scale.pack()

        # create a canvas to show when is marked
        self.marker_canvas_height = 15
        self.marker_canvas = tkinter.Canvas(self.window,
                                            width=self.video.width,
                                            height=self.marker_canvas_height,
                                            background='black')
        self.marker_canvas.pack()

        # the actual storage of all markers
        self.markers = []

        # create a button to mark the current time
        self.button = tkinter.Button(self.window,
                                     text='Mark',
                                     command=self.mark)
        self.button.pack()

        self.update(10)
Beispiel #21
0
def main():
    vid = video.Video()
    start_button = button.InputButton(pin_number=INPUT_PINS[0])

    # all of the lights
    light_manager = light.LightManager(pins=OUTPUT_PINS)

    twit = twitter.Twitter()

    # map the creating a gif
    def light_show(channel):
        light_manager.final_countdown()
        gif_path = vid.make_gif()
        light_manager.flash()
        twit.post_image(gif_path)
        print('cycle complete')

    start_button.add_onclick_callback(light_show)
    print('waiting forever...')
    while True:
        time.sleep(1)
Beispiel #22
0
    def calling_handler(self, nick, dst_udp_port):
        """
            Nombre: calling_handler
            Descripcion: Funcion que responde a una solicitud de llamada.
            Argumentos:
                -nick: nick del usuario
                -dst_udp_port: puerto udp destino
            Retorno: Ninguno
        """
        # Hallamos la informacion del usuario
        user_info = self.users_descubrimiento.query(nick)
        dst_ip = user_info[1]
        dst_port = user_info[2]

        # Si no estamos en llamada
        if not self.video_client.flag_en_llamada:
            # Pregunta si quieres aceptar la llamada
            res = self.gui.yesNoBox("Llamada entrante", nick)
            if res:
                msg = "CALL_ACCEPTED {} {}".format(self.video_client.nick, self.udp_port)
                self.send_msg(msg, dst_ip, dst_port)
                self.gui.setStatusbar("En llamada.", 0)

                # Actualizamos la informacion necesaria en la app
                self.video_client.flag_en_llamada = True
                self.video_client.dst_ip = dst_ip
                self.video_client.dst_port = dst_port

                # Comenzamos la llamada
                self.video_client.video = video.Video(self.video_client, dst_ip,
                                                      int(self.udp_port), int(dst_udp_port))
                self.video_client.video.llamada()

            else:
                msg = "CALL_DENIED {}".format(nick)
                self.send_msg(msg, dst_ip, dst_port)

        else:
            msg = "CALL_BUSY"
            self.send_msg(msg, dst_ip, dst_port)
Beispiel #23
0
    def __init__(
            self, filename: str,
            every_n_video_frames: int = 1,
            audio_bitrate: int = 14700,
            audio_normalization: float = None,
            max_bytes_out: int = None,
            video_mode: VideoMode = VideoMode.HGR,
            palette: Palette = Palette.NTSC,
    ):
        self.filename = filename  # type: str
        self.every_n_video_frames = every_n_video_frames  # type: int
        self.max_bytes_out = max_bytes_out  # type: int
        self.video_mode = video_mode  # type: VideoMode
        self.palette = palette  # type: Palette

        self.audio = audio.Audio(
            filename, bitrate=audio_bitrate,
            normalization=audio_normalization)  # type: audio.Audio

        self.frame_grabber = frame_grabber.FileFrameGrabber(
            filename, mode=video_mode, palette=self.palette)
        self.video = video.Video(
            self.frame_grabber,
            ticks_per_second=self.audio.sample_rate,
            mode=video_mode,
            palette=self.palette
        )  # type: video.Video

        # Byte offset within TCP stream
        self.stream_pos = 0  # type: int

        # Current audio tick opcode count within movie stream.
        self.ticks = 0  # type: int

        # Tracks internal state of player virtual machine
        self.state = machine.Machine()

        # Currently operating on AUX memory bank?
        self.aux_memory_bank = False
Beispiel #24
0
    def _Calculate(self):
        video_capture = video.Video(self._VIDEO_FILE_NAME)
        histograms = [(time,
                       bmp.ColorHistogram(ignore_color=self._WHITE,
                                          tolerance=8))
                      for time, bmp in video_capture.GetVideoFrameIter()]

        start_histogram = histograms[0][1]
        final_histogram = histograms[-1][1]
        total_distance = start_histogram.Distance(final_histogram)

        def FrameProgress(histogram):
            if total_distance == 0:
                if histogram.Distance(final_histogram) == 0:
                    return 1.0
                else:
                    return 0.0
            return 1 - histogram.Distance(final_histogram) / total_distance

        time_completeness_list = [(time, FrameProgress(hist))
                                  for time, hist in histograms]
        return time_completeness_list
Beispiel #25
0
def save_video_attribute(inputFilepath="video_search.txt",
                         outputFilepath="videos.csv",
                         overwrite=True,
                         inputAttributeName=None):
    """
	TODO: C++ pandas integration?
	:param inputFilepath:
	:param outputFilepath:
	"""
    if (inputAttributeName is None):
        attributeList = vi.Video.getAttributeList()
    else:
        attributeList = [inputAttributeName]
    for attributeName in attributeList:
        videos = pd.read_csv(inputFilepath,
                             sep=',',
                             names=['filePath'],
                             index_col=None)
        videos = pd.DataFrame(videos,
                              columns=['filePath'].extend(attributeList))
        (totalRows, _) = videos.shape
        outputFilepathPerAttribute = os.path.join(
            os.path.dirname(outputFilepath),
            os.path.splitext(outputFilepath)[0] + "_" + attributeName + ".csv")
        if (os.path.exists(outputFilepathPerAttribute) and overwrite):
            file = open(outputFilepathPerAttribute, 'wb')
            attributesHeader = 'filePath,' + attributeName
            file.write(attributesHeader + '\n')
        else:
            file = open(outputFilepathPerAttribute, 'ab')
        for index, videoLine in videos.iterrows():
            print videoLine['filePath']
            video = vi.Video(videoLine['filePath'], videos=videos)
            read = video[attributeName]
            file.write(','.join(
                [str(videoLine['filePath']),
                 str(video[attributeName])]) + '\n')
Beispiel #26
0
    def call_accepted_handler(self, nick, dst_udp_port):
        """
            Nombre: call_end_handler
            Descripcion: Funcion que comienza una llamada tras ser aceptada.
            Argumentos:
                -nick: nick del usuario
                -dst_udp_port: puerto udp destino
            Retorno: Ninguno
        """
        if not self.video_client.flag_en_llamada:
            user_info = self.users_descubrimiento.query(nick)
            dst_ip = user_info[1]

            self.gui.infoBox("Información de llamada", "{} ha aceptado tu llamada.".format(nick))
            self.gui.setStatusbar("En llamada.", 0)

            # Actualizamos la informacion necesaria en la app
            self.video_client.flag_en_llamada = True
            self.video_client.dst_ip = dst_ip
            self.video_client.dst_port = user_info[2]

            # Comenzamos la llamada
            self.video_client.video = video.Video(self.video_client, dst_ip, int(self.udp_port), int(dst_udp_port))
            self.video_client.video.llamada()
Beispiel #27
0
def generate_h5(input_video, input_users, output):

    with h5py.File(output + '.h5', "w") as file:
        videos = get_videos_names(input_video)

        for video_name in videos:
            actual_video = video.Video(os.path.join(input_video, video_name))
            group = file.create_group(actual_video.name)
            asciiList = [
                n.encode("ascii", "ignore") for n in actual_video.name
            ]
            group.create_dataset(
                'video_name', (len(asciiList), 1), "|S3",
                asciiList)  #For python 2 = |S3, for python 3 = <U3
            asciiList = [
                n.encode("ascii", "ignore") for n in actual_video.path
            ]
            group.create_dataset('video_path', (len(asciiList), 1), "|S3",
                                 asciiList)
            asciiList = [
                n.encode("ascii", "ignore") for n in actual_video.extension
            ]
            group.create_dataset('video_extension', (len(asciiList), 1), "|S3",
                                 asciiList)
            group.create_dataset('fps', (1, ), 'f', actual_video.fps)
            group.create_dataset('frames', (1, ), 'i', actual_video.frames)
            user_frames = users_frames_to_list(
                os.path.join(input_users, actual_video.name))

            #print (user_frames)
            if np.amax(user_frames) > 1:  #is csv with frame ID
                if actual_video.frames < np.amax(user_frames):
                    print(actual_video.name, "\t", actual_video.frames, "\t",
                          np.amax(user_frames), "\t", actual_video.fps,
                          "\tPROBLEM!!!!!!!\tPROBLEM!!!!!!!")
                else:
                    print(actual_video.name, "\t", actual_video.frames, "\t",
                          np.amax(user_frames), "\t", actual_video.fps)
                    group.create_dataset('user_frames', (user_frames.shape),
                                         'i', user_frames)
                    user_summary = user_picks_expand(user_frames,
                                                     actual_video.frames)
                    group.create_dataset('user_summary', (user_summary.shape),
                                         'i', user_summary)

            else:  #is csv without frame ID, vector_len = video_frames
                if actual_video.frames * 0.2 < len(
                        user_frames[0]):  #Summe dataset case
                    print(actual_video.name, "\t", actual_video.frames, "\t",
                          len(user_frames[0]), "\t", actual_video.fps)
                    #debug_count_ones(user_frames)
                    #print (actual_video.name)
                    #user_summary=expand_zeros(user_frames,actual_video.frames)
                    #user_summary=
                    #debug_count_ones(user_frames)

                    group.create_dataset('user_summary', (user_frames.shape),
                                         'i', user_frames)
                    user_frames_with_ID = user_picks_contract(user_frames)
                    group.create_dataset('user_frames',
                                         (user_frames_with_ID.shape), 'i',
                                         user_frames_with_ID)
                else:
                    print(actual_video.name, "\t", actual_video.frames, "\t",
                          len(user_frames[0]), "\t", actual_video.fps,
                          "\tPROBLEM!!!!!!!\tPROBLEM!!!!!!!")
Beispiel #28
0
# Fall detector main
# Kim Salmi, kim.salmi(at)iki(dot)fi
# http://tunn.us/arduino/falldetector.php
# License: GPLv3

import video
import time
import sys

video = video.Video(0)
time.sleep(1.0) # let camera autofocus + autosaturation settle
video.nextFrame()
video.testBackgroundFrame()

while 1:
	video.nextFrame()
	video.testBackgroundFrame()
	video.updateBackground()
	video.compare()
	video.showFrame()
	video.testSettings()
	if video.testDestroy():
		sys.exit()
Beispiel #29
0
def ParseCreateVideoParam(data):
    v = video.Video()

    try:
        jdata = json.loads(data)

        # 校验参数合法性
        # 英文名称
        if not jdata.has_key("name_en") or (0 == len(jdata["name_en"])):
            logging.error("[%s][%d] Get name_en failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get name_en failed!")

        v.name_en = jdata["name_en"]

        # 中文名称
        if not jdata.has_key("name_ch") or (0 == len(jdata["name_ch"])):
            logging.error("[%s][%d] Get name_ch failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get name_ch failed!")

        v.name_ch = jdata["name_ch"]

        # 缩略图URL
        if not jdata.has_key("poster") or (0 == len(jdata["poster"])):
            logging.error("[%s][%d] Get poster failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get poster failed!")

        v.poster = jdata["poster"]

        # 视频时长(秒)
        if not jdata.has_key("duration") or (0 == jdata["duration"]):
            logging.error("[%s][%d] Get duration failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get duration failed!")

        v.duration = jdata["duration"]

        # 播放地址
        if not jdata.has_key("url") or (0 == len(jdata["url"])):
            logging.error("[%s][%d] Get url failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get url failed!")

        v.url = jdata["url"]

        # 字幕内容
        if not jdata.has_key("words_script") or (0 == len(
                jdata["words_script"])):
            logging.error("[%s][%d] Get words_script failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get words_script failed!")

        v.words_script = jdata["words_script"]

        # 视频清晰度
        if not jdata.has_key("definition") or (0 == len(jdata["definition"])):
            logging.error("[%s][%d] Get definition failed! data:%s" %
                          (__file__, sys._getframe().f_lineno, data))
            return (None, comm.ERR_PARAM_INVALID, "Get definition failed!")

        v.definition = jdata["definition"]

        return (v, comm.OK, "Ok")
    except Exception as e:
        logging.error("[%s][%d] Create video failed! data:%s e:%s" %
                      (__file__, sys._getframe().f_lineno, data, str(e)))
        return (None, comm.ERR_UNKNOWN, str(e))
    return (None, comm.ERR_UNKNOWN, "Parse create video parameter failed!")
Beispiel #30
0
# Fall detector main
# Kim Salmi, kim.salmi(at)iki(dot)fi
# http://tunn.us/arduino/falldetector.php
# License: GPLv3

import video
import time
import sys
import numpy as np
import cv2
import time

video = video.Video()
time.sleep(1.0) # let camera autofocus + autosaturation settle
video.nextFrame()
video.testBackgroundFrame()

while 1:
	video.nextFrame()
	video.testBackgroundFrame()
	video.updateBackground()
	video.compare()
	video.showFrame()
	video.testSettings()
	if video.testDestroy():
		sys.exit()