目录
opencv实现
opencv实现,只有缩小
import globimport cv2def resize_image(image, max_area=800 * 400):original_height, original_width = image.shape[:2]max_area_found = 0best_resized_image = None# 确定最小缩放比例,避免过度缩小导致图像信息丢失过多或出现不合理情况min_scale = 0.2# 从原始尺寸开始逐步缩放,可缩小也可放大,但限制最小缩放比例for scale in [scale_value for scale_value in [i / 100 for i in range(100, int(min_scale * 100), -1)] if scale_value >= min_scale]:new_width = int(original_width * scale / 64) * 64new_height = int(original_height * scale / 64) * 64if 0 < new_width * new_height < max_area:resized_image = cv2.resize(image, (new_width, new_height))current_area = new_width * new_heightif current_area > max_area_found:max_area_found = current_areabest_resized_image = resized_imagebreakreturn best_resized_imageimg_paths=glob.glob(r'D:\data\coco128\images\train2017/*.jpg')for img_path in img_paths:image = cv2.imread(img_path)resized_image = resize_image(image)if resized_image is not None:print(image.shape,img_path)print(resized_image.shape[0]/64,resized_image.shape[1]/64,resized_image.shape[0],resized_image.shape[1])cv2.imshow('Resized Image', resized_image)cv2.waitKey(0)cv2.destroyAllWindows()else:print("无法找到满足条件的缩放图像。")