μ½˜ν…μΈ λ‘œ κ±΄λ„ˆλ›°κΈ°

μ°Έμ‘° ultralytics/data/loaders.py

μ°Έκ³ 

이 νŒŒμΌμ€ https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/data/loaders .pyμ—μ„œ 확인할 수 μžˆμŠ΅λ‹ˆλ‹€. 문제λ₯Ό λ°œκ²¬ν•˜λ©΄ ν’€ λ¦¬ν€˜μŠ€νŠΈ (πŸ› οΈ)λ₯Ό μ œμΆœν•˜μ—¬ 문제λ₯Ό ν•΄κ²°ν•˜λ„λ‘ λ„μ™€μ£Όμ„Έμš”. κ°μ‚¬ν•©λ‹ˆλ‹€ πŸ™!



ultralytics.data.loaders.SourceTypes dataclass

클래슀λ₯Ό μ‚¬μš©ν•˜μ—¬ μ˜ˆμΈ‘μ„ μœ„ν•œ λ‹€μ–‘ν•œ μœ ν˜•μ˜ μž…λ ₯ μ†ŒμŠ€λ₯Ό ν‘œν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
@dataclass
class SourceTypes:
    """Class to represent various types of input sources for predictions."""

    stream: bool = False
    screenshot: bool = False
    from_img: bool = False
    tensor: bool = False



ultralytics.data.loaders.LoadStreams

λ‹€μ–‘ν•œ μœ ν˜•μ˜ λΉ„λ””μ˜€ μŠ€νŠΈλ¦Όμ„ μœ„ν•œ 슀트림 λ‘œλ”, RTSP, RTMP, HTTP 및 TCP μŠ€νŠΈλ¦Όμ„ μ§€μ›ν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
sources str

λ™μ˜μƒ 슀트림의 μ†ŒμŠ€ μž…λ ₯ 경둜 λ˜λŠ” URLμž…λ‹ˆλ‹€.

vid_stride int

λΉ„λ””μ˜€ ν”„λ ˆμž„ 속도 보폭, 기본값은 1μž…λ‹ˆλ‹€.

buffer bool

μž…λ ₯ μŠ€νŠΈλ¦Όμ„ 버퍼링할지 μ—¬λΆ€, 기본값은 Falseμž…λ‹ˆλ‹€.

running bool

슀트리밍 μŠ€λ ˆλ“œκ°€ μ‹€ν–‰ 쀑인지 μ—¬λΆ€λ₯Ό λ‚˜νƒ€λ‚΄λŠ” ν”Œλž˜κ·Έμž…λ‹ˆλ‹€.

mode str

μ‹€μ‹œκ°„ 캑처λ₯Ό λ‚˜νƒ€λ‚΄λŠ” '슀트림'으둜 μ„€μ •ν•©λ‹ˆλ‹€.

imgs list

각 슀트림의 이미지 ν”„λ ˆμž„ λͺ©λ‘μž…λ‹ˆλ‹€.

fps list

각 슀트림의 FPS λͺ©λ‘μž…λ‹ˆλ‹€.

frames list

각 슀트림의 총 ν”„λ ˆμž„ λͺ©λ‘μž…λ‹ˆλ‹€.

threads list

각 슀트림의 μŠ€λ ˆλ“œ λͺ©λ‘μž…λ‹ˆλ‹€.

shape list

각 슀트림의 λͺ¨μ–‘ λͺ©λ‘μž…λ‹ˆλ‹€.

caps list

각 μŠ€νŠΈλ¦Όμ— λŒ€ν•œ cv2.VideoCapture 개체 λͺ©λ‘μž…λ‹ˆλ‹€.

bs int

μ²˜λ¦¬ν•  배치 ν¬κΈ°μž…λ‹ˆλ‹€.

방법:

이름 μ„€λͺ…
__init__

슀트림 λ‘œλ”λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

update

데λͺ¬ μŠ€λ ˆλ“œμ—μ„œ 슀트림 ν”„λ ˆμž„μ„ μ½μŠ΅λ‹ˆλ‹€.

close

슀트림 λ‘œλ”λ₯Ό λ‹«κ³  λ¦¬μ†ŒμŠ€λ₯Ό λ¦΄λ¦¬μŠ€ν•©λ‹ˆλ‹€.

__iter__

ν΄λž˜μŠ€μ— λŒ€ν•œ μ΄ν„°λ ˆμ΄ν„° 객체λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

__next__

μ²˜λ¦¬ν•  μ†ŒμŠ€ 경둜, λ³€ν™˜λœ 이미지 및 원본 이미지λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

__len__

μ†ŒμŠ€ 객체의 길이λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

예
yolo predict source='rtsp://example.com/media.mp4'
의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
class LoadStreams:
    """
    Stream Loader for various types of video streams, Supports RTSP, RTMP, HTTP, and TCP streams.

    Attributes:
        sources (str): The source input paths or URLs for the video streams.
        vid_stride (int): Video frame-rate stride, defaults to 1.
        buffer (bool): Whether to buffer input streams, defaults to False.
        running (bool): Flag to indicate if the streaming thread is running.
        mode (str): Set to 'stream' indicating real-time capture.
        imgs (list): List of image frames for each stream.
        fps (list): List of FPS for each stream.
        frames (list): List of total frames for each stream.
        threads (list): List of threads for each stream.
        shape (list): List of shapes for each stream.
        caps (list): List of cv2.VideoCapture objects for each stream.
        bs (int): Batch size for processing.

    Methods:
        __init__: Initialize the stream loader.
        update: Read stream frames in daemon thread.
        close: Close stream loader and release resources.
        __iter__: Returns an iterator object for the class.
        __next__: Returns source paths, transformed, and original images for processing.
        __len__: Return the length of the sources object.

    Example:
         ```bash
         yolo predict source='rtsp://example.com/media.mp4'
         ```
    """

    def __init__(self, sources="file.streams", vid_stride=1, buffer=False):
        """Initialize instance variables and check for consistent input stream shapes."""
        torch.backends.cudnn.benchmark = True  # faster for fixed-size inference
        self.buffer = buffer  # buffer input streams
        self.running = True  # running flag for Thread
        self.mode = "stream"
        self.vid_stride = vid_stride  # video frame-rate stride

        sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]
        n = len(sources)
        self.bs = n
        self.fps = [0] * n  # frames per second
        self.frames = [0] * n
        self.threads = [None] * n
        self.caps = [None] * n  # video capture objects
        self.imgs = [[] for _ in range(n)]  # images
        self.shape = [[] for _ in range(n)]  # image shapes
        self.sources = [ops.clean_str(x) for x in sources]  # clean source names for later
        for i, s in enumerate(sources):  # index, source
            # Start thread to read frames from video stream
            st = f"{i + 1}/{n}: {s}... "
            if urlparse(s).hostname in {"www.youtube.com", "youtube.com", "youtu.be"}:  # if source is YouTube video
                # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/LNwODJXcvt4'
                s = get_best_youtube_url(s)
            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam
            if s == 0 and (IS_COLAB or IS_KAGGLE):
                raise NotImplementedError(
                    "'source=0' webcam not supported in Colab and Kaggle notebooks. "
                    "Try running 'source=0' in a local environment."
                )
            self.caps[i] = cv2.VideoCapture(s)  # store video capture object
            if not self.caps[i].isOpened():
                raise ConnectionError(f"{st}Failed to open {s}")
            w = int(self.caps[i].get(cv2.CAP_PROP_FRAME_WIDTH))
            h = int(self.caps[i].get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = self.caps[i].get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan
            self.frames[i] = max(int(self.caps[i].get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float(
                "inf"
            )  # infinite stream fallback
            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback

            success, im = self.caps[i].read()  # guarantee first frame
            if not success or im is None:
                raise ConnectionError(f"{st}Failed to read images from {s}")
            self.imgs[i].append(im)
            self.shape[i] = im.shape
            self.threads[i] = Thread(target=self.update, args=([i, self.caps[i], s]), daemon=True)
            LOGGER.info(f"{st}Success βœ… ({self.frames[i]} frames of shape {w}x{h} at {self.fps[i]:.2f} FPS)")
            self.threads[i].start()
        LOGGER.info("")  # newline

    def update(self, i, cap, stream):
        """Read stream `i` frames in daemon thread."""
        n, f = 0, self.frames[i]  # frame number, frame array
        while self.running and cap.isOpened() and n < (f - 1):
            if len(self.imgs[i]) < 30:  # keep a <=30-image buffer
                n += 1
                cap.grab()  # .read() = .grab() followed by .retrieve()
                if n % self.vid_stride == 0:
                    success, im = cap.retrieve()
                    if not success:
                        im = np.zeros(self.shape[i], dtype=np.uint8)
                        LOGGER.warning("WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.")
                        cap.open(stream)  # re-open stream if signal was lost
                    if self.buffer:
                        self.imgs[i].append(im)
                    else:
                        self.imgs[i] = [im]
            else:
                time.sleep(0.01)  # wait until the buffer is empty

    def close(self):
        """Close stream loader and release resources."""
        self.running = False  # stop flag for Thread
        for thread in self.threads:
            if thread.is_alive():
                thread.join(timeout=5)  # Add timeout
        for cap in self.caps:  # Iterate through the stored VideoCapture objects
            try:
                cap.release()  # release video capture
            except Exception as e:
                LOGGER.warning(f"WARNING ⚠️ Could not release VideoCapture object: {e}")
        cv2.destroyAllWindows()

    def __iter__(self):
        """Iterates through YOLO image feed and re-opens unresponsive streams."""
        self.count = -1
        return self

    def __next__(self):
        """Returns source paths, transformed and original images for processing."""
        self.count += 1

        images = []
        for i, x in enumerate(self.imgs):
            # Wait until a frame is available in each buffer
            while not x:
                if not self.threads[i].is_alive() or cv2.waitKey(1) == ord("q"):  # q to quit
                    self.close()
                    raise StopIteration
                time.sleep(1 / min(self.fps))
                x = self.imgs[i]
                if not x:
                    LOGGER.warning(f"WARNING ⚠️ Waiting for stream {i}")

            # Get and remove the first frame from imgs buffer
            if self.buffer:
                images.append(x.pop(0))

            # Get the last frame, and clear the rest from the imgs buffer
            else:
                images.append(x.pop(-1) if x else np.zeros(self.shape[i], dtype=np.uint8))
                x.clear()

        return self.sources, images, [""] * self.bs

    def __len__(self):
        """Return the length of the sources object."""
        return self.bs  # 1E12 frames = 32 streams at 30 FPS for 30 years

__init__(sources='file.streams', vid_stride=1, buffer=False)

μΈμŠ€ν„΄μŠ€ λ³€μˆ˜λ₯Ό μ΄ˆκΈ°ν™”ν•˜κ³  μΌκ΄€λœ μž…λ ₯ 슀트림 λͺ¨μ–‘을 ν™•μΈν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __init__(self, sources="file.streams", vid_stride=1, buffer=False):
    """Initialize instance variables and check for consistent input stream shapes."""
    torch.backends.cudnn.benchmark = True  # faster for fixed-size inference
    self.buffer = buffer  # buffer input streams
    self.running = True  # running flag for Thread
    self.mode = "stream"
    self.vid_stride = vid_stride  # video frame-rate stride

    sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]
    n = len(sources)
    self.bs = n
    self.fps = [0] * n  # frames per second
    self.frames = [0] * n
    self.threads = [None] * n
    self.caps = [None] * n  # video capture objects
    self.imgs = [[] for _ in range(n)]  # images
    self.shape = [[] for _ in range(n)]  # image shapes
    self.sources = [ops.clean_str(x) for x in sources]  # clean source names for later
    for i, s in enumerate(sources):  # index, source
        # Start thread to read frames from video stream
        st = f"{i + 1}/{n}: {s}... "
        if urlparse(s).hostname in {"www.youtube.com", "youtube.com", "youtu.be"}:  # if source is YouTube video
            # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/LNwODJXcvt4'
            s = get_best_youtube_url(s)
        s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam
        if s == 0 and (IS_COLAB or IS_KAGGLE):
            raise NotImplementedError(
                "'source=0' webcam not supported in Colab and Kaggle notebooks. "
                "Try running 'source=0' in a local environment."
            )
        self.caps[i] = cv2.VideoCapture(s)  # store video capture object
        if not self.caps[i].isOpened():
            raise ConnectionError(f"{st}Failed to open {s}")
        w = int(self.caps[i].get(cv2.CAP_PROP_FRAME_WIDTH))
        h = int(self.caps[i].get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = self.caps[i].get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan
        self.frames[i] = max(int(self.caps[i].get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float(
            "inf"
        )  # infinite stream fallback
        self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback

        success, im = self.caps[i].read()  # guarantee first frame
        if not success or im is None:
            raise ConnectionError(f"{st}Failed to read images from {s}")
        self.imgs[i].append(im)
        self.shape[i] = im.shape
        self.threads[i] = Thread(target=self.update, args=([i, self.caps[i], s]), daemon=True)
        LOGGER.info(f"{st}Success βœ… ({self.frames[i]} frames of shape {w}x{h} at {self.fps[i]:.2f} FPS)")
        self.threads[i].start()
    LOGGER.info("")  # newline

__iter__()

YOLO 이미지 ν”Όλ“œλ₯Ό λ°˜λ³΅ν•˜κ³  μ‘λ‹΅ν•˜μ§€ μ•ŠλŠ” μŠ€νŠΈλ¦Όμ„ λ‹€μ‹œ μ—½λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __iter__(self):
    """Iterates through YOLO image feed and re-opens unresponsive streams."""
    self.count = -1
    return self

__len__()

μ†ŒμŠ€ 객체의 길이λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __len__(self):
    """Return the length of the sources object."""
    return self.bs  # 1E12 frames = 32 streams at 30 FPS for 30 years

__next__()

처리λ₯Ό μœ„ν•΄ μ†ŒμŠ€ 경둜, λ³€ν™˜λœ 이미지 및 원본 이미지λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __next__(self):
    """Returns source paths, transformed and original images for processing."""
    self.count += 1

    images = []
    for i, x in enumerate(self.imgs):
        # Wait until a frame is available in each buffer
        while not x:
            if not self.threads[i].is_alive() or cv2.waitKey(1) == ord("q"):  # q to quit
                self.close()
                raise StopIteration
            time.sleep(1 / min(self.fps))
            x = self.imgs[i]
            if not x:
                LOGGER.warning(f"WARNING ⚠️ Waiting for stream {i}")

        # Get and remove the first frame from imgs buffer
        if self.buffer:
            images.append(x.pop(0))

        # Get the last frame, and clear the rest from the imgs buffer
        else:
            images.append(x.pop(-1) if x else np.zeros(self.shape[i], dtype=np.uint8))
            x.clear()

    return self.sources, images, [""] * self.bs

close()

슀트림 λ‘œλ”λ₯Ό λ‹«κ³  λ¦¬μ†ŒμŠ€λ₯Ό λ¦΄λ¦¬μŠ€ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def close(self):
    """Close stream loader and release resources."""
    self.running = False  # stop flag for Thread
    for thread in self.threads:
        if thread.is_alive():
            thread.join(timeout=5)  # Add timeout
    for cap in self.caps:  # Iterate through the stored VideoCapture objects
        try:
            cap.release()  # release video capture
        except Exception as e:
            LOGGER.warning(f"WARNING ⚠️ Could not release VideoCapture object: {e}")
    cv2.destroyAllWindows()

update(i, cap, stream)

슀트림 읽기 i ν”„λ ˆμž„μ„ 데λͺ¬ μŠ€λ ˆλ“œμ— μΆ”κ°€ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def update(self, i, cap, stream):
    """Read stream `i` frames in daemon thread."""
    n, f = 0, self.frames[i]  # frame number, frame array
    while self.running and cap.isOpened() and n < (f - 1):
        if len(self.imgs[i]) < 30:  # keep a <=30-image buffer
            n += 1
            cap.grab()  # .read() = .grab() followed by .retrieve()
            if n % self.vid_stride == 0:
                success, im = cap.retrieve()
                if not success:
                    im = np.zeros(self.shape[i], dtype=np.uint8)
                    LOGGER.warning("WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.")
                    cap.open(stream)  # re-open stream if signal was lost
                if self.buffer:
                    self.imgs[i].append(im)
                else:
                    self.imgs[i] = [im]
        else:
            time.sleep(0.01)  # wait until the buffer is empty



ultralytics.data.loaders.LoadScreenshots

YOLOv8 μŠ€ν¬λ¦°μƒ· λ°μ΄ν„°λ‘œλ”.

이 ν΄λž˜μŠ€λŠ” YOLOv8 둜 μ²˜λ¦¬ν•  μŠ€ν¬λ¦°μƒ· μ΄λ―Έμ§€μ˜ λ‘œλ”©μ„ κ΄€λ¦¬ν•©λ‹ˆλ‹€. ν•¨κ»˜ μ‚¬μš©ν•˜κΈ°μ— μ ν•©ν•©λ‹ˆλ‹€. yolo predict source=screen.

속성:

이름 μœ ν˜• μ„€λͺ…
source str

μΊ‘μ²˜ν•  화면을 λ‚˜νƒ€λ‚΄λŠ” μ†ŒμŠ€ μž…λ ₯μž…λ‹ˆλ‹€.

screen int

μΊ‘μ²˜ν•  ν™”λ©΄ λ²ˆν˜Έμž…λ‹ˆλ‹€.

left int

ν™”λ©΄ 캑처 μ˜μ—­μ˜ μ™Όμͺ½ μ’Œν‘œμž…λ‹ˆλ‹€.

top int

ν™”λ©΄ 캑처 μ˜μ—­μ˜ 상단 μ’Œν‘œμž…λ‹ˆλ‹€.

width int

ν™”λ©΄ 캑처 μ˜μ—­μ˜ λ„ˆλΉ„μž…λ‹ˆλ‹€.

height int

ν™”λ©΄ 캑처 μ˜μ—­μ˜ λ†’μ΄μž…λ‹ˆλ‹€.

mode str

μ‹€μ‹œκ°„ 캑처λ₯Ό λ‚˜νƒ€λ‚΄λŠ” '슀트림'으둜 μ„€μ •ν•©λ‹ˆλ‹€.

frame int

μΊ‘μ²˜ν•œ ν”„λ ˆμž„μ˜ μΉ΄μš΄ν„°μž…λ‹ˆλ‹€.

sct mss

ν™”λ©΄ 캑처 개체 mss 라이브러리.

bs int

배치 크기λ₯Ό 1둜 μ„€μ •ν•©λ‹ˆλ‹€.

monitor dict

ꡬ성 μ„ΈλΆ€ 정보λ₯Ό λͺ¨λ‹ˆν„°λ§ν•©λ‹ˆλ‹€.

방법:

이름 μ„€λͺ…
__iter__

μ΄ν„°λ ˆμ΄ν„° 객체λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

__next__

λ‹€μŒ μŠ€ν¬λ¦°μƒ·μ„ μΊ‘μ²˜ν•˜μ—¬ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
class LoadScreenshots:
    """
    YOLOv8 screenshot dataloader.

    This class manages the loading of screenshot images for processing with YOLOv8.
    Suitable for use with `yolo predict source=screen`.

    Attributes:
        source (str): The source input indicating which screen to capture.
        screen (int): The screen number to capture.
        left (int): The left coordinate for screen capture area.
        top (int): The top coordinate for screen capture area.
        width (int): The width of the screen capture area.
        height (int): The height of the screen capture area.
        mode (str): Set to 'stream' indicating real-time capture.
        frame (int): Counter for captured frames.
        sct (mss.mss): Screen capture object from `mss` library.
        bs (int): Batch size, set to 1.
        monitor (dict): Monitor configuration details.

    Methods:
        __iter__: Returns an iterator object.
        __next__: Captures the next screenshot and returns it.
    """

    def __init__(self, source):
        """Source = [screen_number left top width height] (pixels)."""
        check_requirements("mss")
        import mss  # noqa

        source, *params = source.split()
        self.screen, left, top, width, height = 0, None, None, None, None  # default to full screen 0
        if len(params) == 1:
            self.screen = int(params[0])
        elif len(params) == 4:
            left, top, width, height = (int(x) for x in params)
        elif len(params) == 5:
            self.screen, left, top, width, height = (int(x) for x in params)
        self.mode = "stream"
        self.frame = 0
        self.sct = mss.mss()
        self.bs = 1
        self.fps = 30

        # Parse monitor shape
        monitor = self.sct.monitors[self.screen]
        self.top = monitor["top"] if top is None else (monitor["top"] + top)
        self.left = monitor["left"] if left is None else (monitor["left"] + left)
        self.width = width or monitor["width"]
        self.height = height or monitor["height"]
        self.monitor = {"left": self.left, "top": self.top, "width": self.width, "height": self.height}

    def __iter__(self):
        """Returns an iterator of the object."""
        return self

    def __next__(self):
        """mss screen capture: get raw pixels from the screen as np array."""
        im0 = np.asarray(self.sct.grab(self.monitor))[:, :, :3]  # BGRA to BGR
        s = f"screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: "

        self.frame += 1
        return [str(self.screen)], [im0], [s]  # screen, img, string

__init__(source)

좜처 = [ν™”λ©΄ 번호 μ™Όμͺ½ 상단 λ„ˆλΉ„ 높이] (ν”½μ…€).

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __init__(self, source):
    """Source = [screen_number left top width height] (pixels)."""
    check_requirements("mss")
    import mss  # noqa

    source, *params = source.split()
    self.screen, left, top, width, height = 0, None, None, None, None  # default to full screen 0
    if len(params) == 1:
        self.screen = int(params[0])
    elif len(params) == 4:
        left, top, width, height = (int(x) for x in params)
    elif len(params) == 5:
        self.screen, left, top, width, height = (int(x) for x in params)
    self.mode = "stream"
    self.frame = 0
    self.sct = mss.mss()
    self.bs = 1
    self.fps = 30

    # Parse monitor shape
    monitor = self.sct.monitors[self.screen]
    self.top = monitor["top"] if top is None else (monitor["top"] + top)
    self.left = monitor["left"] if left is None else (monitor["left"] + left)
    self.width = width or monitor["width"]
    self.height = height or monitor["height"]
    self.monitor = {"left": self.left, "top": self.top, "width": self.width, "height": self.height}

__iter__()

객체의 μ΄ν„°λ ˆμ΄ν„°λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __iter__(self):
    """Returns an iterator of the object."""
    return self

__next__()

mss ν™”λ©΄ 캑처: ν™”λ©΄μ—μ„œ μ›μ‹œ 픽셀을 np λ°°μ—΄λ‘œ κ°€μ Έμ˜΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __next__(self):
    """mss screen capture: get raw pixels from the screen as np array."""
    im0 = np.asarray(self.sct.grab(self.monitor))[:, :, :3]  # BGRA to BGR
    s = f"screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: "

    self.frame += 1
    return [str(self.screen)], [im0], [s]  # screen, img, string



ultralytics.data.loaders.LoadImagesAndVideos

YOLOv8 이미지/λΉ„λ””μ˜€ λ°μ΄ν„°λ‘œλ”.

이 ν΄λž˜μŠ€λŠ” YOLOv8 에 λŒ€ν•œ 이미지 및 λΉ„λ””μ˜€ λ°μ΄ν„°μ˜ λ‘œλ”©κ³Ό μ „μ²˜λ¦¬λ₯Ό κ΄€λ¦¬ν•©λ‹ˆλ‹€. 이 ν΄λž˜μŠ€λŠ” λ‹€μŒμ—μ„œ λ‘œλ“œλ₯Ό μ§€μ›ν•©λ‹ˆλ‹€. 단일 이미지 파일, λΉ„λ””μ˜€ 파일, 이미지 및 λΉ„λ””μ˜€ 경둜 λͺ©λ‘ λ“± λ‹€μ–‘ν•œ ν˜•μ‹μ˜ λ‘œλ”©μ„ μ§€μ›ν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
files list

이미지 및 λ™μ˜μƒ 파일 경둜 λͺ©λ‘μž…λ‹ˆλ‹€.

nf int

총 파일 수(이미지 및 λ™μ˜μƒ).

video_flag list

파일이 λ™μ˜μƒ(True) λ˜λŠ” 이미지(False)인지 μ—¬λΆ€λ₯Ό λ‚˜νƒ€λ‚΄λŠ” ν”Œλž˜κ·Έμž…λ‹ˆλ‹€.

mode str

ν˜„μž¬ λͺ¨λ“œ, '이미지' λ˜λŠ” 'λ™μ˜μƒ'.

vid_stride int

λΉ„λ””μ˜€ ν”„λ ˆμž„ μ†λ„μ˜ 보폭, 기본값은 1μž…λ‹ˆλ‹€.

bs int

이 ν΄λž˜μŠ€μ— λŒ€ν•΄ 배치 크기λ₯Ό 1둜 μ„€μ •ν•©λ‹ˆλ‹€.

cap VideoCapture

OpenCV용 λΉ„λ””μ˜€ 캑처 κ°œμ²΄μž…λ‹ˆλ‹€.

frame int

λ™μ˜μƒμš© ν”„λ ˆμž„ μΉ΄μš΄ν„°.

frames int

λ™μ˜μƒμ˜ 총 ν”„λ ˆμž„ μˆ˜μž…λ‹ˆλ‹€.

count int

λ°˜λ³΅μ„ μœ„ν•œ μΉ΄μš΄ν„°λ‘œ, 반볡 쀑 0으둜 μ΄ˆκΈ°ν™”λ©λ‹ˆλ‹€. __iter__().

방법:

이름 μ„€λͺ…
_new_video

μ§€μ •λœ λ™μ˜μƒ κ²½λ‘œμ— λŒ€ν•œ μƒˆ cv2.VideoCapture 객체λ₯Ό λ§Œλ“­λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
class LoadImagesAndVideos:
    """
    YOLOv8 image/video dataloader.

    This class manages the loading and pre-processing of image and video data for YOLOv8. It supports loading from
    various formats, including single image files, video files, and lists of image and video paths.

    Attributes:
        files (list): List of image and video file paths.
        nf (int): Total number of files (images and videos).
        video_flag (list): Flags indicating whether a file is a video (True) or an image (False).
        mode (str): Current mode, 'image' or 'video'.
        vid_stride (int): Stride for video frame-rate, defaults to 1.
        bs (int): Batch size, set to 1 for this class.
        cap (cv2.VideoCapture): Video capture object for OpenCV.
        frame (int): Frame counter for video.
        frames (int): Total number of frames in the video.
        count (int): Counter for iteration, initialized at 0 during `__iter__()`.

    Methods:
        _new_video(path): Create a new cv2.VideoCapture object for a given video path.
    """

    def __init__(self, path, batch=1, vid_stride=1):
        """Initialize the Dataloader and raise FileNotFoundError if file not found."""
        parent = None
        if isinstance(path, str) and Path(path).suffix == ".txt":  # *.txt file with img/vid/dir on each line
            parent = Path(path).parent
            path = Path(path).read_text().splitlines()  # list of sources
        files = []
        for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
            a = str(Path(p).absolute())  # do not use .resolve() https://github.com/ultralytics/ultralytics/issues/2912
            if "*" in a:
                files.extend(sorted(glob.glob(a, recursive=True)))  # glob
            elif os.path.isdir(a):
                files.extend(sorted(glob.glob(os.path.join(a, "*.*"))))  # dir
            elif os.path.isfile(a):
                files.append(a)  # files (absolute or relative to CWD)
            elif parent and (parent / p).is_file():
                files.append(str((parent / p).absolute()))  # files (relative to *.txt file parent)
            else:
                raise FileNotFoundError(f"{p} does not exist")

        # Define files as images or videos
        images, videos = [], []
        for f in files:
            suffix = f.split(".")[-1].lower()  # Get file extension without the dot and lowercase
            if suffix in IMG_FORMATS:
                images.append(f)
            elif suffix in VID_FORMATS:
                videos.append(f)
        ni, nv = len(images), len(videos)

        self.files = images + videos
        self.nf = ni + nv  # number of files
        self.ni = ni  # number of images
        self.video_flag = [False] * ni + [True] * nv
        self.mode = "image"
        self.vid_stride = vid_stride  # video frame-rate stride
        self.bs = batch
        if any(videos):
            self._new_video(videos[0])  # new video
        else:
            self.cap = None
        if self.nf == 0:
            raise FileNotFoundError(f"No images or videos found in {p}. {FORMATS_HELP_MSG}")

    def __iter__(self):
        """Returns an iterator object for VideoStream or ImageFolder."""
        self.count = 0
        return self

    def __next__(self):
        """Returns the next batch of images or video frames along with their paths and metadata."""
        paths, imgs, info = [], [], []
        while len(imgs) < self.bs:
            if self.count >= self.nf:  # end of file list
                if len(imgs) > 0:
                    return paths, imgs, info  # return last partial batch
                else:
                    raise StopIteration

            path = self.files[self.count]
            if self.video_flag[self.count]:
                self.mode = "video"
                if not self.cap or not self.cap.isOpened():
                    self._new_video(path)

                for _ in range(self.vid_stride):
                    success = self.cap.grab()
                    if not success:
                        break  # end of video or failure

                if success:
                    success, im0 = self.cap.retrieve()
                    if success:
                        self.frame += 1
                        paths.append(path)
                        imgs.append(im0)
                        info.append(f"video {self.count + 1}/{self.nf} (frame {self.frame}/{self.frames}) {path}: ")
                        if self.frame == self.frames:  # end of video
                            self.count += 1
                            self.cap.release()
                else:
                    # Move to the next file if the current video ended or failed to open
                    self.count += 1
                    if self.cap:
                        self.cap.release()
                    if self.count < self.nf:
                        self._new_video(self.files[self.count])
            else:
                self.mode = "image"
                im0 = cv2.imread(path)  # BGR
                if im0 is None:
                    raise FileNotFoundError(f"Image Not Found {path}")
                paths.append(path)
                imgs.append(im0)
                info.append(f"image {self.count + 1}/{self.nf} {path}: ")
                self.count += 1  # move to the next file
                if self.count >= self.ni:  # end of image list
                    break

        return paths, imgs, info

    def _new_video(self, path):
        """Creates a new video capture object for the given path."""
        self.frame = 0
        self.cap = cv2.VideoCapture(path)
        self.fps = int(self.cap.get(cv2.CAP_PROP_FPS))
        if not self.cap.isOpened():
            raise FileNotFoundError(f"Failed to open video {path}")
        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)

    def __len__(self):
        """Returns the number of batches in the object."""
        return math.ceil(self.nf / self.bs)  # number of files

__init__(path, batch=1, vid_stride=1)

λ°μ΄ν„°λ‘œλ”λ₯Ό μ΄ˆκΈ°ν™”ν•˜κ³  νŒŒμΌμ„ 찾을 수 μ—†λŠ” 경우 FileNotFoundErrorλ₯Ό λ°œμƒμ‹œν‚΅λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __init__(self, path, batch=1, vid_stride=1):
    """Initialize the Dataloader and raise FileNotFoundError if file not found."""
    parent = None
    if isinstance(path, str) and Path(path).suffix == ".txt":  # *.txt file with img/vid/dir on each line
        parent = Path(path).parent
        path = Path(path).read_text().splitlines()  # list of sources
    files = []
    for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
        a = str(Path(p).absolute())  # do not use .resolve() https://github.com/ultralytics/ultralytics/issues/2912
        if "*" in a:
            files.extend(sorted(glob.glob(a, recursive=True)))  # glob
        elif os.path.isdir(a):
            files.extend(sorted(glob.glob(os.path.join(a, "*.*"))))  # dir
        elif os.path.isfile(a):
            files.append(a)  # files (absolute or relative to CWD)
        elif parent and (parent / p).is_file():
            files.append(str((parent / p).absolute()))  # files (relative to *.txt file parent)
        else:
            raise FileNotFoundError(f"{p} does not exist")

    # Define files as images or videos
    images, videos = [], []
    for f in files:
        suffix = f.split(".")[-1].lower()  # Get file extension without the dot and lowercase
        if suffix in IMG_FORMATS:
            images.append(f)
        elif suffix in VID_FORMATS:
            videos.append(f)
    ni, nv = len(images), len(videos)

    self.files = images + videos
    self.nf = ni + nv  # number of files
    self.ni = ni  # number of images
    self.video_flag = [False] * ni + [True] * nv
    self.mode = "image"
    self.vid_stride = vid_stride  # video frame-rate stride
    self.bs = batch
    if any(videos):
        self._new_video(videos[0])  # new video
    else:
        self.cap = None
    if self.nf == 0:
        raise FileNotFoundError(f"No images or videos found in {p}. {FORMATS_HELP_MSG}")

__iter__()

λΉ„λ””μ˜€μŠ€νŠΈλ¦Ό λ˜λŠ” 이미지 폴더에 λŒ€ν•œ μ΄ν„°λ ˆμ΄ν„° 객체λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __iter__(self):
    """Returns an iterator object for VideoStream or ImageFolder."""
    self.count = 0
    return self

__len__()

κ°œμ²΄μ— μžˆλŠ” 배치의 수λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __len__(self):
    """Returns the number of batches in the object."""
    return math.ceil(self.nf / self.bs)  # number of files

__next__()

이미지 λ˜λŠ” λ™μ˜μƒ ν”„λ ˆμž„μ˜ λ‹€μŒ 배치λ₯Ό 경둜 및 메타데이터와 ν•¨κ»˜ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __next__(self):
    """Returns the next batch of images or video frames along with their paths and metadata."""
    paths, imgs, info = [], [], []
    while len(imgs) < self.bs:
        if self.count >= self.nf:  # end of file list
            if len(imgs) > 0:
                return paths, imgs, info  # return last partial batch
            else:
                raise StopIteration

        path = self.files[self.count]
        if self.video_flag[self.count]:
            self.mode = "video"
            if not self.cap or not self.cap.isOpened():
                self._new_video(path)

            for _ in range(self.vid_stride):
                success = self.cap.grab()
                if not success:
                    break  # end of video or failure

            if success:
                success, im0 = self.cap.retrieve()
                if success:
                    self.frame += 1
                    paths.append(path)
                    imgs.append(im0)
                    info.append(f"video {self.count + 1}/{self.nf} (frame {self.frame}/{self.frames}) {path}: ")
                    if self.frame == self.frames:  # end of video
                        self.count += 1
                        self.cap.release()
            else:
                # Move to the next file if the current video ended or failed to open
                self.count += 1
                if self.cap:
                    self.cap.release()
                if self.count < self.nf:
                    self._new_video(self.files[self.count])
        else:
            self.mode = "image"
            im0 = cv2.imread(path)  # BGR
            if im0 is None:
                raise FileNotFoundError(f"Image Not Found {path}")
            paths.append(path)
            imgs.append(im0)
            info.append(f"image {self.count + 1}/{self.nf} {path}: ")
            self.count += 1  # move to the next file
            if self.count >= self.ni:  # end of image list
                break

    return paths, imgs, info



ultralytics.data.loaders.LoadPilAndNumpy

일괄 처리λ₯Ό μœ„ν•΄ PIL 및 Numpy λ°°μ—΄μ—μ„œ 이미지λ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.

이 ν΄λž˜μŠ€λŠ” PIL 및 Numpy ν˜•μ‹μ˜ 이미지 데이터 λ‘œλ”© 및 μ „μ²˜λ¦¬λ₯Ό κ΄€λ¦¬ν•˜λ„λ‘ μ„€κ³„λ˜μ—ˆμŠ΅λ‹ˆλ‹€. 이미지가 λ‹€μš΄μŠ€νŠΈλ¦Ό μ²˜λ¦¬μ— ν•„μš”ν•œ ν˜•μ‹μΈμ§€ ν™•μΈν•˜κΈ° μœ„ν•΄ κΈ°λ³Έ μœ νš¨μ„± 검사 및 ν˜•μ‹ λ³€ν™˜μ„ μˆ˜ν–‰ν•©λ‹ˆλ‹€. ν˜•μ‹μΈμ§€ ν™•μΈν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
paths list

이미지 경둜 λ˜λŠ” μžλ™ μƒμ„±λœ 파일λͺ… λͺ©λ‘μž…λ‹ˆλ‹€.

im0 list

λ„˜ν”Ό λ°°μ—΄λ‘œ μ €μž₯된 이미지 λͺ©λ‘μž…λ‹ˆλ‹€.

mode str

처리 쀑인 데이터 μœ ν˜•, 기본값은 '이미지'μž…λ‹ˆλ‹€.

bs int

배치 크기, 길이에 ν•΄λ‹Ήν•˜λŠ” im0.

방법:

이름 μ„€λͺ…
_single_check

단일 μ΄λ―Έμ§€μ˜ μœ νš¨μ„±μ„ κ²€μ‚¬ν•˜κ³  Numpy λ°°μ—΄λ‘œ ν¬λ§·ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
class LoadPilAndNumpy:
    """
    Load images from PIL and Numpy arrays for batch processing.

    This class is designed to manage loading and pre-processing of image data from both PIL and Numpy formats.
    It performs basic validation and format conversion to ensure that the images are in the required format for
    downstream processing.

    Attributes:
        paths (list): List of image paths or autogenerated filenames.
        im0 (list): List of images stored as Numpy arrays.
        mode (str): Type of data being processed, defaults to 'image'.
        bs (int): Batch size, equivalent to the length of `im0`.

    Methods:
        _single_check(im): Validate and format a single image to a Numpy array.
    """

    def __init__(self, im0):
        """Initialize PIL and Numpy Dataloader."""
        if not isinstance(im0, list):
            im0 = [im0]
        self.paths = [getattr(im, "filename", f"image{i}.jpg") for i, im in enumerate(im0)]
        self.im0 = [self._single_check(im) for im in im0]
        self.mode = "image"
        self.bs = len(self.im0)

    @staticmethod
    def _single_check(im):
        """Validate and format an image to numpy array."""
        assert isinstance(im, (Image.Image, np.ndarray)), f"Expected PIL/np.ndarray image type, but got {type(im)}"
        if isinstance(im, Image.Image):
            if im.mode != "RGB":
                im = im.convert("RGB")
            im = np.asarray(im)[:, :, ::-1]
            im = np.ascontiguousarray(im)  # contiguous
        return im

    def __len__(self):
        """Returns the length of the 'im0' attribute."""
        return len(self.im0)

    def __next__(self):
        """Returns batch paths, images, processed images, None, ''."""
        if self.count == 1:  # loop only once as it's batch inference
            raise StopIteration
        self.count += 1
        return self.paths, self.im0, [""] * self.bs

    def __iter__(self):
        """Enables iteration for class LoadPilAndNumpy."""
        self.count = 0
        return self

__init__(im0)

PIL 및 λ„˜ν”Ό λ°μ΄ν„°λ‘œλ”λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __init__(self, im0):
    """Initialize PIL and Numpy Dataloader."""
    if not isinstance(im0, list):
        im0 = [im0]
    self.paths = [getattr(im, "filename", f"image{i}.jpg") for i, im in enumerate(im0)]
    self.im0 = [self._single_check(im) for im in im0]
    self.mode = "image"
    self.bs = len(self.im0)

__iter__()

LoadPilAndNumpy ν΄λž˜μŠ€μ— 반볡처리λ₯Ό ν™œμ„±ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __iter__(self):
    """Enables iteration for class LoadPilAndNumpy."""
    self.count = 0
    return self

__len__()

'im0' μ†μ„±μ˜ 길이λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __len__(self):
    """Returns the length of the 'im0' attribute."""
    return len(self.im0)

__next__()

배치 경둜, 이미지, 처리된 이미지, μ—†μŒ, ''λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __next__(self):
    """Returns batch paths, images, processed images, None, ''."""
    if self.count == 1:  # loop only once as it's batch inference
        raise StopIteration
    self.count += 1
    return self.paths, self.im0, [""] * self.bs



ultralytics.data.loaders.LoadTensor

torch μ—μ„œ 이미지λ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.Tensor 데이터.

이 ν΄λž˜μŠ€λŠ” μΆ”κ°€ 처리λ₯Ό μœ„ν•΄ PyTorch ν…μ„œμ—μ„œ 이미지 λ°μ΄ν„°μ˜ λ‘œλ”© 및 μ „μ²˜λ¦¬λ₯Ό κ΄€λ¦¬ν•©λ‹ˆλ‹€.

속성:

이름 μœ ν˜• μ„€λͺ…
im0 Tensor

이미지가 ν¬ν•¨λœ tensor μž…λ ₯μž…λ‹ˆλ‹€.

bs int

배치 크기, λ‹€μŒ λͺ¨μ–‘μ—μ„œ 좔둠됨. im0.

mode str

ν˜„μž¬ λͺ¨λ“œλ₯Ό '이미지'둜 μ„€μ •ν•©λ‹ˆλ‹€.

paths list

이미지 경둜 λ˜λŠ” 파일 이름 λͺ©λ‘μž…λ‹ˆλ‹€.

count int

λ°˜λ³΅μ„ μœ„ν•œ μΉ΄μš΄ν„°λ‘œ, 반볡 쀑 0으둜 μ΄ˆκΈ°ν™”λ©λ‹ˆλ‹€. __iter__().

방법:

이름 μ„€λͺ…
_single_check

μž…λ ₯을 ν™•μΈν•˜κ³  μˆ˜μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€ tensor.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
class LoadTensor:
    """
    Load images from torch.Tensor data.

    This class manages the loading and pre-processing of image data from PyTorch tensors for further processing.

    Attributes:
        im0 (torch.Tensor): The input tensor containing the image(s).
        bs (int): Batch size, inferred from the shape of `im0`.
        mode (str): Current mode, set to 'image'.
        paths (list): List of image paths or filenames.
        count (int): Counter for iteration, initialized at 0 during `__iter__()`.

    Methods:
        _single_check(im, stride): Validate and possibly modify the input tensor.
    """

    def __init__(self, im0) -> None:
        """Initialize Tensor Dataloader."""
        self.im0 = self._single_check(im0)
        self.bs = self.im0.shape[0]
        self.mode = "image"
        self.paths = [getattr(im, "filename", f"image{i}.jpg") for i, im in enumerate(im0)]

    @staticmethod
    def _single_check(im, stride=32):
        """Validate and format an image to torch.Tensor."""
        s = (
            f"WARNING ⚠️ torch.Tensor inputs should be BCHW i.e. shape(1, 3, 640, 640) "
            f"divisible by stride {stride}. Input shape{tuple(im.shape)} is incompatible."
        )
        if len(im.shape) != 4:
            if len(im.shape) != 3:
                raise ValueError(s)
            LOGGER.warning(s)
            im = im.unsqueeze(0)
        if im.shape[2] % stride or im.shape[3] % stride:
            raise ValueError(s)
        if im.max() > 1.0 + torch.finfo(im.dtype).eps:  # torch.float32 eps is 1.2e-07
            LOGGER.warning(
                f"WARNING ⚠️ torch.Tensor inputs should be normalized 0.0-1.0 but max value is {im.max()}. "
                f"Dividing input by 255."
            )
            im = im.float() / 255.0

        return im

    def __iter__(self):
        """Returns an iterator object."""
        self.count = 0
        return self

    def __next__(self):
        """Return next item in the iterator."""
        if self.count == 1:
            raise StopIteration
        self.count += 1
        return self.paths, self.im0, [""] * self.bs

    def __len__(self):
        """Returns the batch size."""
        return self.bs

__init__(im0)

Tensor λ°μ΄ν„°λ‘œλ”λ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __init__(self, im0) -> None:
    """Initialize Tensor Dataloader."""
    self.im0 = self._single_check(im0)
    self.bs = self.im0.shape[0]
    self.mode = "image"
    self.paths = [getattr(im, "filename", f"image{i}.jpg") for i, im in enumerate(im0)]

__iter__()

μ΄ν„°λ ˆμ΄ν„° 객체λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __iter__(self):
    """Returns an iterator object."""
    self.count = 0
    return self

__len__()

배치 크기λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __len__(self):
    """Returns the batch size."""
    return self.bs

__next__()

반볡기의 λ‹€μŒ ν•­λͺ©μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def __next__(self):
    """Return next item in the iterator."""
    if self.count == 1:
        raise StopIteration
    self.count += 1
    return self.paths, self.im0, [""] * self.bs



ultralytics.data.loaders.autocast_list(source)

λ‹€μ–‘ν•œ μœ ν˜•μ˜ μ†ŒμŠ€ λͺ©λ‘μ„ 널빀지 λ°°μ—΄ λ˜λŠ” PIL 이미지 λͺ©λ‘μœΌλ‘œ λ³‘ν•©ν•©λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def autocast_list(source):
    """Merges a list of source of different types into a list of numpy arrays or PIL images."""
    files = []
    for im in source:
        if isinstance(im, (str, Path)):  # filename or uri
            files.append(Image.open(requests.get(im, stream=True).raw if str(im).startswith("http") else im))
        elif isinstance(im, (Image.Image, np.ndarray)):  # PIL or np Image
            files.append(im)
        else:
            raise TypeError(
                f"type {type(im).__name__} is not a supported Ultralytics prediction source type. \n"
                f"See https://docs.ultralytics.com/modes/predict for supported source types."
            )

    return files



ultralytics.data.loaders.get_best_youtube_url(url, use_pafy=True)

μ§€μ •λœ YouTube λ™μ˜μƒμ—μ„œ 졜고 ν™”μ§ˆμ˜ MP4 λ™μ˜μƒ 슀트림의 URL을 κ²€μƒ‰ν•©λ‹ˆλ‹€.

이 ν•¨μˆ˜λŠ” pafy λ˜λŠ” yt_dlp 라이브러리λ₯Ό μ‚¬μš©ν•˜μ—¬ YouTubeμ—μ„œ λ™μ˜μƒ 정보λ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€. 그런 λ‹€μŒ λΉ„λ””μ˜€ 코덱은 μžˆμ§€λ§Œ μ˜€λ””μ˜€ 코덱이 μ—†λŠ” λΉ„λ””μ˜€ 코덱은 μžˆμ§€λ§Œ μ˜€λ””μ˜€ 코덱이 μ—†λŠ” 졜고 ν’ˆμ§ˆμ˜ MP4 ν˜•μ‹μ„ μ°Ύμ•„ 이 λΉ„λ””μ˜€ 슀트림의 URL을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

λ§€κ°œλ³€μˆ˜:

이름 μœ ν˜• μ„€λͺ… κΈ°λ³Έκ°’
url str

YouTube λ™μ˜μƒμ˜ URLμž…λ‹ˆλ‹€.

ν•„μˆ˜
use_pafy bool

기본값이 True인 pafy νŒ¨ν‚€μ§€λ₯Ό μ‚¬μš©ν•˜κ³ , 그렇지 μ•ŠμœΌλ©΄ yt_dlp νŒ¨ν‚€μ§€λ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€.

True

λ°˜ν™˜ν•©λ‹ˆλ‹€:

μœ ν˜• μ„€λͺ…
str

졜고 ν’ˆμ§ˆμ˜ MP4 λ™μ˜μƒ 슀트림의 URL λ˜λŠ” μ ν•©ν•œ μŠ€νŠΈλ¦Όμ„ 찾을 수 μ—†λŠ” 경우 μ—†μŒμž…λ‹ˆλ‹€.

의 μ†ŒμŠ€ μ½”λ“œ ultralytics/data/loaders.py
def get_best_youtube_url(url, use_pafy=True):
    """
    Retrieves the URL of the best quality MP4 video stream from a given YouTube video.

    This function uses the pafy or yt_dlp library to extract the video info from YouTube. It then finds the highest
    quality MP4 format that has video codec but no audio codec, and returns the URL of this video stream.

    Args:
        url (str): The URL of the YouTube video.
        use_pafy (bool): Use the pafy package, default=True, otherwise use yt_dlp package.

    Returns:
        (str): The URL of the best quality MP4 video stream, or None if no suitable stream is found.
    """
    if use_pafy:
        check_requirements(("pafy", "youtube_dl==2020.12.2"))
        import pafy  # noqa

        return pafy.new(url).getbestvideo(preftype="mp4").url
    else:
        check_requirements("yt-dlp")
        import yt_dlp

        with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
            info_dict = ydl.extract_info(url, download=False)  # extract info
        for f in reversed(info_dict.get("formats", [])):  # reversed because best is usually last
            # Find a format with video codec, no audio, *.mp4 extension at least 1920x1080 size
            good_size = (f.get("width") or 0) >= 1920 or (f.get("height") or 0) >= 1080
            if good_size and f["vcodec"] != "none" and f["acodec"] == "none" and f["ext"] == "mp4":
                return f.get("url")





생성 2023-11-12, μ—…λ°μ΄νŠΈ 2024-05-08
μž‘μ„±μž: Burhan-Q (1), κΈ€λ Œ-쑰처 (4), μ›ƒλŠ”-큐 (1)