Transformers documentation

画像プロセッサ用のユーティリティ

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

and get access to the augmented documentation experience

to get started

画像プロセッサ用のユーティリティ

このページでは、画像プロセッサで使用されるすべてのユーティリティ関数をリストしています。主に、画像の処理に使用される関数型の変換です。

これらの多くは、ライブラリの画像プロセッサのコードを研究する場合にのみ有用です。

画像変換

transformers.image_transforms.center_crop

< >

( image: ndarraysize: tupledata_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

パラメータ

  • image (np.ndarray) — クロップする画像。
  • size (tuple[int, int]) — クロップされた画像のターゲットサイズです。
  • data_format (str または ChannelDimension, 省略可) — 出力画像のチャネル次元の形式です。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。 未設定の場合、入力画像の推定形式が使用されます。
  • input_data_format (str または ChannelDimension, 省略可) — 入力画像のチャネル次元の形式です。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。 未設定の場合、入力画像の推定形式が使用されます。

戻り値

np.ndarray

切り抜かれた画像。

imageを中央クロップにより指定されたsizeに切り出します。画像が指定されたサイズにクロップできないほど小さい場合は、パディングが適用されます(そのため、返される結果は常にsizeのサイズになります)。

transformers.image_transforms.center_to_corners_format

< >

( bboxes_center: TensorType )

バウンディングボックスを中心形式から角形式に変換します。

center形式: ボックスの中心座標と幅、高さの寸法を含みます (center_x, center_y, width, height) corners形式: ボックスの左上隅と右下隅の座標を含みます (top_left_x, top_left_y, bottom_right_x, bottom_right_y)

transformers.image_transforms.corners_to_center_format

< >

( bboxes_corners: TensorType )

バウンディングボックスをコーナー形式からセンター形式に変換します。

corners 形式: ボックスの左上隅と右下隅の座標を含みます (top_left_x, top_left_y, bottom_right_x, bottom_right_y) center 形式: ボックスの中心の座標と、幅および高さの寸法を含みます (center_x, center_y, width, height)

transformers.image_transforms.id_to_rgb

< >

( id_map )

一意のIDをRGBカラーに変換します。

transformers.image_transforms.normalize

< >

( image: ndarraymean: float | collections.abc.Collection[float]std: float | collections.abc.Collection[float]data_format: transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None )

パラメータ

  • image (np.ndarray) — 正規化対象の画像。
  • mean (float または Collection[float]) — 正規化に使用する平均値。
  • std (float または Collection[float]) — 正規化に使用する標準偏差。
  • data_format (ChannelDimension、省略可) — 出力画像のチャネル次元の形式です。未設定の場合、入力から推定された形式が使用されます。
  • input_data_format (ChannelDimension、省略可) — 入力画像のチャネル次元の形式です。未設定の場合、入力から推定された形式が使用されます。

imageを、meanとstdで指定された平均と標準偏差を用いて正規化します。

image = (image - mean) / std

transformers.image_transforms.pad

< >

( image: ndarraypadding: int | tuple[int, int] | collections.abc.Iterable[tuple[int, int]]mode: PaddingMode = <PaddingMode.CONSTANT: 'constant'>constant_values: float | collections.abc.Iterable[float] = 0.0data_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

パラメータ

  • image (np.ndarray) — パディングする画像。
  • padding (int または tuple[int, int] または Iterable[tuple[int, int]]) — 高さ・幅軸の端に適用するパディング。以下の3つの形式のいずれかを使用できます:
    • ((before_height, after_height), (before_width, after_width)) 各軸ごとの固有のパッド幅。
    • ((before, after),) は、高さおよび幅に対して同じ before と after のパディングを生成します。
    • (pad,) または int は、すべての軸に対して before = after = pad の幅を指定するショートカットです。
  • mode (PaddingMode) — 使用するパディングモード。以下のいずれかです:
    • "constant": 一定の値でパディングします。
    • "reflect": 各軸に沿って、ベクトルの先頭と末尾の値を基準として、ベクトルの反射でパディングします。
    • "replicate": 各軸に沿って、配列の端の最後の値を複製してパディングします。
    • "symmetric": 配列の端を軸としてベクトルを鏡像反転させた値でパディングします。
  • constant_values (float または Iterable[float]、任意) — mode が "constant" の場合に、パディングに使用する値です。
  • data_format (str または ChannelDimension, 省略可) — 出力画像のチャネル次元の形式です。以下のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。 未設定の場合、入力画像と同じ形式が使用されます。
  • input_data_format (str または ChannelDimension, 省略可) — 入力画像のチャネル次元の形式です。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。 未設定の場合、入力画像の推定形式が使用されます。

戻り値

np.ndarray

パディングされた画像。

imageを指定された (height, width) の padding および mode でパディングします。

transformers.image_transforms.rgb_to_id

< >

( color )

RGBカラーを一意なIDに変換します。

transformers.image_transforms.rescale

< >

( image: ndarrayscale: floatdata_format: transformers.image_utils.ChannelDimension | None = Nonedtype: dtype = <class 'numpy.float32'>input_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

パラメータ

  • image (np.ndarray) — リスケールする画像です。
  • scale (float) — 画像をリスケールする際に使用するスケール。
  • data_format (ChannelDimension、省略可) — 画像のチャネル次元の形式です。指定しない場合、入力画像と同じになります。
  • dtype (np.dtype、省略可、デフォルトは np.float32) — 出力画像の dtype です。デフォルトは np.float32 です。feature extractor との後方互換性のために使用されます。
  • input_data_format (ChannelDimension、省略可) — 入力画像のチャネル次元の形式です。指定しない場合、入力画像から推論されます。

戻り値

np.ndarray

リサイズされた画像。

imageをscaleで再スケーリングします。

transformers.image_transforms.resize

< >

( image: ndarraysize: tupleresample: typing.Optional[ForwardRef('PILImageResampling')] = Nonereducing_gap: int | None = Nonedata_format: transformers.image_utils.ChannelDimension | None = Nonereturn_numpy: bool = Trueinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

パラメータ

  • image (np.ndarray) — リサイズする画像。
  • size (tuple[int, int]) — 画像のリサイズに使用するサイズです。
  • resample (int、任意、デフォルトは PILImageResampling.BILINEAR) — リサンプリングに使用するフィルタ。
  • reducing_gap (int, 省略可) — 2段階で画像をリサイズすることにより最適化を適用します。reducing_gap の値が大きいほど、結果はフェアなリサンプリングに近づきます。詳細については、対応する Pillow のドキュメントを参照してください。
  • data_format (ChannelDimension、省略可) — 出力画像のチャネル次元の形式です。未設定の場合、入力から推定された形式が使用されます。
  • return_numpy (bool、省略可能、デフォルトは True) — リサイズされた画像を numpy 配列として返すかどうか。False の場合、PIL.Image.Image オブジェクトが返されます。
  • input_data_format (ChannelDimension、省略可) — 入力画像のチャネル次元の形式です。未設定の場合、入力から推定された形式が使用されます。

戻り値

np.ndarray

リサイズされた画像。

PILライブラリを使用して、sizeで指定された(height, width)にimageをリサイズします。

transformers.image_transforms.to_pil_image

< >

( image: typing.Union[numpy.ndarray, ForwardRef('PIL.Image.Image'), ForwardRef('torch.Tensor')]do_rescale: bool | None = Noneimage_mode: str | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → PIL.Image.Image

パラメータ

  • image (PIL.Image.Image または numpy.ndarray または torch.Tensor) — PIL.Image 形式に変換する画像です。
  • do_rescale (bool, 省略可) — スケーリング係数を適用するかどうか(ピクセル値を 0 から 255 の整数にするため)。画像の型が浮動小数点型であり、int へのキャストで精度が失われる場合は True がデフォルトとなり、それ以外の場合は False となります。
  • image_mode (str, 任意) — PIL イメージに使用するモードです。設定されていない場合、入力イメージのタイプに対するデフォルトモードが使用されます。
  • input_data_format (ChannelDimension、省略可) — 入力画像のチャネル次元の形式です。未設定の場合、入力から推定された形式が使用されます。

戻り値

PIL.Image.Image

変換された画像。

imageをPIL Imageに変換します。必要に応じて、リスケールし、チャネル次元を最後の軸に戻します。

ImageProcessingMixin

class transformers.ImageProcessingMixin

< >

( **kwargs )

これは、シーケンシャルおよび画像のフィーチャーエクストラクターに対して保存/読み込み機能を提供するために使用される画像プロセッサのミックスインです。

fetch_images

< >

( image_url_or_urls: str | list[str] | list[list[str]] )

単一のURLまたはURLのリストを、対応するPIL.Imageオブジェクトに変換します。

単一のurlが渡された場合、戻り値は単一のオブジェクトになります。リストが渡された場合、オブジェクトのリストが返されます。

from_dict

< >

( image_processor_dict: dict**kwargs ) → ImageProcessingMixin

パラメータ

  • image_processor_dict (dict[str, Any]) — 画像プロセッサオブジェクトをインスタンス化するために使用される辞書です。この辞書は、to_dict() メソッドを活用して事前学習済みチェックポイントから取得できます。
  • kwargs (dict[str, Any]) — 画像プロセッサオブジェクトの初期化に使用する追加のパラメータです。

これらのパラメータからインスタンス化された画像プロセッサオブジェクト。

パラメータの Python 辞書から ImageProcessingMixin の型をインスタンス化します。

from_json_file

< >

( json_file: str | os.PathLike ) → A image processor of type ImageProcessingMixin

パラメータ

  • json_file (str または os.PathLike) — パラメータを含む JSON ファイルへのパス。

戻り値

型がImageProcessingMixinの画像プロセッサ

そのJSONファイルからインスタンス化されたimage_processorオブジェクト

パラメータのJSONファイルへのパスから、ImageProcessingMixin 型の画像プロセッサをインスタンス化します。

from_pretrained

< >

( pretrained_model_name_or_path: str | os.PathLikecache_dir: str | os.PathLike | None = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: str | bool | None = Nonerevision: str = 'main'**kwargs )

パラメータ

  • pretrained_model_name_or_path (str または os.PathLike) — 以下いずれかです:
    • 文字列、huggingface.co上のモデルリポジトリにホストされている事前学習済みimage_processorのmodel id。
    • a path to a directory containing a image processor file saved using the save_pretrained() method, e.g., ./my_model_directory/.
    • 保存された画像プロセッサの JSON ファイルへのパス。例: ./my_model_directory/preprocessor_config.json
  • cache_dir (str または os.PathLike、省略可) — 標準のキャッシュを使用しない場合、ダウンロードした事前学習済みモデルの画像プロセッサをキャッシュするディレクトリのパス。
  • force_download (bool、省略可、デフォルトは False) — イメージプロセッサのファイルを(再)ダウンロードを強制し、キャッシュされたバージョンが存在する場合にそれを上書きするかどうか。
  • proxies (dict[str, str]、省略可) — プロトコルまたはエンドポイントごとに使用するプロキシサーバーの辞書です。例: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. 各リクエストでこれらのプロキシが使用されます。
  • token (str または bool、省略可) — リモートファイルの HTTP ベアラ認証に使用するトークンです。True の場合、または指定されていない場合は、hf auth login を実行した際に生成されたトークン(~/.huggingface に保存)が使用されます。
  • revision (str、任意、デフォルトは "main") — 使用する特定のモデルのバージョンです。huggingface.co 上でモデルやその他の成果物を保存するために git ベースのシステムを使用しているため、ブランチ名、タグ名、コミット ID のいずれかを指定できます。したがって、revision には git で許可される任意の識別子を指定できます。

画像プロセッサからImageProcessingMixinの型をインスタンス化します。

例:

# We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a
# derived class: *CLIPImageProcessor*
image_processor = CLIPImageProcessor.from_pretrained(
    "openai/clip-vit-base-patch32"
)  # Download image_processing_config from huggingface.co and cache.
image_processor = CLIPImageProcessor.from_pretrained(
    "./test/saved_model/"
)  # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')*
image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json")
image_processor = CLIPImageProcessor.from_pretrained(
    "openai/clip-vit-base-patch32", do_normalize=False, foo=False
)
assert image_processor.do_normalize is False
image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained(
    "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True
)
assert image_processor.do_normalize is False
assert unused_kwargs == {"foo": False}

get_image_processor_dict

< >

( pretrained_model_name_or_path: str | os.PathLike**kwargs ) → tuple[Dict, Dict]

パラメータ

  • pretrained_model_name_or_path (str または os.PathLike) — パラメータの辞書を取得したい事前学習済みチェックポイントの識別子です。
  • subfolder (str、任意、デフォルトは "") — huggingface.co 上のモデルリポジトリのサブフォルダ内に該当するファイルが配置されている場合、ここにフォルダ名を指定できます。
  • image_processor_filename (str、任意、デフォルトは "config.json") — モデルディレクトリ内で、画像プロセッサの設定として使用するファイルの名前です。

戻り値

tuple[Dict, Dict]

画像プロセッサオブジェクトをインスタンス化するために使用される辞書です。

pretrained_model_name_or_path から、~image_processor_utils.ImageProcessingMixin 型の画像プロセッサを from_dict を用いてインスタンス化するために使用する、パラメータの辞典に解決します。

push_to_hub

< >

( repo_id: strcommit_message: str | None = Nonecommit_description: str | None = Noneprivate: bool | None = Nonetoken: bool | str | None = Nonerevision: str | None = Nonecreate_pr: bool = Falsemax_shard_size: int | str | None = '50GB'tags: list[str] | None = None )

パラメータ

  • repo_id (str) — イメージプロセッサをプッシュするリポジトリの名前です。特定の組織にプッシュする場合は、組織名を含む必要があります。
  • commit_message (str, 任意) — プッシュ時にコミットするメッセージ。デフォルトは "Upload image processor" です。
  • commit_description (str, 省略可) — 作成されるコミットの説明
  • private (bool、省略可) — リポジトリを非公開にするかどうか。None(デフォルト)の場合、組織のデフォルトが非公開でない限り、リポジトリは公開になります。リポジトリが既に存在する場合、この値は無視されます。
  • token (bool または str、省略可) — リモートファイルの HTTP ベアラ認証に使用するトークン。True(デフォルト)の場合、hf auth login を実行した際に生成されたトークン(~/.huggingface に保存)が使用されます。
  • revision (str、省略可) — アップロードしたファイルをプッシュするブランチ。
  • create_pr (bool、省略可、デフォルトはFalse) — アップロードしたファイルを含む PR を作成するか、直接コミットするかどうかを指定します。
  • max_shard_size (int または str、省略可能、デフォルトは "50GB") — モデルにのみ適用されます。シャード化される前のチェックポイントの最大サイズです。シャード化されたチェックポイントは、それぞれがこのサイズ未満になります。文字列で指定する場合は、数字の後に単位("5MB" など)を続ける必要があります。
  • tags (list[str]、省略可) — Hub にプッシュするタグのリストです。

画像プロセッサのファイルを🤗 Model Hubにアップロードします。

例:

from transformers import AutoImageProcessor

image processor = AutoImageProcessor.from_pretrained("google-bert/bert-base-cased")

# Push the image processor to your namespace with the name "my-finetuned-bert".
image processor.push_to_hub("my-finetuned-bert")

# Push the image processor to an organization with the name "my-finetuned-bert".
image processor.push_to_hub("huggingface/my-finetuned-bert")

register_for_auto_class

< >

( auto_class = 'AutoImageProcessor' )

パラメータ

  • auto_class (str または type、省略可能、デフォルトは "AutoImageProcessor ") — この新しい image processor を登録する auto class。

このクラスを指定された auto クラスに登録します。ライブラリ内のものはすでにAutoImageProcessorにマッピングされているため、このメソッドはカスタム画像プロセッサでのみ使用すべきです。

save_pretrained

< >

( save_directory: str | os.PathLikepush_to_hub: bool = False**kwargs )

パラメータ

  • save_directory (str または os.PathLike) — 画像プロセッサの JSON ファイルを保存するディレクトリ(存在しない場合は作成されます)。
  • push_to_hub (bool、省略可、デフォルトは False) — モデルを保存した後、Hugging Face モデルハブにプッシュするかどうかを指定します。プッシュ先のリポジトリは repo_id で指定できます(指定しない場合、save_directory の名前があなたのネームスペース内でデフォルトとして使用されます)。
  • kwargs (dict[str, Any]、省略可) — push_to_hub() メソッドに渡される追加のキーワード引数。

画像プロセッサオブジェクトをディレクトリ save_directory に保存し、from_pretrained() クラスメソッドを使って再読み込みできるようにします。

to_dict

< >

( ) → dict[str, Any]

戻り値

dict[str, Any]

この image processor インスタンスを構成するすべての属性の辞書。

このインスタンスをPythonの辞書にシリアライズします。

to_json_file

< >

( json_file_path: str | os.PathLike )

パラメータ

  • json_file_path (str または os.PathLike) — この image_processor インスタンスのパラメータを保存する JSON ファイルへのパス。

このインスタンスをJSONファイルに保存します。

to_json_string

< >

( ) → str

戻り値

str

この feature_extractor インスタンスを構成するすべての属性を JSON 形式で含む文字列。

このインスタンスをJSON文字列にシリアライズします。

Update on GitHub