class DinoFcImageProcessor(BaseImageProcessorFast):
model_input_names = ["pixel_values"]
valid_kwargs = DefaultFastImageProcessorKwargs
code
# 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
以下是库中相关代码:
code
分析原因,并解决。
Assistant
Okay, let's analyze the problem and the code provided.
Reason for the Error:
Your DinoFcImageProcessor inherits from BaseImageProcessorFast.
When you call processor(images=image, return_tensors="pt"), the __call__ method of the base class (or a mixin it inherits from) is triggered, which in turn calls self.preprocess.
The preprocess method in BaseImageProcessorFast (which your original preprocess method was calling via super().preprocess) has a specific flow:
It gathers all arguments passed by the user (kwargs).
It sets default values for any missing arguments based on the processor's class attributes (like do_resize, resample, do_rescale, etc.).
It performs input preparation (_prepare_input_images).
It calls _further_process_kwargs.
Crucially, it calls self._validate_preprocess_kwargs(**processed_kwargs).
It then calls self._preprocess(images, *args, **kwargs).
The _validate_preprocess_kwargs method (which calls validate_fast_preprocess_arguments) contains the logic: if do_resize and (size is None or resample is None): raise ValueError(...).
In your DinoFcImageProcessor, the class attribute do_resize is set to True.
When the base preprocess method sets defaults, do_resize becomes True in the kwargs dictionary. However, size is not a class attribute in DinoFcImageProcessor, and you are not passing a size argument when calling processor(...). Therefore, size remains None in the kwargs dictionary at the point of validation.
The validation if do_resize and (size is None or resample is None): evaluates to if True and (None is None or Resampling.BICUBIC is None):, which simplifies to if True and (True or False):, which is if True and True:. This condition is met, and the ValueError is raised.
The core problem is that your custom calculates the size dynamically using the base class's method has already attempted to validate the parameters based on the assumption that a single would be provided upfront when is .
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)
_preprocess
per image
get_new_size
after
preprocess
size
do_resize
True
Solution:
The DinoFcImageProcessor has custom resizing logic that doesn't fit the standard BaseImageProcessorFast validation flow which expects a fixed size when do_resize is True. To fix this, you need to override the preprocess method in your DinoFcImageProcessor to bypass the problematic validation step, while still utilizing the other useful parts of the base preprocess method (like input preparation) and calling your custom _preprocess.
Here's the corrected code:
python
import math
from typing import Any, Dict, List, Optional, Tuple, Union
# Assuming necessary imports from transformers and torch
# You might need specific imports depending on your exact environment setup
from transformers import DefaultFastImageProcessorKwargs, BatchFeature, ImageInput, SizeDict, ProcessorMixin
from transformers.image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
get_image_size,
infer_channel_dimension_for_image,
is_scaled_image,
numpy_to_pytorch,
pil_to_numpy,
pil_to_pytorch,
pytorch_to_numpy,
to_channel_dimension_format,
validate_fast_preprocess_arguments, # Need this signature for reference, but won't call it
validate_kwargs, # Need this to validate initial kwargs
)
from transformers.utils import (
ExplicitEnum,
TensorType,
is_jax_available,
is_tf_available,
is_torch_available,
requires_backends,
)
# Import the base class correctly
from transformers.image_processing_utils import BaseImageProcessorFast
# Assuming auto_docstring is a decorator you have
from transformers.utils.doc import auto_docstring
# Ensure torch is available and import functional
if is_torch_available():
import torch
import torch.nn.functional as F
else:
raise ImportError("Requires torch to be installed.")
# Ensure PIL Resampling is available
try:
from PIL.Image import Resampling
except ImportError:
# Provide dummy if PIL is not installed (though transformers requires it usually)
class Resampling:
NEAREST = 0
BOX = 4
BILINEAR = 2
HAMMING = 5
BICUBIC = 3
LANCZOS = 1
print("Warning: PIL not found, using dummy Resampling enum.")
# Assuming a mapping from PIL Resampling to Torchvision InterpolationMode exists
# This is typically handled internally by BaseImageProcessorFast, but defining explicitly if needed
# Or rely on the base class's `_further_process_kwargs` or similar that does this mapping.
# Looking at the base code, it maps `resample` to `interpolation` *after* validation.
# So, we need this mapping or ensure the base class handles it. Let's copy the mapping logic.
try:
# Try importing from torchvision
from torchvision.transforms import functional as TF
from torchvision.transforms.functional import InterpolationMode
pil_torch_interpolation_mapping = {
Resampling.NEAREST: InterpolationMode.NEAREST,
Resampling.BOX: InterpolationMode.BOX,
Resampling.BILINEAR: InterpolationMode.BILINEAR,
Resampling.HAMMING: InterpolationMode.HAMMING,
Resampling.BICUBIC: InterpolationMode.BICUBIC,
Resampling.LANCZOS: InterpolationMode.LANCZOS,
}
except ImportError:
# Fallback or raise error if torchvision is required but not found
print("Warning: torchvision not found. Image processing might fail.")
# Define a dummy mapping if needed, depending on how self.resize is implemented in the base class
pil_torch_interpolation_mapping = {} # This might cause issues later
class DinoFcImageProcessor(BaseImageProcessorFast):
model_input_names = ["pixel_values"]
# valid_kwargs = DefaultFastImageProcessorKwargs # This is too restrictive.
# The base class's __init__ will automatically populate _valid_kwargs_names
# with attributes having type annotations defined on the class and parent classes,
# plus anything explicitly added. So, leaving this as default or ensuring __init__ handles
# custom attributes is usually sufficient.
# Define default configuration as class attributes
do_resize: bool = True # Keep as True semantically
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):
# BaseImageProcessorFast's __init__ will read these class attributes
# and set instance attributes and potentially add them to _valid_kwargs_names.
super().__init__(**kwargs)
# Override preprocess completely to bypass the problematic validation flow
@auto_docstring
def preprocess(
self, images: ImageInput, *args, **kwargs: Any
) -> BatchFeature:
# The base class's preprocess method does several steps before calling _preprocess.
# We need to replicate these steps but skip the validation that requires 'size'.
# Step 1: Validate input kwargs against known processor kwargs
# self._valid_kwargs_names is populated by the base __init__ from class attributes
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_kwargs_names)
# Step 2: Set default kwargs from the processor's configuration
# This dictionary will contain do_resize=True, resample=..., but size=None
processed_kwargs = kwargs.copy()
for kwarg_name in self._valid_kwargs_names:
processed_kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))
# Step 3: Prepare input images (e.g., convert to PIL Image, then to tensor, handle channels)
# Extract preparation specific args
do_convert_rgb = processed_kwargs.pop("do_convert_rgb", getattr(self, "do_convert_rgb", True)) # Use getattr with default for safety
input_data_format = processed_kwargs.pop("input_data_format", None)
device = processed_kwargs.pop("device", None)
images = self._prepare_input_images(
images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
)
# _prepare_input_images returns a list of tensors [C, H, W] or [H, W, C] depending on data_format,
# or a single tensor [N, C, H, W] or [N, H, W, C] if the input was a batch tensor.
# Assuming it returns a list of CHW tensors for list input, or NCHW for batch tensor input.
# The subsequent _preprocess expects a list of CHW tensors. If _prepare_input_images returns NCHW,
# we might need to convert it back to a list of CHW tensors here.
# Let's check the base class _prepare_input_images return type. It usually returns a list of tensors.
# Step 4: Further process kwargs (e.g., convert size tuples to SizeDicts)
# This might expect 'size' to be present if do_resize is True, but the base implementation
# is usually robust enough to handle size=None here.
processed_kwargs = self._further_process_kwargs(**processed_kwargs)
# Step 5: ***SKIP THE PROBLEMATIC VALIDATION***
# Do NOT call self._validate_preprocess_kwargs(**processed_kwargs)
# The validation would fail because do_resize is True but size is None.
# Step 6: Map resample to interpolation and pop standard kwargs not needed by _preprocess signature
# Need to use the value of resample from processed_kwargs (which has the default)
resample = processed_kwargs.pop("resample", getattr(self, "resample", None))
if resample is not None: # Only map if resample was present/defaulted
processed_kwargs["interpolation"] = (
pil_torch_interpolation_mapping[resample] if isinstance(resample, (int, PILImageResampling)) else resample
)
# else: interpolation will remain None if not set by user/defaults
# Pop other standard kwargs consumed before _preprocess in base
# The actual list might vary slightly depending on the base class version.
# common ones popped: default_to_square, data_format
processed_kwargs.pop("default_to_square", None)
processed_kwargs.pop("data_format", None) # Used in _prepare_input_images
# Step 7: Call the core preprocessing logic (_preprocess)
# Pass the list of prepared images and all remaining kwargs.
# _preprocess will receive do_resize=True, size=None, interpolation=..., etc.
return self._preprocess(images=images, *args, **processed_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"]
# Add safety checks for zero dimensions
if width == 0 or height == 0:
print(f"Warning: Image has zero dimension ({width}, {height}). Cannot compute new size. Using base resolution fallback.")
return self.base_resolution # Fallback to a default size
# Calculate target patch count from base resolution (assuming base_resolution is also patch-aligned)
base_patch_h = self.base_resolution[0] / self.patch_size
base_patch_w = self.base_resolution[1] / self.patch_size
target_num_patches = base_patch_h * base_patch_w
aspect_ratio = height / width
# Calculate target number of patches along height and width while maintaining original aspect ratio
# num_patches_h * num_patches_w = target_num_patches
# (num_patches_h * patch_size) / (num_patches_w * patch_size) = height / width = aspect_ratio
# num_patches_h / num_patches_w = aspect_ratio => num_patches_h = aspect_ratio * num_patches_w
# Substitute: (aspect_ratio * num_patches_w) * num_patches_w = target_num_patches
# num_patches_w^2 = target_num_patches / aspect_ratio => num_patches_w = sqrt(target_num_patches / aspect_ratio)
# num_patches_h = aspect_ratio * sqrt(target_num_patches / aspect_ratio) = sqrt(target_num_patches * aspect_ratio)
# Handle potential division by zero or sqrt of negative number if aspect_ratio is problematic
if aspect_ratio <= 0:
print(f"Warning: Image has non-positive aspect ratio ({aspect_ratio}). Cannot compute new size. Using base resolution fallback.")
return self.base_resolution # Fallback
try:
new_num_patches_h = math.sqrt(target_num_patches * aspect_ratio)
new_num_patches_w = math.sqrt(target_num_patches / aspect_ratio)
except ValueError as e:
print(f"Error calculating new patch counts for size ({width}, {height}) with aspect ratio {aspect_ratio}: {e}. Using base resolution fallback.")
return self.base_resolution # Fallback
# New dimensions must be multiples of patch_size after rounding patch counts
new_h = int(round(new_num_patches_h)) * self.patch_size
new_w = int(round(new_num_patches_w)) * self.patch_size
# Ensure dimensions are at least patch_size, especially important for small input images
new_h = max(new_h, self.patch_size)
new_w = max(new_w, self.patch_size)
# Add a check that the resulting size is reasonable, maybe relate to base_resolution
# e.g., prevent extremely large sizes from small patch sizes / large base_resolution
# For simplicity, skipping this advanced check unless necessary.
return new_h, new_w # Note: Returns (height, width)
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 an empty tensor with the correct number of dimensions (e.g., NCHW)
# based on expected output format, if possible. Assuming N=0, C=images[0].shape[0] (if images non-empty), H=0, W=0
# Or better, return a tensor with shape [0] as F.pad would likely expect more dims.
# An empty list typically indicates no images processed, so returning a zero-length batch is appropriate.
# Determine expected output shape based on potential channels. If images list is empty, we don't know channels.
# Returning torch.empty(0) might be okay depending on downstream usage, but let's return shape [0, C, H, W] if we can infer C.
# If called with empty list, we cannot infer C. Let's stick to original for now but be mindful.
return torch.empty(0)
# Assuming input images are a list of [C, H, W] tensors (from _prepare_input_images)
# Need to find max H and W across the batch
max_h = max(img.shape[1] for img in images)
max_w = max(img.shape[2] for img in images)
num_channels = images[0].shape[0] # Assuming all images have the same number of channels
batch_shape = (len(images), num_channels, max_h, max_w)
# Create the output batch tensor filled with zeros
# Use the dtype and device of the input images for consistency
padded_batch = torch.zeros(batch_shape, dtype=images[0].dtype, device=images[0].device)
# Iterate through images and paste them into the padded batch tensor
for i, img in enumerate(images):
# Assuming NCHW format: dim 1 is H, dim 2 is W
# Calculate padding needed for this image
pad_h = max_h - img.shape[1]
pad_w = max_w - img.shape[2]
# Use torch.nn.functional.pad to pad the image.
# Pad format is (pad_left, pad_right, pad_top, pad_bottom) relative to the last two dimensions.
# We want to pad on the right and bottom.
# F.pad expects input tensor as [..., H, W]
padded_img = F.pad(img, (0, pad_w, 0, pad_h), value=0) # value=0 is default but explicit is good
# Place the padded single image tensor into the batch tensor
# The padded image is now [C, max_h, max_w]
padded_batch[i] = padded_img
return padded_batch
def _preprocess(
self,
images: list[torch.Tensor], # This is the list of tensors [C, H, W] from _prepare_input_images
do_resize: bool, # This will be True based on the class attribute / processed_kwargs
interpolation: "F.InterpolationMode", # This is the mapped interpolation mode
do_rescale: bool,
rescale_factor: float,
do_normalize: bool,
image_mean: list[float],
image_std: list[float],
return_tensors: str | TensorType | None,
# Accept any other standard or custom kwargs passed from the overridden preprocess method.
# e.g., 'size' will be None, which is fine as we don't use it here for resizing.
**kwargs,
) -> BatchFeature:
"""
The core preprocessing function executing the DinoFC specific steps:
dynamic resize per image -> optional pad batch -> rescale -> normalize.
"""
# This method implements the *actual* preprocessing steps for DinoFC.
# The flags like do_resize, do_rescale, do_normalize are now correctly passed
# from the overridden preprocess method based on the processor's configuration.
# Step 1: Custom Resizing (per image, dynamically calculated size)
processed_images = []
# Loop through the list of images (each is a [C, H, W] tensor)
for image_tensor in images:
# Calculate the new size for this specific image
_, h, w = image_tensor.shape
new_h, new_w = self.get_new_size(SizeDict(height=h, width=w))
# Perform the resize.
# self.resize is an alias for torchvision.transforms.functional.resize in BaseImageProcessorFast
# It expects input as [C, H, W] for a single image, which matches `image_tensor`.
# It uses the `interpolation` argument passed to this method.
resized_image = self.resize(
image=image_tensor,
size=SizeDict(height=new_h, width=new_w),
interpolation=interpolation,
# data_format=ChannelDimension.FIRST, # Explicitly state CHW input if needed by self.resize
)
processed_images.append(resized_image)
# Step 2: Optional Padding and Stacking
# Check the class attribute `self.do_pad` to decide whether to pad
if self.do_pad:
# _pad_batch takes a list of CHW tensors and returns a single padded NCHW tensor
pixel_values = self._pad_batch(processed_images)
else:
# If not padding, all images *must* have the same dimensions after resizing to be stacked.
# The `get_new_size` method calculates size per image. If original images had different aspect ratios,
# the resulting `new_h`, `new_w` might be different, even though they preserve patch count/aspect ratio.
# Adding a check here to prevent errors if images have different sizes and padding is off.
if processed_images: # Check if the list is not empty
first_shape = processed_images[0].shape
if any(img.shape != first_shape for img in processed_images):
raise ValueError(
"Images must all be the same size after resizing to stack when `do_pad` is False."
"This can happen if original images had different aspect ratios."
)
# Stack the list of CHW tensors into a single NCHW batch tensor
pixel_values = torch.stack(processed_images)
# Step 3: Rescale the batch tensor
# Use the `do_rescale` flag and `rescale_factor` passed to this method
if do_rescale:
# self.rescale expects input in NCHW or N... depending on data_format
pixel_values = self.rescale(image=pixel_values, scale=rescale_factor)
# Step 4: Normalize the batch tensor
# Use the `do_normalize` flag and `image_mean`/`image_std` passed to this method
if do_normalize:
# self.normalize expects input in NCHW or N... depending on data_format
pixel_values = self.normalize(image=pixel_values, mean=image_mean, std=image_std)
# Step 5: Return as BatchFeature
# The `return_tensors` argument controls the final output format (e.g., "pt", "tf", "np")
return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors)
Explanation of Changes:
Override preprocess: The key change is to completely replace the base class's preprocess method. The original override was simply calling super().preprocess, which led back to the problematic validation.
Replicate Base Steps (partially): The new preprocess method copies the necessary initial steps from the base class's preprocess implementation:
Validating input kwargs using validate_kwargs.
Setting default kwargs from the processor's class attributes (processed_kwargs = kwargs.copy(); for ... setdefault(...)). This ensures flags like do_resize, do_rescale, do_normalize, resample and their values are correctly picked up from the processor's configuration or user input.
Extracting and handling input preparation arguments (do_convert_rgb, input_data_format, device).
Calling self._prepare_input_images. This handles converting various input types (PIL Image, numpy array, list, batch tensor) into a consistent list of tensors (usually [C, H, W]) or a single batch tensor [N, C, H, W] on the correct device and with the correct channel format.
Calling self._further_process_kwargs. This handles minor transformations on kwargs, like converting a tuple size=(h, w) into a SizeDict(height=h, width=w).
Mapping resample to interpolation.
Popping kwargs consumed earlier in the base preprocess flow.
Skip Validation: The line self._validate_preprocess_kwargs(**processed_kwargs) is deliberately omitted from the new preprocess method. This bypasses the check that failed.
Call _preprocess: The overridden preprocess method now calls self._preprocess(images=images, *args, **processed_kwargs), passing the prepared images and the processed arguments directly to your core logic.
_preprocess Logic: The _preprocess method itself remains largely the same, but it now relies on the flags (do_resize, do_rescale, do_normalize) and values (interpolation, rescale_factor, image_mean, image_std) being correctly passed to it from the overridden preprocess method. It executes the DinoFC-specific flow: iterate images -> calculate dynamic size -> resize -> (pad & stack) -> rescale batch -> normalize batch.
Robustness: Added checks in get_new_size for zero dimensions or problematic aspect ratios, and a check in _preprocess before stacking when do_pad=False to ensure all images are the same size. Also ensured _pad_batch uses the image dtype and device.
By overriding preprocess and skipping the incompatible validation step, you allow your custom image size calculation and resizing logic within _preprocess to execute without triggering the error from the base class's assumptions.