Esempio n. 1
0
def generate():
    global outputFrame, lastFrame, lock
    # loop over frames from the output stream
    timer = fpstimer.FPSTimer(15)
    while True:
        # wait until the lock is acquired
        with lock:
            # check if the output frame is available, otherwise skip
            # the iteration of the loop
            if outputFrame is None:
                continue
            if outputFrame is not None and lastFrame is not None:
                if (outputFrame == lastFrame).all():
                    continue
            # encode the frame in JPEG format
            (flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
            # ensure the frame was successfully encoded
            if not flag:
                continue
        lastFrame = outputFrame
        # yield the output frame in the byte format
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) +
               b'\r\n')
        timer.sleep()
Esempio n. 2
0
def play_video(isMidi, end_frame):

    # Alters CLI interface for Bad Apple!! (only works for Windows)
    os.system('color F0')

    # Band-aid fix for audio-syncrhonization issues across different platforms. Might need to look into the root cause.
    if platform.system() == 'Windows':
        time.sleep(0)

    elif platform.system() == 'Linux':
        time.sleep(0.75)

    timer = fpstimer.FPSTimer(30)

    if isMidi is True:
        start_frame = 30
    else:
        start_frame = 1

    for frame_number in range(start_frame, end_frame - 1):
        sys.stdout.write("\r" + ASCII_LIST[frame_number])
        timer.sleep()

    sys.stdout.write('\n')
    os.system('color 07')
Esempio n. 3
0
def main():
    global _t
    global _handler
    global events
    if not _t:
        _t = threading.Thread(target=worker)
        _t.daemon = True
        _t.start()
    stick_x = 0.0
    stick_y = 0.0
    buttons = 0
    libmario.init(find_floor_handler, None, None, find_water_level_handler)
    timer = fpstimer.FPSTimer(30)
    try:
        while True:
            while len(events) > 0:
                for event in events[0]:
                    if event.code == "ABS_X":
                        stick_x = float(event.state) / 32768.0
                    elif event.code == "ABS_Y":
                        stick_y = float(event.state) / 32768.0
                    elif event.code == "ABS_RX":
                        gpd_input = "Right Stick X"
                    elif event.code == "ABS_RY":
                        gpd_input = "Right Stick Y"
                    elif event.code == "BTN_SOUTH":
                        if event.state == 1:
                            buttons |= A_BUTTON
                        else:
                            buttons &= ~A_BUTTON
                    elif event.code == "BTN_WEST":
                        if event.state == 1:
                            buttons |= B_BUTTON
                        else:
                            buttons &= ~B_BUTTON
                    elif event.code == "ABS_Z":
                        if event.state == 255:
                            buttons |= Z_TRIG
                        else:
                            buttons &= ~Z_TRIG
                    elif event.code != "SYN_REPORT":
                        print(event.code + ':' + str(event.state))
                events.pop(0)

            libmario.step(buttons, c_float(stick_x), c_float(stick_y))
            pos = Vec3f()
            vel = Vec3f()
            libmario.getMarioPosition(pos)
            libmario.getMarioVelocity(vel)

            print(
                'Position: %8.2f %8.2f %8.2f  Velocity: %8.2f %8.2f %8.2f Buttons: 0x%08X Anim: 0x%02X AnimFrame: %d'
                % (pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], buttons,
                   libmario.getMarioAnimIndex(), libmario.getMarioAnimFrame()))

            timer.sleep()
    except KeyboardInterrupt:
        print("Ctrl+C pressed...")
        sys.exit(0)
Esempio n. 4
0
    def __init__(self):

        self.timer = fpstimer.FPSTimer(60)

        self.lastTime = int(round(time.time() * 1000))

        self.currentFps = 0
        self.fpsCounter = 0
Esempio n. 5
0
def test_basic():
    # NOTE: This test takes about 45 seconds.
    timer = fpstimer.FPSTimer()
    random.seed(42)

    for testFps in range(10, 110, 10): # Test fps rates 10, 20, ... up to 100.
        for trial in range(5): # Do five trials for each fps rate.

            timer = fpstimer.FPSTimer(testFps)

            start = time.time()
            for i in range(testFps): # Run enough timer.sleep() calls for 1 second.
                pass
                if random.randint(0, 1) == 1:
                    time.sleep(1 / (testFps * 2))
                timer.sleep()
            trialTime = time.time() - start

            assert trialTime < (1 + ACCEPTABLE_DEVIATION), 'Failed for testFps == %s, trialTime was %s' % (testFps, trialTime)
def play_video(total_frames):
    # os.system('color F0')
    os.system('mode 150, 500')

    timer = fpstimer.FPSTimer(30)

    start_frame = 0

    for frame_number in range(start_frame, total_frames):
        sys.stdout.write("\r" + ASCII_LIST[frame_number])
        timer.sleep()
Esempio n. 7
0
def update_db():
    timer = fpstimer.FPSTimer(0.3)
    last_inside = -999
    last_down = 0
    last_up = 0
    while True:
        inside = totalDown - totalUp
        if totalUp != last_up:
            database.leave_store(totalUp - last_up)
            last_up = totalUp
        if totalDown != last_down:
            database.enter_store(totalDown - last_down)
            last_down = totalDown
        if inside != last_inside:
            database.update_status(inside)
            last_inside = inside
        timer.sleep()
Esempio n. 8
0
def test_ctor():
    assert fpstimer.FPSTimer()._framesPerSecond == 60 # Test with no argument.
    assert fpstimer.FPSTimer(None)._framesPerSecond == 60 # Test with None argument.
    assert fpstimer.FPSTimer(1)._framesPerSecond == 1 # Test with 60 argument.
    assert fpstimer.FPSTimer(1.0)._framesPerSecond == 1 # Test with 60 argument.

    assert fpstimer.FPSTimer.DEFAULT_FPS == 60 # Test that this constant hasn't changed.

    # Test invalid ctor arguments:
    with pytest.raises(TypeError):
        fpstimer.FPSTimer('invalid')
    with pytest.raises(ValueError):
        fpstimer.FPSTimer(0)
    with pytest.raises(ValueError):
        fpstimer.FPSTimer(-1)
Esempio n. 9
0
def loop(data):
    while not data['flag']:
        pass

    print(data['file'])
    data['msg_count'] = 0
    file = data['file']
    model = data['model']
    delay = data['delay']
    pub_topic = data['pub_topic']
    client = data['client']
    lps = data['lps']

    import fpstimer
    timer = fpstimer.FPSTimer(lps)  # Make a timer that is set for 60 fps.

    num_lines = sum(1 for line in open(file, 'r'))
    pbar = tqdm(total=num_lines, leave=False, unit='lines')
    # telegraf/mart-ubuntu-s-1vcpu-1gb-sgp1-01/Model-PRO
    cnt = 0
    with open(file, 'r') as f:
        for line in f:
            # sleep(delay)
            # sleep(0.00066)
            # print(line)
            parsed = parse_line(line)
            topic = parsed['tags']['topic'].split("/")[-2]
            topic = "DUSTBOY/{}/{}/status".format(model, topic)
            parsed['timestamp'] = str(parsed['time']) + '000'
            parsed['tags']['topic'] = topic
            parsed['batch_id'] = data['batch_id']
            client.publish(pub_topic,
                           json.dumps(parsed, sort_keys=True),
                           qos=0)
            pbar.update(1)
            timer.sleep(
            )  # Pause just enough to have a 1/60 second wait since last fpstSleep() call.
            cnt += 1
        pbar.close()
        # print('cnt=', cnt)
        sleep(0.00066)
        # print('msg_count =  ', data['msg_count'])
        client.disconnect()
        # client.loop_stop()
        raise SystemExit
Esempio n. 10
0
def play_video(isMidi):
    os.system('color F0')
    # os.system('mode 150, 500')
    if platform.system() == 'Windows':
        time.sleep(0)

    elif platform.system() == 'Linux':
        time.sleep(0.5)

    timer = fpstimer.FPSTimer(30)

    if isMidi is True:
        start_frame = 40
    else:
        start_frame = 1

    for frame_number in range(start_frame, 6570):
        sys.stdout.write("\r" + ASCII_LIST[frame_number])
        timer.sleep()

    os.system('color 07')
def play_video(isMidi):
    os.system('color F0')
    os.system('mode 150, 500')

    timer = fpstimer.FPSTimer(30)

    if isMidi is True:
        start_frame = 40
    else:
        start_frame = 1

    for frame_number in range(start_frame, 6570):
        start_time = time.time()
        file_name = r"TextFiles/" + "bad_apple" + str(frame_number) + ".txt"
        with open(file_name, 'r') as f:
            sys.stdout.write("\r" + f.read())
        compute_delay = float(time.time() - start_time)
        delay_duration = frame_interval - compute_delay
        if delay_duration < 0:
            delay_duration = 0
        timer.sleep()

    os.system('color 07')
Esempio n. 12
0
def print_frames(frames, fps=30, loop=True, reference=False, filename=''):
    """
    output frames strings in given list one after the other. basically like a film projector

    depending on the terminal, you may see images overlap or flickering for random reasons.
    playing around with the fps might help out with that

    the reference flag will start up the video in a separate vlc window.
    the terminal might start before the vlc player is ready to play though
    """
    input('Successfully processed video. Press enter to play ascii video...')

    fps_timer = fpstimer.FPSTimer(fps)

    if reference:
        # creating vlc media player object
        media = vlc.MediaPlayer(filename)

        # start playing video
        media.play()
        # time.sleep(.4)

    clear()
    start = timer()
    while True:
        try:
            for frame in frames:
                # clear()  # makes the screen flicker and is super slow
                print(frame, end='')
                fps_timer.sleep()
                # time.sleep(rate)  # not super accurate but w/e
            if not loop:
                break
        except KeyboardInterrupt:
            break
    end = timer()
    print(f'played video for {end - start : .2f}s')
Esempio n. 13
0
def count_people():
    global outputFrame, totalDown, totalUp
    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-p",
                    "--prototxt",
                    default="mobilenet_ssd/MobileNetSSD_deploy.prototxt",
                    help="path to Caffe 'deploy' prototxt file")
    ap.add_argument("-m",
                    "--model",
                    default="mobilenet_ssd/MobileNetSSD_deploy.caffemodel",
                    help="path to Caffe pre-trained model")
    ap.add_argument("-i",
                    "--input",
                    type=str,
                    default="videos/example_01.mp4",
                    help="path to optional input video file")
    ap.add_argument("-o",
                    "--output",
                    type=str,
                    help="path to optional output video file")
    ap.add_argument("-c",
                    "--confidence",
                    type=float,
                    default=0.4,
                    help="minimum probability to filter weak detections")
    ap.add_argument("-s",
                    "--skip-frames",
                    type=int,
                    default=30,
                    help="# of skip frames between detections")
    args = vars(ap.parse_args())

    # initialize the list of class labels MobileNet SSD was trained to
    # detect
    CLASSES = [
        "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus",
        "car", "cat", "chair", "cow", "diningtable", "dog", "horse",
        "motorbike", "person", "pottedplant", "sheep", "sofa", "train",
        "tvmonitor"
    ]

    # load our serialized model from disk
    print("[INFO] loading model...")
    net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

    # if a video path was not supplied, grab a reference to the webcam
    if not args.get("input", False):
        print("[INFO] starting video stream...")
        vs = VideoStream(src=0).start()
        time.sleep(2.0)

    # otherwise, grab a reference to the video file
    else:
        print("[INFO] opening video file...")
        vs = cv2.VideoCapture(args["input"])

    # initialize the video writer (we'll instantiate later if need be)
    writer = None

    # initialize the frame dimensions (we'll set them as soon as we read
    # the first frame from the video)
    W = None
    H = None

    # instantiate our centroid tracker, then initialize a list to store
    # each of our dlib correlation trackers, followed by a dictionary to
    # map each unique object ID to a TrackableObject
    ct = CentroidTracker(maxDisappeared=40, maxDistance=50)
    trackers = []
    trackableObjects = {}

    # initialize the total number of frames processed thus far, along
    # with the total number of objects that have moved either up or down
    totalFrames = 0
    totalDown = 0
    totalUp = 0

    # start the frames per second throughput estimator
    fps = FPS().start()
    timer = fpstimer.FPSTimer(30)

    # loop over frames from the video stream
    while True:
        URL = "http://192.168.29.211:8080/shot.jpg"
        # img_arr = np.array(bytearray(urllib.request.urlopen(URL).read()), dtype=np.uint8)
        # img = cv2.imdecode(img_arr, -1)
        frame = vs.read()
        frame = frame[1] if args.get("input", False) else frame

        # if we are viewing a video and we did not grab a frame then we
        # have reached the end of the video
        if args["input"] is not None and frame is None:
            # break
            vs.release()
            vs = cv2.VideoCapture(args["input"])
            continue

        # resize the frame to have a maximum width of 500 pixels (the
        # less data we have, the faster we can process it), then convert
        # the frame from BGR to RGB for dlib
        frame = imutils.resize(frame, width=500)
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # if the frame dimensions are empty, set them
        if W is None or H is None:
            (H, W) = frame.shape[:2]

        # if we are supposed to be writing a video to disk, initialize
        # the writer
        if args["output"] is not None and writer is None:
            fourcc = cv2.VideoWriter_fourcc(*"MJPG")
            writer = cv2.VideoWriter(args["output"], fourcc, 30, (W, H), True)

        # initialize the current status along with our list of bounding
        # box rectangles returned by either (1) our object detector or
        # (2) the correlation trackers
        status = "Waiting"
        rects = []

        # check to see if we should run a more computationally expensive
        # object detection method to aid our tracker
        if totalFrames % 30 == 0:
            # set the status and initialize our new set of object trackers
            status = "Detecting"
            trackers = []

            # convert the frame to a blob and pass the blob through the
            # network and obtain the detections
            blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)
            net.setInput(blob)
            detections = net.forward()

            # loop over the detections
            for i in np.arange(0, detections.shape[2]):
                # extract the confidence (i.e., probability) associated
                # with the prediction
                confidence = detections[0, 0, i, 2]

                # filter out weak detections by requiring a minimum
                # confidence
                if confidence > 0.4:
                    # extract the index of the class label from the
                    # detections list
                    idx = int(detections[0, 0, i, 1])

                    # if the class label is not a person, ignore it
                    if CLASSES[idx] != "person":
                        continue

                    # compute the (x, y)-coordinates of the bounding box
                    # for the object
                    box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
                    (startX, startY, endX, endY) = box.astype("int")

                    # construct a dlib rectangle object from the bounding
                    # box coordinates and then start the dlib correlation
                    # tracker
                    tracker = dlib.correlation_tracker()
                    rect = dlib.rectangle(startX, startY, endX, endY)
                    tracker.start_track(rgb, rect)

                    # add the tracker to our list of trackers so we can
                    # utilize it during skip frames
                    trackers.append(tracker)

        # otherwise, we should utilize our object *trackers* rather than
        # object *detectors* to obtain a higher frame processing throughput
        else:
            # loop over the trackers
            for tracker in trackers:
                # set the status of our system to be 'tracking' rather
                # than 'waiting' or 'detecting'
                status = "Tracking"

                # update the tracker and grab the updated position
                tracker.update(rgb)
                pos = tracker.get_position()

                # unpack the position object
                startX = int(pos.left())
                startY = int(pos.top())
                endX = int(pos.right())
                endY = int(pos.bottom())

                # add the bounding box coordinates to the rectangles list
                rects.append((startX, startY, endX, endY))

        # draw a horizontal line in the center of the frame -- once an
        # object crosses this line we will determine whether they were
        # moving 'up' or 'down'
        cv2.line(frame, (0, H // 2), (W, H // 2), (0, 255, 255), 2)

        # use the centroid tracker to associate the (1) old object
        # centroids with (2) the newly computed object centroids
        objects = ct.update(rects)

        # loop over the tracked objects
        for (objectID, centroid) in objects.items():
            # check to see if a trackable object exists for the current
            # object ID
            to = trackableObjects.get(objectID, None)

            # if there is no existing trackable object, create one
            if to is None:
                to = TrackableObject(objectID, centroid)

            # otherwise, there is a trackable object so we can utilize it
            # to determine direction
            else:
                # the difference between the y-coordinate of the *current*
                # centroid and the mean of *previous* centroids will tell
                # us in which direction the object is moving (negative for
                # 'up' and positive for 'down')
                y = [c[1] for c in to.centroids]
                direction = centroid[1] - np.mean(y)
                to.centroids.append(centroid)

                # check to see if the object has been counted or not
                if not to.counted:
                    # if the direction is negative (indicating the object
                    # is moving up) AND the centroid is above the center
                    # line, count the object
                    if direction < 0 and centroid[1] < H // 2:
                        totalUp += 1
                        to.counted = True

                    # if the direction is positive (indicating the object
                    # is moving down) AND the centroid is below the
                    # center line, count the object
                    elif direction > 0 and centroid[1] > H // 2:
                        totalDown += 1
                        to.counted = True

            # store the trackable object in our dictionary
            trackableObjects[objectID] = to

            # draw both the ID of the object and the centroid of the
            # object on the output frame
            text = "ID {}".format(objectID)
            cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
            cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)

        # construct a tuple of information we will be displaying on the
        # frame
        info = [
            ("Up", totalUp),
            ("Down", totalDown),
            ("Status", status),
        ]

        # loop over the info tuples and draw them on our frame
        for (i, (k, v)) in enumerate(info):
            text = "{}: {}".format(k, v)
            cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

        # check to see if we should write the frame to disk
        if writer is not None:
            writer.write(frame)

        # show the output frame
        cv2.imshow("Frame", frame)
        key = cv2.waitKey(1) & 0xFF
        outputFrame = frame

        # if the `q` key was pressed, break from the loop
        if key == ord("q"):
            break

        # increment the total number of frames processed thus far and
        # then update the FPS counter
        totalFrames += 1
        fps.update()
        timer.sleep()

    # stop the timer and display FPS information
    fps.stop()
    print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
    print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

    # check to see if we need to release the video writer pointer
    if writer is not None:
        writer.release()

    # if we are not using a video file, stop the camera video stream
    if not args.get("input", False):
        vs.stop()

    # otherwise, release the video file pointer
    else:
        vs.release()

    # close any open windows
    cv2.destroyAllWindows()
Esempio n. 14
0
def test_zero():
    timer = fpstimer.FPSTimer(60)
    time.sleep(0.1) # 0.1 seconds is much longer than the 1/60 that sleep() should at most pause for.
    assert timer.sleep() == 0 # sleep() should therefore not have any pause.
Esempio n. 15
0
 def setFps(self, numberOfFps):
     self.timer = fpstimer.FPSTimer(numberOfFps)