@@ -180,17 +180,33 @@ def verify_exist(file_path: Union[str, Path]):
180180 raise LoadImageError (f"{ file_path } does not exist." )
181181
182182
183- def ResizePad (img , target_size ):
184- h , w = img .shape [:2 ]
185- m = max (h , w )
186- ratio = target_size / m
187- new_w , new_h = int (ratio * w ), int (ratio * h )
188- img = cv2 .resize (img , (new_w , new_h ), cv2 .INTER_LINEAR )
189- top = (target_size - new_h ) // 2
190- bottom = (target_size - new_h ) - top
191- left = (target_size - new_w ) // 2
192- right = (target_size - new_w ) - left
193- img1 = cv2 .copyMakeBorder (
194- img , top , bottom , left , right , cv2 .BORDER_CONSTANT , value = (114 , 114 , 114 )
195- )
196- return img1 , new_w , new_h , left , top
183+ def resize_and_center_crop (image : np .ndarray , target_size : int ):
184+ """
185+ Resize the image so that the smallest side is equal to the target size,
186+ then crop the center of the image to the specified target size.
187+
188+ Args:
189+ image (np.ndarray): Input image as a NumPy array with shape (height, width, channels).
190+ target_size (int): Target size for the smallest side of the image and the output size.
191+
192+ Returns:
193+ (np.ndarray): Resized and cropped image as a NumPy array.
194+ """
195+ # 获取输入图像的尺寸
196+ h , w = image .shape [:2 ]
197+
198+ # 计算缩放比例
199+ scale = target_size / min (h , w )
200+ new_h , new_w = int (h * scale ), int (w * scale )
201+
202+ # 缩放图像
203+ resized_image = cv2 .resize (image , (new_w , new_h ), interpolation = cv2 .INTER_LINEAR )
204+
205+ # 计算裁剪的起始位置
206+ i = (new_h - target_size ) // 2
207+ j = (new_w - target_size ) // 2
208+
209+ # 裁剪图像
210+ cropped_image = resized_image [i : i + target_size , j : j + target_size ]
211+
212+ return cropped_image
0 commit comments