Example #1
0
def test_playback(address, port):
    """
    Tests NetGear Bare-minimum network playback capabilities
    """
    stream = None
    server = None
    client = None
    try:
        # open stream
        stream = VideoGear(source=return_testvideo_path()).start()
        # open server and client with default params
        client = NetGear(address=address, port=port, receive_mode=True)
        server = NetGear(address=address, port=port)
        # playback
        while True:
            frame_server = stream.read()
            if frame_server is None:
                break
            server.send(frame_server)  # send
            frame_client = client.recv()  # recv
    except Exception as e:
        if isinstance(e, (ZMQError, ValueError)) or address == "www.idk.com":
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
        if not (client is None):
            client.close()
Example #2
0
async def test_benchmark_NetGear():
    """
    Benchmark NetGear original in FPS
    """
    try:
        # open stream with valid source
        stream = VideoGear(source=return_testvideo_path()).start()
        # open server and client
        client = NetGear(receive_mode=True, pattern=1)
        server = NetGear(pattern=1)
        # start FPS handler
        fps = FPS().start()
        # playback
        while True:
            frame_server = stream.read()
            if frame_server is None:
                break
            fps.update()  # update
            server.send(frame_server)  # send
            frame_client = client.recv()  # recv
        stream.stop()
    except Exception as e:
        pytest.fail(str(e))
    finally:
        # close
        server.close()
        client.close()
        logger.info("NetGear approx. FPS: {:.2f}".format(fps.average_fps()))
Example #3
0
def test_PiGear_import():
    """
    Testing VideoGear Import -> assign to fail when PiGear class is imported
    """
    with pytest.raises(ImportError):
        stream = VideoGear(enablePiCamera=True, logging=True).start()
        stream.stop()
Example #4
0
def test_server_reliablity(options):
    """
    Testing validation function of WebGear API
    """
    server = None
    stream = None
    try:
        # define params
        server = NetGear(
            pattern=1,
            port=[5585] if "multiclient_mode" in options.keys() else 6654,
            logging=True,
            **options
        )
        stream = VideoGear(source=return_testvideo_path()).start()
        i = 0
        while i < random.randint(10, 100):
            frame_client = stream.read()
            i += 1
        # check if input frame is valid
        assert not (frame_client is None)
        # send frame without connection
        server.send(frame_client)
        server.send(frame_client)
    except Exception as e:
        if isinstance(e, (RuntimeError)):
            pytest.xfail("Reconnection ran successfully.")
        else:
            logger.exception(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
Example #5
0
def test_primary_mode(receive_mode):
    """
    Tests NetGear Bare-minimum network playback capabilities
    """
    stream = None
    conn = None
    try:
        # open stream
        options_gear = {"THREAD_TIMEOUT": 60}
        stream = VideoGear(source=return_testvideo_path(),
                           **options_gear).start()
        frame = stream.read()
        # open server and client with default params
        conn = NetGear(receive_mode=receive_mode)
        if receive_mode:
            conn.send(frame)
        else:
            frame_client = conn.recv()
    except Exception as e:
        if isinstance(e, ValueError):
            pytest.xfail("Test Passed!")
        elif isinstance(e, (queue.Empty)):
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (conn is None):
            conn.close()
Example #6
0
def test_video_stablization():
    """
	Testing VideoGear's Video Stablization playback capabilities 
	"""
    try:
        #Video credit: http://www.liushuaicheng.org/CVPR2014/index.html
        Url = 'https://raw.githubusercontent.com/abhiTronix/Imbakup/master/Images/example4_train_input.mp4'
        #define params
        options = {
            'SMOOTHING_RADIUS': 5,
            'BORDER_SIZE': 10,
            'BORDER_TYPE': 'replicate',
            'CROP_N_ZOOM': True
        }
        #open stream
        stab_stream = VideoGear(source=Url,
                                stabilize=True,
                                logging=True,
                                **options).start()
        #playback
        while True:
            frame = stab_stream.read()  #read stablized frames
            if frame is None:
                break
        #clean resources
        stab_stream.stop()
    except Exception as e:
        pytest.fail(str(e))
Example #7
0
def test_playback():
	"""
	Tests NetGear Bare-minimum network playback capabilities
	"""
	try:
		#open stream
		stream = VideoGear(source=return_testvideo_path()).start()
		#open server and client with default params
		client = NetGear(receive_mode = True)
		server = NetGear()
		#playback
		while True:
			frame_server = stream.read()
			if frame_server is None: break
			server.send(frame_server) #send
			frame_client = client.recv() #recv
		#clean resources
		stream.stop()
		server.close()
		client.close()
	except Exception as e:
		if isinstance(e, (ZMQError, ValueError)):
			logger.debug(traceback.print_tb(e.__traceback__))
		else:
			pytest.fail(str(e))
Example #8
0
def test_patterns(pattern):
	"""
	Testing NetGear different messaging patterns
	"""
	#open stream
	try:
		stream = VideoGear(source=return_testvideo_path()).start()
		
		#define parameters
		options = {'flag' : 0, 'copy' : True, 'track' : False}
		client = NetGear(pattern = pattern, receive_mode = True, logging = True, **options)
		server = NetGear(pattern = pattern, logging = True, **options)
		#initialize 
		frame_server = None
		#select random input frame from stream
		i = 0
		while (i < random.randint(10, 100)):
			frame_server = stream.read()
			i+=1
		#check if input frame is valid
		assert not(frame_server is None)
		#send frame over network
		server.send(frame_server)
		frame_client = client.recv()
		#clean resources
		stream.stop()
		server.close()
		client.close()
		#check if recieved frame exactly matches input frame
		assert np.array_equal(frame_server, frame_client)
	except Exception as e:
		if isinstance(e, (ZMQError, ValueError)):
			logger.error(traceback.print_tb(e.__traceback__))
		else:
			pytest.fail(str(e))
Example #9
0
def run_camera(input_str, address, port, protocol):
    if input_str.isdigit():
        input = int(input_str)
    else: input = input_str

    # Open any video stream
    stream = VideoGear(source=input).start()
    # server = NetGear() # Locally
    server = NetGear(address=address, port=port, protocol=protocol,
                    pattern=0, receive_mode=False, logging=True) 

    # infinite loop until [Ctrl+C] is pressed
    while True:
        try:
            frame = stream.read()
            # read frames

            # check if frame is None
            if frame is None:
                # if True break the infinite loop
                break

            # do something with frame here

            # send frame to server
            server.send(frame)

        except KeyboardInterrupt:
            # break the infinite loop
            break

    # safely close video stream
    stream.stop()
Example #10
0
def test_compression():
	"""
	Testing NetGear's real-time frame compression capabilities
	"""
	try:
		#open streams
		stream = VideoGear(source=return_testvideo_path()).start()
		#define client parameters
		options = {'compression_param':cv2.IMREAD_COLOR} #read color image 
		client = NetGear(pattern = 1, receive_mode = True, logging = True, **options)
		#define server parameters
		options = {'compression_format': '.jpg', 'compression_param':[cv2.IMWRITE_JPEG_OPTIMIZE, 20]} #JPEG compression
		server = NetGear(pattern = 1, logging = True, **options)
		#send over network
		while True:
			frame_server = stream.read()
			if frame_server is None: break
			server.send(frame_server)
			frame_client = client.recv()
		#clean resources
		stream.stop()
		server.close()
		client.close()
	except Exception as e:
		if isinstance(e, (ZMQError, ValueError)):
			logger.error(traceback.print_tb(e.__traceback__))
		else:
			pytest.fail(str(e))
Example #11
0
def test_multiserver_mode():
	"""
	Testing NetGear's Multi-Server Mode with three unique servers
	"""
	try:
		#open network stream
		stream = VideoGear(source=return_testvideo_path()).start()

		#define and activate Multi-Server Mode
		options = {'multiserver_mode': True}

		#define a single client
		client = NetGear(port = ['5556', '5557', '5558'], pattern = 1, receive_mode = True, logging = True, **options)
		#define client-end dict to save frames inaccordance with unique port 
		client_frame_dict = {}

		#define three unique server
		server_1 = NetGear(pattern = 1, port = '5556', logging = True, **options) #at port `5556`
		server_2 = NetGear(pattern = 1, port = '5557', logging = True, **options) #at port `5557`
		server_3 = NetGear(pattern = 1, port = '5558', logging = True, **options) #at port `5558`

		#generate a random input frame
		frame_server = None
		i = 0
		while (i < random.randint(10, 100)):
			frame_server = stream.read()
			i+=1
		#check if input frame is valid
		assert not(frame_server is None)

		#send frame from Server-1 to client and save it in dict
		server_1.send(frame_server)
		unique_address, frame = client.recv()
		client_frame_dict[unique_address] = frame
		#send frame from Server-2 to client and save it in dict
		server_2.send(frame_server)
		unique_address, frame = client.recv()
		client_frame_dict[unique_address] = frame
		#send frame from Server-3 to client and save it in dict
		server_3.send(frame_server)
		unique_address, frame = client.recv()
		client_frame_dict[unique_address] = frame
		
		#clean all resources
		stream.stop()
		server_1.close()
		server_2.close()
		server_3.close()
		client.close()

		#check if recieved frames from each unique server exactly matches input frame
		for key in client_frame_dict.keys():
			assert np.array_equal(frame_server, client_frame_dict[key])

	except Exception as e:
		if isinstance(e, (ZMQError, ValueError)):
			logger.error(traceback.print_tb(e.__traceback__))
		else:
			pytest.fail(str(e)) 
Example #12
0
def run_camera(input_str, address, port, protocol, pattern=0, fps=25, client_plugins={}):
    """Runs the camera, sends messages

    Args:
        input_str (str): Path to video file **OR** an `int` for camera input
        address (str): URL of `OpenCV` server 
        port (int): Port of `OpenCV` server
        protocol (str): Protocol of of `OpenCV` server 
        pattern (int, optional): ZMQ Pattern. 0=`zmq.PAIR`, 1=`zmq.REQ/zmq.REP`; 2=`zmq.PUB,zmq.SUB`. Defaults to 0.
        fps (int, optional): Framerate for video capture. Defaults to 25.
    """
    if input_str.isdigit():
        input = int(input_str)
    else:
        input = input_str

    options = {'THREADED_QUEUE_MODE': False}
    if address == '':
        address = None
    # Open any video stream; `framerate` here is just for picamera
    stream = VideoGear(source=input, framerate=fps, **options).start()
    # server = NetGear() # Locally
    netgear_options = {'max_retries': 10, 'request_timeout': 10}
    server = NetGear(address=address, port=port, protocol=protocol,
                     pattern=pattern, receive_mode=False, logging=True, **netgear_options)

    # Plugin parsing
    c_plugs = load_image_detector_client_plugins(client_plugins)
    # infinite loop until [Ctrl+C] is pressed
    _prev_frame = None
    while True:
        # Sleep
        time.sleep(0.02)

        # Client plugins - before
        run_image_detector_plugins_before(client_plugins, 'client', None, None, _prev_frame)

        try:
            frame = stream.read()
            # check if frame is None
            if frame is None:
                logger.error('No frame available')
                break

            # Client plugins - after
            run_image_detector_plugins_after(client_plugins, 'client', 
                _conditional_send, [server, frame, c_plugs], np.copy(frame))
            _prev_frame = frame 

            # send frame to server
            # server.send(frame)

        except KeyboardInterrupt:
            # break the infinite loop
            break

    # safely close video stream
    stream.stop()
Example #13
0
def clean_videostabilize(videofile):

    # open any valid video stream with stabilization enabled(`stabilize = True`)
    stream_stab = VideoGear(videofile, stabilize=True).start()

    # open same stream without stabilization for comparison
    stream_org = VideoGear(source="test.mp4").start()

    # loop over
    while True:

        # read stabilized frames
        frame_stab = stream_stab.read()

        # check for stabilized frame if Nonetype
        if frame_stab is None:
            break

        # read un-stabilized frame
        frame_org = stream_org.read()

        # concatenate both frames
        output_frame = np.concatenate((frame_org, frame_stab), axis=1)

        # put text over concatenated frame
        cv2.putText(
            output_frame,
            "Before",
            (10, output_frame.shape[0] - 10),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.6,
            (0, 255, 0),
            2,
        )
        cv2.putText(
            output_frame,
            "After",
            (output_frame.shape[1] // 2 + 10, output_frame.shape[0] - 10),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.6,
            (0, 255, 0),
            2,
        )

        # Show output window
        cv2.imshow("Stabilized Frame", output_frame)

        # check for 'q' key if pressed
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break

    # close output window
    cv2.destroyAllWindows()

    # safely close both video streams
    stream_org.stop()
    stream_stab.stop()
Example #14
0
def test_bidirectional_mode(pattern, target_data, options):
    """
    Testing NetGear's Bidirectional Mode with different data-types
    """
    # initialize
    stream = None
    server = None
    client = None
    try:
        logger.debug("Given Input Data: {}".format(target_data))
        # open stream
        stream = VideoGear(source=return_testvideo_path()).start()
        # define params
        client = NetGear(pattern=pattern, receive_mode=True, **options)
        server = NetGear(pattern=pattern, **options)
        # get frame from stream
        frame_server = stream.read()
        assert not (frame_server is None)
        # check if target data is numpy ndarray
        if isinstance(target_data, np.ndarray):
            # sent frame and data from server to client
            server.send(target_data, message=target_data)
            # client receives the data and frame and send its data
            server_data, frame_client = client.recv(return_data=target_data)
            # server receives the data and cycle continues
            client_data = server.send(target_data, message=target_data)
            # logger.debug data received at client-end and server-end
            logger.debug("Data received at Server-end: {}".format(frame_client))
            logger.debug("Data received at Client-end: {}".format(client_data))
            assert np.array_equal(client_data, frame_client)
        else:
            # sent frame and data from server to client
            server.send(frame_server, message=target_data)
            # client receives the data and frame and send its data
            server_data, frame_client = client.recv(return_data=target_data)
            # server receives the data and cycle continues
            client_data = server.send(frame_server, message=target_data)
            # check if received frame exactly matches input frame
            assert np.array_equal(frame_server, frame_client)
            # logger.debug data received at client-end and server-end
            logger.debug("Data received at Server-end: {}".format(server_data))
            logger.debug("Data received at Client-end: {}".format(client_data))
            assert client_data == server_data
    except Exception as e:
        if isinstance(e, (ZMQError, ValueError)):
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
        if not (client is None):
            client.close()
Example #15
0
def test_CamGear_import():
    """
	Testing VideoGear Import - Passed if CamGear Class is Imported sucessfully
	"""
    try:
        Url = 'rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov'
        output_stream = VideoGear(source=Url).start()
        output_stream.stop()
    except Exception as e:
        pytest.fail(str(e))
Example #16
0
def detectFaceCam():
    options_webcam = {"exposure_compensation":0,"awb_mode": "sun", "sensor_mode": 0, "CAP_PROP_FRAME_WIDTH ":1920, "CAP_PROP_FRAME_HEIGHT":1080, "CAP_PROP_AUTOFOCUS": 'True'} # define tweak parameters

    try:
        video_stream = VideoGear(source=0, resolution=(1920,1080), **options_webcam).start()
        video_stream.stop()
        print("FaceCam Detected")
        return True
    except:
       os.system("sudo python3 -c 'import ErrorHandling;ErrorHandling.errorFaceCam()'")
       return False
Example #17
0
def zmq_sender(zmq_args):
    stream = VideoGear(source=RESOURCE_PATH + '/tests/walking_test_5s.mp4',
                       framerate=zmq_args['fps']).start()
    server = NetGear(address=zmq_args['ip'],
                     port=zmq_args['port'],
                     protocol=zmq_args['protocol'],
                     pattern=0,
                     receive_mode=False,
                     logging=True)

    yield (stream, server)
    # Close
    stream.stop()
Example #18
0
def test_secure_mode(pattern, security_mech, custom_cert_location, overwrite_cert):
    """
    Testing NetGear's Secure Mode
    """
    # define security mechanism
    options = {
        "secure_mode": security_mech,
        "custom_cert_location": custom_cert_location,
        "overwrite_cert": overwrite_cert,
    }
    # initialize
    frame_server = None
    stream = None
    server = None
    client = None
    try:
        # open stream
        stream = VideoGear(source=return_testvideo_path()).start()
        # define params
        server = NetGear(pattern=pattern, logging=True, **options)
        client = NetGear(pattern=pattern, receive_mode=True, logging=True, **options)
        # select random input frame from stream
        i = 0
        while i < random.randint(10, 100):
            frame_server = stream.read()
            i += 1
        # check input frame is valid
        assert not (frame_server is None)
        # send and recv input frame
        server.send(frame_server)
        frame_client = client.recv()
        # check if received frame exactly matches input frame
        assert np.array_equal(frame_server, frame_client)
    except Exception as e:
        if isinstance(e, (ZMQError, ValueError)):
            logger.exception(str(e))
        elif (
            isinstance(e, AssertionError)
            and custom_cert_location == "INVALID_DIRECTORY"
        ):
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
        if not (client is None):
            client.close()
    def use_vidgear(self):

        stream_stab = VideoGear(
            source=self.path, stabilize=True, y_tube=self.y_tube
        ).start(
        )  # To open any valid video stream with `stabilize` flag set to True.
        stream_org = VideoGear(source=self.path, y_tube=self.y_tube).start(
        )  # open same stream without stabilization for comparison

        # infinite loop
        while True:

            frame_stab = stream_stab.read()
            # read stabilized frames
            # check if frame is None
            if frame_stab is None:
                # if True break the infinite loop
                break
            # read original frame
            frame_org = stream_org.read()

            # concatenate both frames
            output_frame = np.concatenate((frame_org, frame_stab), axis=1)

            # put text
            cv2.putText(output_frame, "Before",
                        (10, output_frame.shape[0] - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
            cv2.putText(
                output_frame, "After",
                (output_frame.shape[1] // 2 + 10, output_frame.shape[0] - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

            if self.watch_only_stabilized:
                cv2.imshow("Stabilized Frame", frame_stab)
            # choose to see both original and stabilized frame
            else:
                cv2.imshow("output Frame", output_frame)
            # Show output window

            key = cv2.waitKey(1) & 0xFF
            # check for 'q' key-press
            if key == ord("q"):
                # if 'q' key-pressed break out
                break

        cv2.destroyAllWindows()
        # close output window
        stream_org.stop()
        stream_stab.stop()
Example #20
0
def test_compression(options_server):
    """
    Testing NetGear's real-time frame compression capabilities
    """
    # initialize
    stream = None
    server = None
    client = None
    try:
        # open streams
        options_gear = {"THREAD_TIMEOUT": 60}
        colorspace = (
            "COLOR_BGR2GRAY"
            if isinstance(options_server["jpeg_compression"], str)
            and options_server["jpeg_compression"].strip().upper() == "GRAY"
            else None
        )
        stream = VideoGear(
            source=return_testvideo_path(), colorspace=colorspace, **options_gear
        ).start()
        client = NetGear(pattern=0, receive_mode=True, logging=True)
        server = NetGear(pattern=0, logging=True, **options_server)
        # send over network
        while True:
            frame_server = stream.read()
            if frame_server is None:
                break
            server.send(frame_server)
            frame_client = client.recv()
            if (
                isinstance(options_server["jpeg_compression"], str)
                and options_server["jpeg_compression"].strip().upper() == "GRAY"
            ):
                assert (
                    frame_server.ndim == frame_client.ndim
                ), "Grayscale frame Test Failed!"
    except Exception as e:
        if isinstance(e, (ZMQError, ValueError, RuntimeError, queue.Empty)):
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
        if not (client is None):
            client.close()
Example #21
0
def test_compression(options_client):
    """
    Testing NetGear's real-time frame compression capabilities
    """
    options = {
        "compression_format":
        ".jpg",
        "compression_param": [
            cv2.IMWRITE_JPEG_QUALITY,
            20,
            cv2.IMWRITE_JPEG_OPTIMIZE,
            True,
        ],
    }  # JPEG compression
    # initialize
    stream = None
    server = None
    client = None
    try:
        # open streams
        options_gear = {"THREAD_TIMEOUT": 60}
        stream = VideoGear(source=return_testvideo_path(),
                           **options_gear).start()
        client = NetGear(pattern=0,
                         receive_mode=True,
                         logging=True,
                         **options_client)
        server = NetGear(pattern=0, logging=True, **options)
        # send over network
        while True:
            frame_server = stream.read()
            if frame_server is None:
                break
            server.send(frame_server)
            frame_client = client.recv()
    except Exception as e:
        if isinstance(e, (ZMQError, ValueError, RuntimeError, queue.Empty)):
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
        if not (client is None):
            client.close()
Example #22
0
async def custom_frame_generator():
    # Open video stream
    stream = VideoGear(source=return_testvideo_path()).start()
    # loop over stream until its terminated
    while True:
        # read frames
        frame = stream.read()
        # check if frame empty
        if frame is None:
            break
        # yield frame
        yield frame
        # sleep for sometime
        await asyncio.sleep(0.000001)
    # close stream
    stream.stop()
Example #23
0
def test_CamGear_import():
    """
	Testing VideoGear Import -> passed if CamGear Class is Imported sucessfully 
	and returns a valid framerate
	"""
    try:
        options = {'THREADED_QUEUE_MODE': False}
        output_stream = VideoGear(source=return_testvideo_path(),
                                  logging=True,
                                  **options).start()
        framerate = output_stream.framerate
        output_stream.stop()
        logger.debug('Input Framerate: {}'.format(framerate))
        assert framerate > 0
    except Exception as e:
        pytest.fail(str(e))
Example #24
0
def detectTabletCam():

    options_picam = {"exposure_compensation":15,"awb_mode": "horizon", "sensor_mode": 0, "CAP_PROP_FRAME_WIDTH ":1920, "CAP_PROP_FRAME_HEIGHT":1080}

    try:
        try:
            video_stream = VideoGear(source=2, resolution=(1920,1080),verbose=0, **options_picam).start()
            video_stream.stop()
        except:
            video_stream = VideoGear(source=1, resolution=(1920,1080),verbose=0, **options_picam).start()
            video_stream.stop()
        print("TabletCam Detected")
        return True
    except:
        os.system("sudo python3 -c 'import ErrorHandling;ErrorHandling.errorTabletCam()'")
        return False
Example #25
0
def run_camera(input_str, address, port, protocol, pattern=0, fps=25):
    """Runs the camera, sends messages

    Args:
        input_str (str): Path to video file **OR** an `int` for camera input
        address (str): URL of `OpenCV` server 
        port (int): Port of `OpenCV` server
        protocol (str): Protocol of of `OpenCV` server 
        pattern (int, optional): ZMQ Pattern. 0=`zmq.PAIR`, 1=`zmq.REQ/zmq.REP`; 2=`zmq.PUB,zmq.SUB`. Defaults to 0.
        fps (int, optional): Framerate for video capture. Defaults to 25.
    """
    if input_str.isdigit():
        input = int(input_str)
    else:
        input = input_str

    # Open any video stream; `framerate` here is just for picamera
    stream = VideoGear(source=input, framerate=fps).start()
    # server = NetGear() # Locally
    server = NetGear(address=address,
                     port=port,
                     protocol=protocol,
                     pattern=pattern,
                     receive_mode=False,
                     logging=True)

    # infinite loop until [Ctrl+C] is pressed
    while True:
        # Sleep
        time.sleep(0.02)

        try:
            frame = stream.read()
            # check if frame is None
            if frame is None:
                logger.error('No frame available')
                break

            # send frame to server
            server.send(frame)

        except KeyboardInterrupt:
            # break the infinite loop
            break

    # safely close video stream
    stream.stop()
Example #26
0
def test_bidirectional_mode(target_data):
	"""
	Testing NetGear's Bidirectional Mode with different datatypes
	"""
	try:
		logger.debug('Given Input Data: {}'.format(target_data))

		#open strem
		stream = VideoGear(source=return_testvideo_path()).start()
		#activate bidirectional_mode
		options = {'bidirectional_mode': True}
		#define params
		client = NetGear(receive_mode = True, logging = True, **options)
		server = NetGear(logging = True, **options)
		#get frame from stream
		frame_server = stream.read()
		assert not(frame_server is None)

		#sent frame and data from server to client
		server.send(frame_server, message = target_data)
		#client recieves the data and frame and send its data
		server_data, frame_client = client.recv(return_data = target_data)
		#server recieves the data and cycle continues
		client_data = server.send(frame_server, message = target_data)

		#clean resources
		stream.stop()
		server.close()
		client.close()

		#logger.debug data recieved at client-end and server-end
		logger.debug('Data recieved at Server-end: {}'.format(server_data))
		logger.debug('Data recieved at Client-end: {}'.format(client_data))
		
		#check if recieved frame exactly matches input frame
		assert np.array_equal(frame_server, frame_client)
		#check if client-end data exactly matches server-end data
		assert client_data == server_data
	except Exception as e:
		if isinstance(e, (ZMQError, ValueError)):
			logger.error(traceback.print_tb(e.__traceback__))
		else:
			pytest.fail(str(e))
Example #27
0
def test_patterns(pattern):
    """
    Testing NetGear different messaging patterns
    """
    # define parameters
    options = {"flag": 0, "copy": False, "track": False}
    # initialize
    frame_server = None
    stream = None
    server = None
    client = None
    try:
        # open stream
        stream = VideoGear(source=return_testvideo_path()).start()
        client = NetGear(pattern=pattern, receive_mode=True, logging=True, **options)
        server = NetGear(pattern=pattern, logging=True, **options)
        # select random input frame from stream
        i = 0
        random_cutoff = random.randint(10, 100)
        while i < random_cutoff:
            frame_server = stream.read()
            i += 1
        # check if input frame is valid
        assert not (frame_server is None)
        # send frame over network
        server.send(frame_server)
        frame_client = client.recv()
        # check if received frame exactly matches input frame
        assert np.array_equal(frame_server, frame_client)
    except Exception as e:
        if isinstance(e, (ZMQError, ValueError)):
            logger.exception(str(e))
        else:
            pytest.fail(str(e))
    finally:
        # clean resources
        if not (stream is None):
            stream.stop()
        if not (server is None):
            server.close()
        if not (client is None):
            client.close()
Example #28
0
def test_PiGear_import():
    """
    Testing VideoGear Import -> assign to fail when PiGear class is imported
    """
    # cleanup environment

    try:
        del sys.modules["picamera"]
        del sys.modules["picamera.array"]
    except KeyError:
        pass

    try:
        stream = VideoGear(enablePiCamera=True, logging=True).start()
        stream.stop()
    except Exception as e:
        if isinstance(e, ImportError):
            pytest.xfail(str(e))
        else:
            pytest.fail(str(e))
Example #29
0
def Videowriter_non_compression_mode(path):
	"""
	Function to Benchmark VidGearwriter - (Non-Compression Mode: OpenCV)
	"""
	stream = VideoGear(source=path).start() 
	writer = WriteGear(output_filename = 'Output_vnc.mp4', compression_mode = False )
	fps_CV = FPS().start()
	while True:
		frame = stream.read()
		if frame is None:
			break
		writer.write(frame)
		fps_CV.update()
	fps_CV.stop()
	stream.stop()
	writer.close()
	print("OpenCV Writer")
	print("[LOG] total elasped time: {:.2f}".format(fps_CV.total_time_elapsed()))
	print("[LOG] approx. FPS: {:.2f}".format(fps_CV.fps()))
	os.remove(os.path.abspath('Output_vnc.mp4'))
Example #30
0
def Videowriter_compression_mode(path):
	"""
	Function to Benchmark VidGearwriter - (Compression Mode: FFmpeg)
	"""
	stream = VideoGear(source=path).start()
	writer = WriteGear(output_filename = 'Output_vc.mp4', custom_ffmpeg = return_static_ffmpeg())
	fps_Vid = FPS().start()
	while True:
		frame = stream.read()
		if frame is None:
			break
		writer.write(frame)
		fps_Vid.update()
	fps_Vid.stop()
	stream.stop()
	writer.close()
	print("FFmpeg Writer")
	print("[LOG] total elasped time: {:.2f}".format(fps_Vid.total_time_elapsed()))
	print("[LOG] approx. FPS: {:.2f}".format(fps_Vid.fps()))
	os.remove(os.path.abspath('Output_vc.mp4'))