Transformers documentation

SuperPoint

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2017-12-20에 HF papers에 게시되었으며, 2024-03-19에 Hugging Face Transformers에 기여되었습니다.

PyTorch

SuperPoint

SuperPoint는 관심점 검출 및 기술자를 위한 완전 합성곱 신경망을 자기 지도 학습으로 훈련한 결과물입니다. 이 모델은 호모그래피 변환 하에서도 반복적으로 검출 가능한 관심점을 찾아내고, 각 점에 대한 기술자를 제공합니다. 단독 사용 시 활용 범위는 제한적이지만, 호모그래피 추정 및 이미지 매칭과 같은 다른 작업의 특징 추출기로 사용할 수 있습니다.

drawing

모든 SuperPoint 원본 체크포인트는 Magic Leap Community 조직에서 찾을 수 있습니다.

이 모델은 stevenbucaille에 의해 기여되었습니다.

SuperPoint를 다양한 컴퓨터 비전 작업에 적용하는 방법에 대한 추가 예제는 오른쪽 사이드바의 SuperPoint 모델에서 확인하세요.

아래 예제는 AutoModel 클래스를 사용하여 이미지에서 관심 지점을 감지하는 방법을 보여줍니다.

AutoModel
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, SuperPointForKeypointDetection


url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)

processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint", device_map="auto")

inputs = processor(image, return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

# Post-process to get keypoints, scores, and descriptors
image_size = (image.height, image.width)
processed_outputs = processor.post_process_keypoint_detection(outputs, [image_size])

The input is a single word "Notes". 참고

  • SuperPoint는 이미지마다 가변 수의 keypoint를 출력하므로, 가변 길이의 feature 표현이 필요한 작업에 적합합니다.

    from transformers import AutoImageProcessor, SuperPointForKeypointDetection
    import torch
    from PIL import Image
    import requests
    processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
    model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint", device_map="auto")
    url_image_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
    image_1 = Image.open(requests.get(url_image_1, stream=True).raw)
    url_image_2 = "http://images.cocodataset.org/test-stuff2017/000000000568.jpg"
    image_2 = Image.open(requests.get(url_image_2, stream=True).raw)
    images = [image_1, image_2]
    inputs = processor(images, return_tensors="pt").to(model.device)
    # Example of handling dynamic keypoint output
    outputs = model(**inputs)
    keypoints = outputs.keypoints  # Shape varies per image
    scores = outputs.scores        # Confidence scores for each keypoint
    descriptors = outputs.descriptors  # 256-dimensional descriptors
    mask = outputs.mask # Value of 1 corresponds to a keypoint detection
  • 모델은 단일 forward pass에서 keypoint 좌표와 해당 설명자(256차원 벡터)를 모두 제공합니다.

  • 여러 이미지에 대한 배치 처리를 수행하려면 post_process_keypoint_detection를 사용하여 각 이미지에 해당하는 정보를 가져와야 합니다. SuperPointImageProcessor의 post_process_keypoint_detection를 사용하면 각 이미지의 정보를 가져올 수 있습니다.

    # Batch processing example
    images = [image1, image2, image3]
    inputs = processor(images, return_tensors="pt").to(model.device)
    outputs = model(**inputs)
    image_sizes = [(img.height, img.width) for img in images]
    processed_outputs = processor.post_process_keypoint_detection(outputs, image_sizes)
  • 이후 원하는 이미지에 keypoint를 출력하여 결과를 시각화할 수 있습니다:

    import matplotlib.pyplot as plt
    plt.axis("off")
    plt.imshow(image_1)
    plt.scatter(
        outputs[0]["keypoints"][:, 0],
        outputs[0]["keypoints"][:, 1],
        c=outputs[0]["scores"] * 100,
        s=outputs[0]["scores"] * 50,
        alpha=0.8
    )
    plt.savefig(f"output_image.png")

리소스

  • 추론 및 시각화 예제는 이 노트북을 참고하세요.

SuperPointConfig

class transformers.SuperPointConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneencoder_hidden_sizes: list[int] | tuple[int, ...] = (64, 64, 128, 128)decoder_hidden_size: int = 256keypoint_decoder_dim: int = 65descriptor_decoder_dim: int = 256keypoint_threshold: float = 0.005max_keypoints: int = -1nms_radius: int = 4border_removal_distance: int = 4initializer_range: float = 0.02 )

매개변수

  • encoder_hidden_sizes (List, 선택 사항, 기본값 [64, 64, 128, 128]) — 인코더의 각 컨볼루션 레이어의 채널 수입니다.
  • decoder_hidden_size (int, 선택 사항, 기본값 256) — 숨겨진 표현의 차원입니다.
  • keypoint_decoder_dim (int, 선택 사항, 기본값 65) — keypoint decoder의 출력 차원입니다.
  • descriptor_decoder_dim (int, 선택 사항, 기본값 256) — 디스크립터 디코더의 출력 차원입니다.
  • keypoint_threshold (float, 선택 사항, 기본값 0.005) — 키포인트 추출에 사용할 임계값입니다.
  • max_keypoints (int, 선택 사항, 기본값 -1) — 추출할 최대 keypoint 수입니다. -1인 경우 모든 keypoint를 추출합니다.
  • nms_radius (int, 선택 사항, 기본값 4) — non-maximum suppression에 사용할 반경입니다.
  • border_removal_distance (int, 선택 사항, 기본값 4) — 제거할 keypoint까지의 경계 거리입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

이것은 SuperpointModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Superpoint 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 magic-leap-community/superpoint와 유사한 구성이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import SuperPointConfig, SuperPointForKeypointDetection

>>> # Initializing a SuperPoint superpoint style configuration
>>> configuration = SuperPointConfig()
>>> # Initializing a model from the superpoint style configuration
>>> model = SuperPointForKeypointDetection(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config

SuperPointImageProcessor

class transformers.SuperPointImageProcessor

< >

( **kwargs: *<class 'transformers.models.superpoint.image_processing_superpoint.SuperPointImageProcessorKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'height' -- 480, 'width': 640}): 모델에 전달되는 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 False) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값 2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다. PILImageResampling enum 중 하나를 사용할 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택, 기본값 True) — 이미지를 다시 스케일링할지 여부.
  • rescale_factor (float, kwargs, 선택 사항, 기본값 0.00392156862745098) — do_rescale이 True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다.
  • do_normalize (bool, kwargs, 선택 사항, 기본값 None) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • do_grayscale (bool, kwargs, 선택 사항, 기본값 self.do_grayscale) — 이미지를 회색조로 변환할지 여부입니다. preprocess 메서드의 do_grayscale로 재정의할 수 있습니다.

SuperPointImageProcessor 이미지 프로세서를 생성합니다.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • image_like_kwargs (dict[str, Any], 선택) — 추가 이미지 유사 입력을 전처리할 때 사용하는 개발자용 플래그입니다. 입력을 kwarg로 전달하는 것이 작동하지 않는 경우에만 사용하세요. 예를 들어, preprocess(images, masks=masks)가 권장되는 옵션이지만 일부 모델에서는 인자 우선순위 문제가 발생할 수 있습니다. 이러한 경우 대신 preprocess(images, image_like_inputs={"masks": masks})를 사용할 수 있습니다.
  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 모델의 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택 사항) — 이미지를 다시 스케일링할지 여부입니다.
  • rescale_factor (float, kwargs, optional) — do_rescale이 True로 설정된 경우 이미지를 리스케일하기 위한 리스케일 팩터입니다.
  • do_normalize (bool, kwargs, optional) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

반환값

~image_processing_base.BatchFeature

  • data (dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.

이미지 또는 이미지 배치(batch)를 전처리합니다.

SuperPointImageProcessorPil

class transformers.SuperPointImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.superpoint.image_processing_pil_superpoint.SuperPointImageProcessorKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'height' -- 480, 'width': 640}): 모델에 전달되는 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 False) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값 2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다. PILImageResampling enum 중 하나를 사용할 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택, 기본값 True) — 이미지를 다시 스케일링할지 여부.
  • rescale_factor (float, kwargs, 선택 사항, 기본값 0.00392156862745098) — do_rescale이 True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다.
  • do_normalize (bool, kwargs, 선택 사항, 기본값 None) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • do_grayscale (bool, kwargs, 선택 사항, 기본값 self.do_grayscale) — 이미지를 회색조로 변환할지 여부입니다. preprocess 메서드의 do_grayscale로 재정의할 수 있습니다.

SuperPointImageProcessor 이미지 프로세서를 생성합니다.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • image_like_kwargs (dict[str, Any], 선택) — 추가 이미지 유사 입력을 전처리할 때 사용하는 개발자용 플래그입니다. 입력을 kwarg로 전달하는 것이 작동하지 않는 경우에만 사용하세요. 예를 들어, preprocess(images, masks=masks)가 권장되는 옵션이지만 일부 모델에서는 인자 우선순위 문제가 발생할 수 있습니다. 이러한 경우 대신 preprocess(images, image_like_inputs={"masks": masks})를 사용할 수 있습니다.
  • do_convert_rgb (bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다.
  • do_resize (bool, kwargs, 선택) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 모델의 최대 입력 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택 사항) — 이미지를 다시 스케일링할지 여부입니다.
  • rescale_factor (float, kwargs, optional) — do_rescale이 True로 설정된 경우 이미지를 리스케일하기 위한 리스케일 팩터입니다.
  • do_normalize (bool, kwargs, optional) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

반환값

~image_processing_base.BatchFeature

  • data (dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.

이미지 또는 이미지 배치(batch)를 전처리합니다.

post_process_keypoint_detection

< >

( outputs: SuperPointKeypointDescriptionOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple] ) → list[Dict]

매개변수

  • outputs (SuperPointKeypointDescriptionOutput) — 상대 (x, y) 형식의 keypoint와 score, descriptor를 포함하는 모델의 원시 출력
  • target_sizes (torch.Tensor 또는 list[tuple[int, int]]) — 배치 내 각 이미지의 대상 크기 (height, width)를 포함하는 (batch_size, 2) 모양의 Tensor 또는 튜플(tuple[int, int]) 목록입니다. 이는 처리 전의 원본 이미지 크기여야 합니다.

반환값

list[Dict]

target_sizes에 따라 절대 좌표 형식의 keypoint, 점수, 기술자를 각각 포함하는 사전의 목록입니다. 각 사전은 모델이 배치 내의 이미지별로 예측한 값을 나타냅니다.

SuperPointForKeypointDetection의 원시 출력을 원본 이미지 크기에 대한 절대 좌표를 가진 keypoint, score, descriptor 목록으로 변환합니다.

SuperPointForKeypointDetection

class transformers.SuperPointForKeypointDetection

< >

( config: SuperPointConfig )

매개변수

  • config (SuperPointConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

SuperPoint 모델이 keypoint와 descriptor를 출력하는 모습.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SuperPointKeypointDescriptionOutput or tuple(torch.FloatTensor)

매개변수

  • pixel_values (torch.FloatTensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 SuperPointImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 SuperPointImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 SuperPointImageProcessor를 사용합니다).
  • labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.vocab_size] 범위 내의 값이거나 -100이어야 합니다(input_ids docstring 참조). 인덱스가 -100으로 설정된 토큰은 무시(마스크)되며, 손실은 [0, ..., config.vocab_size] 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

SuperPointKeypointDescriptionOutput 또는 tuple(torch.FloatTensor)

SuperPointKeypointDescriptionOutput 또는 torch.FloatTensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(SuperPointConfig)과 입력에 따라 다양한 요소를 포함합니다.

SuperPointForKeypointDetection의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.FloatTensor, shape (1,), 선택 사항) — 학습 중에 계산된 손실.
  • keypoints (torch.FloatTensor, shape (batch_size, num_keypoints, 2)) — 주어진 이미지에서 예측된 keypoints의 상대 (x, y) 좌표.
  • scores (torch.FloatTensor, shape (batch_size, num_keypoints)) — 예측된 keypoint의 점수.
  • descriptors (torch.FloatTensor, shape (batch_size, num_keypoints, descriptor_size)) — 예측된 keypoint의 Descriptors.
  • mask (torch.BoolTensor, shape (batch_size, num_keypoints)) — keypoints, scores, descriptors 값 중 어떤 값이 keypoint 정보인지 나타내는 마스크.
  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력용 1개 + 각 단계의 출력용 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다. 각 단계의 출력에서 모델의 히든 스테이트(피처 맵이라고도 함).

예:

>>> from transformers import AutoImageProcessor, SuperPointForKeypointDetection
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
>>> model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")

>>> inputs = processor(image, return_tensors="pt")
>>> outputs = model(**inputs)
Update on GitHub