class DinoFcImageProcessor(BaseImageProcessorFast):
model_input_names = ["pixel_values"]
valid_kwargs = DefaultFastImageProcessorKwargs
# Define default configuration as class attributes
do_resize: bool = True
resample: Resampling = Resampling.BICUBIC
do_rescale: bool = True
rescale_factor: float = 1/255
do_normalize: bool = True
image_mean: list[float] = [0.485, 0.456, 0.406]
image_std: list[float] = [0.229, 0.224, 0.225]
do_convert_rgb: bool = True
# DinoFc specific kwargs
do_pad: bool = True
patch_size: int = 14
base_resolution: tuple[int, int] = (336, 224)
def __init__(self, **kwargs):
super().__init__(**kwargs)
@auto_docstring
def preprocess(
self, images: ImageInput, **kwargs) -> BatchFeature:
return super().preprocess(images, **kwargs)
def get_new_size(self, image_size: SizeDict) -> tuple[int, int]:
"""Calculates the new size to preserve the number of patches."""
width, height = image_size["width"], image_size["height"]
target_num_patches = (self.base_resolution[0] * self.base_resolution[1]) / (self.patch_size ** 2)
aspect_ratio = height / width
new_num_patches_w = math.sqrt(target_num_patches / aspect_ratio)
new_num_patches_h = target_num_patches / new_num_patches_w
new_w = int(round(new_num_patches_w)) * self.patch_size
new_h = int(round(new_num_patches_h)) * self.patch_size
return new_h, new_w
def _pad_batch(self, images: list[torch.Tensor]) -> torch.Tensor:
"""Pads a list of images to the maximum dimensions in the batch."""
if not images:
return torch.empty(0)
max_h = max(img.shape[1] for img in images)
max_w = max(img.shape[2] for img in images)
batch_shape = (len(images), images[0].shape[0], max_h, max_w)
padded_batch = torch.zeros(batch_shape, dtype=images[0].dtype, device=images[0].device)
for i, img in enumerate(images):
padded_batch[i, :, :img.shape[1], :img.shape[2]] = img
return padded_batch
def _preprocess(
self,
images: list[torch.Tensor],
do_resize: bool,
interpolation: "F.InterpolationMode",
do_rescale: bool,
rescale_factor: float,
do_normalize: bool,
image_mean: list[float],
image_std: list[float],
return_tensors: str | TensorType | None,
**kwargs,
) -> BatchFeature:
"""
The core preprocessing function. This is called by `preprocess` after
input validation and preparation.
"""
if do_resize:
# Resize each image individually
processed_images = []
for image_tensor in images:
_, h, w = image_tensor.shape
new_h, new_w = self.get_new_size(SizeDict(height=h, width=w))
resized_image = self.resize(
image=image_tensor,
size=SizeDict(height=new_h, width=new_w),
interpolation=interpolation,
)
processed_images.append(resized_image)
else:
processed_images = images
# Pad all images in the batch to the same size, and stack them into a single tensor
if self.do_pad:
pixel_values = self._pad_batch(processed_images)
else:
pixel_values = torch.stack(processed_images)
# Now apply rescale and normalize to the entire batch at once
if do_rescale:
pixel_values = self.rescale(image=pixel_values, scale=rescale_factor)
if do_normalize:
pixel_values = self.normalize(image=pixel_values, mean=image_mean, std=image_std)
return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors)
以上代码在调用 inputs = processor(images=image, return_tensors="pt")时报错
File "/ssd/hexucheng/miniconda3/envs/sar/lib/python3.10/site-packages/transformers/image_utils.py", line 554, in validate_preprocess_arguments
raise ValueError("size and resample must be specified if do_resize is True.")
ValueError: size and resample must be specified if do_resize is True
以下是库中相关代码:
def _validate_preprocess_kwargs(
self,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, tuple[float]]] = None,
image_std: Optional[Union[float, tuple[float]]] = None,
do_resize: Optional[bool] = None,
size: Optional[SizeDict] = None,
do_center_crop: Optional[bool] = None,
crop_size: Optional[SizeDict] = None,
resample: Optional[Union["PILImageResampling", "F.InterpolationMode"]] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
data_format: Optional[ChannelDimension] = None,
**kwargs,
):
"""
validate the kwargs for the preprocess method.
"""
validate_fast_preprocess_arguments(
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
do_resize=do_resize,
size=size,
do_center_crop=do_center_crop,
crop_size=crop_size,
resample=resample,
return_tensors=return_tensors,
data_format=data_format,
)
def __call__(self, images: ImageInput, *args, **kwargs: Unpack[DefaultFastImageProcessorKwargs]) -> BatchFeature:
return self.preprocess(images, *args, **kwargs)
@auto_docstring
def preprocess(self, images: ImageInput, *args, **kwargs: Unpack[DefaultFastImageProcessorKwargs]) -> BatchFeature:
# args are not validated, but their order in the `preprocess` and `_preprocess` signatures must be the same
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_kwargs_names)
# Set default kwargs from self. This ensures that if a kwarg is not provided
# by the user, it gets its default value from the instance, or is set to None.
for kwarg_name in self._valid_kwargs_names:
kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))
# Extract parameters that are only used for preparing the input images
do_convert_rgb = kwargs.pop("do_convert_rgb")
input_data_format = kwargs.pop("input_data_format")
device = kwargs.pop("device")
# Prepare input images
images = self._prepare_input_images(
images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
)
# Update kwargs that need further processing before being validated
kwargs = self._further_process_kwargs(**kwargs)
# Validate kwargs
self._validate_preprocess_kwargs(**kwargs)
# torch resize uses interpolation instead of resample
resample = kwargs.pop("resample")
# Check if resample is an int before checking if it's an instance of PILImageResampling
# because if pillow < 9.1.0, resample is an int and PILImageResampling is a module.
# Checking PILImageResampling will fail with error `TypeError: isinstance() arg 2 must be a type or tuple of types`.
kwargs["interpolation"] = (
pil_torch_interpolation_mapping[resample] if isinstance(resample, (int, PILImageResampling)) else resample
)
# Pop kwargs that are not needed in _preprocess
kwargs.pop("default_to_square")
kwargs.pop("data_format")
return self._preprocess(images, *args, **kwargs)
分析原因,并解决。