Transformers documentation

LightGlue

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

이 모델은 2023-06-23에 HF papers에 게시되었으며, 2025-06-17에 Hugging Face Transformers에 기여되었습니다.

PyTorch

LightGlue

LightGlue는 이미지 간 로컬 특징을 매칭하도록 학습하는 딥 뉴럴 네트워크입니다. SuperGlue의 여러 설계 결정을 재검토하고 단순하지만 효과적인 개선 사항을 도출했습니다. 이러한 개선 사항들이 축적되어 LightGlue는 메모리와 계산 측면에서 더 효율적이고, 더 정확하며, 학습이 훨씬 쉬워졌습니다. SuperGlue와 마찬가지로, 이 모델은 두 이미지에서 추출된 두 집합의 로컬 특징을 매칭하는 구조로 되어 있으며, SuperGlue보다 더 빠르게 동작하는 것을 목표로 합니다. SuperPoint model과 함께 사용하면 두 이미지를 매칭하고 그 사이의 자세를 추정하는 데 활용할 수 있습니다.

모든 LightGlue 원본 체크포인트는 ETH-CVG 조직에서 찾을 수 있습니다.

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

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

아래 예제는 Pipeline 또는 AutoModel 클래스를 사용하여 두 이미지 간의 keypoint를 매칭하는 방법을 보여줍니다.

Pipeline
AutoModel
from transformers import pipeline


keypoint_matcher = pipeline(task="keypoint-matching", model="ETH-CVG/lightglue_superpoint")

url_0 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_98169888_3347710852.jpg"
url_1 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_26757027_6717084061.jpg"

results = keypoint_matcher([url_0, url_1], threshold=0.9)
print(results[0])
# {'keypoint_image_0': {'x': ..., 'y': ...}, 'keypoint_image_1': {'x': ..., 'y': ...}, 'score': ...}

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

  • LightGlue는 작업의 난이도에 적응합니다. 시각적 겹침이 넓거나 외형 변화가 제한적인 경우와 같이 직관적으로 매칭이 쉬운 이미지 쌍에서는 추론 속도가 훨씬 빠릅니다.

    from transformers import AutoImageProcessor, AutoModel
    import torch
    from PIL import Image
    import requests
    
    processor = AutoImageProcessor.from_pretrained("ETH-CVG/lightglue_superpoint")
    model = AutoModel.from_pretrained("ETH-CVG/lightglue_superpoint", device_map="auto")
    
    # LightGlue requires pairs of images
    images = [image1, image2]
    inputs = processor(images, return_tensors="pt").to(model.device)
    with torch.inference_mode():
        outputs = model(**inputs)
    
    # Extract matching information
    keypoints0 = outputs.keypoints0  # Keypoints in first image
    keypoints1 = outputs.keypoints1  # Keypoints in second image
    matches = outputs.matches        # Matching indices
    matching_scores = outputs.matching_scores  # Confidence scores
  • 모델은 각 매칭에 대해 매칭 인덱스, 키포인트, 신뢰도 점수를 출력하며, SuperGlue와 유사하지만 효율성이 개선되었습니다.

  • 더 나은 시각화와 분석을 위해 LightGlueImageProcessor.post_process_keypoint_matching() 메서드를 사용하여 더 가독성 높은 형식으로 매칭 결과를 가져오세요.

    # Process outputs for visualization
    image_sizes = [[(image.height, image.width) for image in images]]
    processed_outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
    
    for i, output in enumerate(processed_outputs):
        print(f"For the image pair {i}")
        for keypoint0, keypoint1, matching_score in zip(
                output["keypoints0"], output["keypoints1"], output["matching_scores"]
        ):
            print(f"Keypoint at {keypoint0.numpy()} matches with keypoint at {keypoint1.numpy()} with score {matching_score}")
  • 내장된 플롯팅 기능을 사용하여 이미지 간의 매칭을 시각화합니다.

    # Easy visualization using the built-in plotting method
    processor.visualize_keypoint_matching(images, processed_outputs)

리소스

LightGlueConfig

class transformers.LightGlueConfig

< >

( 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 = Nonekeypoint_detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedescriptor_dim: int = 256num_hidden_layers: int = 9num_attention_heads: int = 4num_key_value_heads: int | None = Nonedepth_confidence: float = 0.95width_confidence: float = 0.99filter_threshold: float = 0.1initializer_range: float = 0.02hidden_act: str = 'gelu'attention_dropout: float | int = 0.0attention_bias: bool = True )

매개변수

  • keypoint_detector_config (Union[AutoConfig, dict], 선택 사항, 기본값 SuperPointConfig) — 키포인트 검출기의 config 객체 또는 사전입니다.
  • descriptor_dim (int, 선택 사항, 기본값 256) — descriptors의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 9) — Transformer decoder의 숨겨진 레이어 수입니다.
  • num_attention_heads (int, 선택 사항, 기본값 4) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • num_key_value_heads (int, 선택 사항) — Grouped Query Attention 구현에 사용할 key_value 헤드 수입니다. num_key_value_heads=num_attention_heads인 경우 모델은 Multi Head Attention(MHA)을 사용하고, num_key_value_heads=1인 경우 모델은 Multi Query Attention(MQA)을 사용하며, 그 외에는 GQA가 사용됩니다. 멀티 헤드 체크포인트를 GQA 체크포인트로 변환할 때, 각 그룹의 key 및 value 헤드는 해당 그룹 내 모든 원래 헤드를 meanpooling하여 구성해야 합니다. 자세한 내용은 이 논문을 확인하세요. 지정되지 않으면 num_attention_heads가 기본값으로 사용됩니다.
  • depth_confidence (float, 선택 사항, 기본값 0.95) — 조기 정지를 수행하는 데 사용되는 신뢰도 임계값
  • width_confidence (float, 선택 사항, 기본값 0.99) — 점을 제거하는 데 사용되는 신뢰도 임계값
  • filter_threshold (float, 선택 사항, 기본값 0.1) — 일치 항목을 필터링하는 데 사용되는 신뢰도 임계값
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • hidden_act (str, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • attention_bias (bool, 선택 사항, 기본값 True) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다.

이것은 LightGlueForKeypointMatching의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Lightglue 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 ETH-CVG/lightglue_superpoint와 유사한 설정이 생성됩니다.

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

예:

>>> from transformers import LightGlueConfig, LightGlueForKeypointMatching

>>> # Initializing a LightGlue style configuration
>>> configuration = LightGlueConfig()

>>> # Initializing a model from the LightGlue style configuration
>>> model = LightGlueForKeypointMatching(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

LightGlueImageProcessor

클래스 transformers.LightGlueImageProcessor

< >

( **kwargs: *<class 'transformers.models.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs'> )

매개변수

  • 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로 재정의할 수 있습니다.

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

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs'> ) → ~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로 설정하세요.
  • 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, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • do_grayscale (bool, kwargs, 선택 사항, 기본값 self.do_grayscale) — 이미지를 회색조로 변환할지 여부입니다. preprocess 메서드의 do_grayscale로 재정의할 수 있습니다.

반환값

~image_processing_base.BatchFeature

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

post_process_keypoint_matching

< >

( outputs: LightGlueKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → list[Dict]

매개변수

  • outputs (LightGlueKeypointMatchingOutput) — 모델의 원시 출력입니다.
  • target_sizes (torch.Tensor 또는 list[tuple[tuple[int, int]]], 선택 사항) — 배치 내 각 이미지의 대상 크기 (height, width)를 포함하는 (batch_size, 2, 2) 형태의 Tensor 또는 튜플의 튜플(tuple[int, int]) 목록입니다. 이는 원본 이미지 크기(처리 전)여야 합니다.
  • threshold (float, 선택 사항, 기본값 0.0) — 낮은 점수를 가진 매치를 필터링하기 위한 임계값입니다.

반환값

list[Dict]

…의 목록으로, 각 사전에는 해당 쌍의 첫 번째 이미지와 두 번째 이미지의 …, …, …가 포함되어 있습니다.

LightGlueKeypointMatchingOutput의 원시 출력을 원래 이미지 크기에 대한 절대 좌표를 가진 keypoint, score, descriptor의 리스트로 변환합니다.

visualize_keypoint_matching

< >

( imageskeypoint_matching_output: list ) → List[PIL.Image.Image]

매개변수

  • images — 그릴 이미지 쌍입니다. EfficientLoFTRImageProcessor.preprocess와 동일합니다. 픽셀 값이 0에서 255 범위로 이루어진 2개의 이미지 목록 또는 2개의 이미지 목록의 목록을 기대합니다.
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 후처리된 keypoint matching 출력

반환값

List[PIL.Image.Image]

각 이미지에 감지된 keypoint와 그들 간의 매칭이 나란히 표시된 이미지 쌍을 포함하는 PIL 이미지 목록

감지된 키포인트와 그들 간의 매칭을 포함하여 이미지 쌍을 나란히 플롯합니다.

LightGlueImageProcessorPil

클래스 transformers.LightGlueImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.lightglue.image_processing_pil_lightglue.LightGlueImageProcessorKwargs'> )

매개변수

  • 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로 재정의할 수 있습니다.

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

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.lightglue.image_processing_pil_lightglue.LightGlueImageProcessorKwargs'> ) → ~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로 설정하세요.
  • 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, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • do_grayscale (bool, kwargs, 선택 사항, 기본값 self.do_grayscale) — 이미지를 회색조로 변환할지 여부입니다. preprocess 메서드의 do_grayscale로 재정의할 수 있습니다.

반환값

~image_processing_base.BatchFeature

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

post_process_keypoint_matching

< >

( outputs: LightGlueKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → list[Dict]

매개변수

  • outputs (LightGlueKeypointMatchingOutput) — 모델의 원시 출력입니다.
  • target_sizes (torch.Tensor 또는 list[tuple[tuple[int, int]]], 선택 사항) — 배치 내 각 이미지의 대상 크기 (height, width)를 포함하는 (batch_size, 2, 2) 형태의 Tensor 또는 튜플의 튜플(tuple[int, int]) 목록입니다. 이는 원본 이미지 크기(처리 전)여야 합니다.
  • threshold (float, 선택 사항, 기본값 0.0) — 낮은 점수를 가진 매치를 필터링하기 위한 임계값입니다.

반환값

list[Dict]

…의 목록으로, 각 사전에는 해당 쌍의 첫 번째 이미지와 두 번째 이미지의 …, …, …가 포함되어 있습니다.

LightGlueKeypointMatchingOutput의 원시 출력을 원래 이미지 크기에 대한 절대 좌표를 가진 keypoint, score, descriptor의 리스트로 변환합니다.

visualize_keypoint_matching

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]keypoint_matching_output: list ) → List[PIL.Image.Image]

매개변수

  • images (ImageInput) — 플롯할 이미지 쌍입니다. LightGlueImageProcessor.preprocess와 동일합니다. 픽셀 값이 0에서 255 범위로 이루어진 2개의 이미지 목록 또는 2개의 이미지 목록의 목록을 기대합니다.
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 후처리된 keypoint matching 출력

반환값

List[PIL.Image.Image]

각 이미지에 감지된 keypoint와 그들 간의 매칭이 나란히 표시된 이미지 쌍을 포함하는 PIL 이미지 목록

감지된 키포인트와 그들 간의 매칭을 포함하여 이미지 쌍을 나란히 플롯합니다.

LightGlueForKeypointMatching

클래스 transformers.LightGlueForKeypointMatching

< >

( config: LightGlueConfig )

매개변수

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

이미지를 입력으로 받아 매칭 결과를 출력하는 LightGlue 모델

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

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

forward

< >

( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = None**kwargs ) → LightGlueKeypointMatchingOutput or tuple(torch.Tensor)

매개변수

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

반환값

LightGlueKeypointMatchingOutput 또는 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor, shape (1,), 선택 사항) — 학습 중에 계산된 손실.
  • matches (torch.Tensor, shape (batch_size, 2, num_matches)) — 다른 이미지에서 매칭된 키포인트의 인덱스.
  • matching_scores (torch.Tensor, shape (batch_size, 2, num_matches)) — 예측된 매치의 점수.
  • keypoints (torch.Tensor, shape (batch_size, num_keypoints, 2)) — 주어진 이미지에서 예측된 keypoints의 절대 (x, y) 좌표.
  • prune (torch.IntTensor, shape (batch_size, num_keypoints)) — 어떤 keypoint가 어떤 layer에서 제거되는지를 나타내는 Pruning mask.
  • mask (torch.BoolTensor, shape (batch_size, num_keypoints)) — matches, matching_scores, keypoints, prune 값 중 어떤 값이 keypoint matching 정보인지를 나타내는 마스크.
  • hidden_states (Tuple[torch.Tensor, ...], 선택 사항) — output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환되는, 각 단계의 출력을 위한 torch.Tensor 튜플(각각 (batch_size, 2, num_channels, num_keypoints) 형태)
  • attentions (Tuple[torch.Tensor, ...], 선택 사항) — output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환되는, 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, 2, num_heads, num_keypoints, num_keypoints)입니다.
Update on GitHub