def test_write(conversion):
	"""
	Testing VidGear Non-Compression(OpenCV) Mode Writer
	"""
	stream = cv2.VideoCapture(return_testvideo_path())
	writer = WriteGear(output_filename = 'Output_twc.avi', compression_mode = False) #Define writer
	while True:
		(grabbed, frame) = stream.read()
		# read frames
		# check if frame empty
		if not grabbed:
			#if True break the infinite loop
			break
		if conversion:
			frame = cv2.cvtColor(frame, capPropId(conversion))
		writer.write(frame)
	stream.release()
	writer.close()
	basepath, _ = os.path.split(return_static_ffmpeg())
	ffprobe_path  = os.path.join(basepath,'ffprobe.exe' if os.name == 'nt' else 'ffprobe')
	result = check_output([ffprobe_path, "-v", "error", "-count_frames", "-i", os.path.abspath('Output_twc.avi')])
	if result:
		if not isinstance(result, string_types):
			result = result.decode()
		print('Result: {}'.format(result))
		for i in ["Error", "Invalid", "error", "invalid"]:
			assert not(i in result)
	os.remove(os.path.abspath('Output_twc.avi'))
def test_write(conversion):
    """
	Testing Compression Mode(FFmpeg) Writer capabilties in different colorspace
	"""
    stream = cv2.VideoCapture(return_testvideo_path(
    ))  #Open live webcam video stream on first index(i.e. 0) device
    writer = WriteGear(output_filename='Output_tw.mp4',
                       custom_ffmpeg=return_static_ffmpeg())  #Define writer
    while True:
        (grabbed, frame) = stream.read()
        if not grabbed:
            break
        if conversion:
            frame = cv2.cvtColor(frame, capPropId(conversion))
        if conversion in ['COLOR_BGR2RGB', 'COLOR_BGR2RGBA']:
            writer.write(frame, rgb_mode=True)
        else:
            writer.write(frame)
    stream.release()
    writer.close()
    basepath, _ = os.path.split(return_static_ffmpeg())
    ffprobe_path = os.path.join(
        basepath, 'ffprobe.exe' if os.name == 'nt' else 'ffprobe')
    result = check_output([
        ffprobe_path, "-v", "error", "-count_frames", "-i",
        os.path.abspath('Output_tw.mp4')
    ])
    if result:
        if not isinstance(result, string_types):
            result = result.decode()
        print('Result: {}'.format(result))
        for i in ["Error", "Invalid", "error", "invalid"]:
            assert not (i in result)
    os.remove(os.path.abspath('Output_tw.mp4'))
Example #3
0
    def __init__( # pylint: disable = too-many-arguments, too-many-locals, too-many-branches, too-many-statements
            self,
            source=0,
            y_tube=False,
            backend=0,
            colorspace=None,
            logging=False,
            time_delay=0,
            transform=None,
            downsample=None,
            buffer_size=96,
            **options
    ):
        if downsample is None:
            downsample = 1
        self.downsample = downsample

        self.buffer_size = buffer_size

        # enable logging if specified
        self.__logging = False
        self.transform = transform
        if logging:
            self.__logging = logging

        # check if Youtube Mode is ON (True)
        if y_tube:
            try:
                # import pafy and parse youtube stream url
                import pafy #pylint: disable = import-outside-toplevel

                # validate
                video_url = youtube_url_validator(source)
                if video_url:
                    source_object = pafy.new(video_url)
                    vo_source = source_object.getbestvideo("webm", ftypestrict=True)
                    va_source = source_object.getbest("webm", ftypestrict=False)
                    # select the best quality
                    if vo_source is None or (
                            va_source.dimensions >= vo_source.dimensions
                    ):
                        source = va_source.url
                    else:
                        source = vo_source.url
                    if self.__logging:
                        LOGGER.debug(
                            "YouTube source ID: %s, Title: %s", video_url, source_object.title
                        )
                else:
                    raise RuntimeError(
                        "Invalid `{}` Youtube URL cannot be processed!".format(source)
                    )
            except Exception as exc:
                if self.__logging:
                    LOGGER.exception(str(exc))
                raise ValueError(
                    "[CamGear:ERROR] :: YouTube Mode is enabled and the input YouTube URL is "
                    "incorrect!"
                )

        # youtube mode variable initialization
        self.__youtube_mode = y_tube

        # assigns special parameter to global variable and clear
        self.__threaded_queue_mode = options.pop("THREADED_QUEUE_MODE", True)
        if not isinstance(self.__threaded_queue_mode, bool):
            # reset improper values
            self.__threaded_queue_mode = True

        self.__queue = None
        # initialize deque for video files only
        if self.__threaded_queue_mode and isinstance(source, str):
            # import deque
            from collections import deque #pylint: disable = import-outside-toplevel

            # define deque and assign it to global var
            # max len self.buffer_size to check overflow
            self.__queue = deque(maxlen=self.buffer_size)
            # log it
            if self.__logging:
                LOGGER.debug(
                    "Enabling Threaded Queue Mode for the current video source!"
                )
        else:
            # otherwise disable it
            self.__threaded_queue_mode = False
            # log it
            if self.__logging:
                LOGGER.warning(
                    "Threaded Queue Mode is disabled for the current video source!"
                )

        # stream variable initialization
        self.stream = None

        if backend and isinstance(backend, int):
            # add backend if specified and initialize the camera stream
            if check_CV_version() == 3:
                # Different OpenCV 3.4.x statement
                self.stream = cv2.VideoCapture(source + backend)
            else:
                # Two parameters are available since OpenCV 4+ (master branch)
                self.stream = cv2.VideoCapture(source, backend)
            LOGGER.debug("Setting backend %s for this source.", backend)
        else:
            # initialize the camera stream
            self.stream = cv2.VideoCapture(source)

        # initializing colorspace variable
        self.color_space = None

        # apply attributes to source if specified
        options = {str(k).strip(): v for k, v in options.items()}
        for key, value in options.items():
            propty = capPropId(key)
            if not (propty is None):
                self.stream.set(propty, value)

        # handle colorspace value
        if not (colorspace is None):
            self.color_space = capPropId(colorspace.strip())
            if self.__logging and not (self.color_space is None):
                LOGGER.debug(
                    "Enabling %s colorspace for this video stream!",
                    colorspace.strip()
                )

        # initialize and assign frame-rate variable
        self.framerate = 0.0
        _fps = self.stream.get(cv2.CAP_PROP_FPS)
        if _fps > 1.0:
            self.framerate = _fps

        # applying time delay to warm-up webcam only if specified
        if time_delay:
            time.sleep(time_delay)

        # frame variable initialization
        (grabbed, self.frame) = self.stream.read()

        # check if valid stream
        if grabbed:
            # render colorspace if defined
            if not (self.color_space is None):
                self.frame = cv2.cvtColor(self.frame, self.color_space)

            if self.__threaded_queue_mode:

                if self.transform:
                    try:
                        self.frame = self.transform(self.frame)
                    except AttributeError:
                        LOGGER.error(
                            "[slave thread] Failed to transform the input video frame. "
                            "Setting stop state of reader.",
                            exc_info=True)
                        self.__terminate = True
                        return

                # initialize and append to queue
                self.__queue.append(self.frame)
        else:
            raise RuntimeError(
                "[CamGear:ERROR] :: Source is invalid, CamGear failed to intitialize stream on "
                "this source!"
            )

        # thread initialization
        self.__thread = None

        # initialize termination flag
        self.__terminate = False