gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
帮我写一个用bicubic下采样图像的python代码,直接使用scale_factor控制
- User
帮我写一个用bicubic下采样图像的python代码,直接使用scale_factor控制
- Assistant
下面是一个使用Python和PyTorch实现bicubic下采样图像的示例代码,直接使用
scale_factor控制缩放比例:import torch import torch.nn.functional as F from PIL import Image import numpy as np def bicubic_downsample(img, scale_factor): """ 用bicubic插值对图像进行下采样 Args: img (PIL.Image 或 numpy.ndarray 或 torch.Tensor): 输入图像 scale_factor (float): 下采样的缩放因子 (0 < scale_factor < 1) Returns: torch.Tensor: 下采样后的图像张量,范围[0,1],shape=[C,H_new,W_new] """ # 如果是PIL图像,转成tensor if isinstance(img, Image.Image): img = np.array(img) img = torch.from_numpy(img).float() / 255.0 if img.ndim == 2: img = img.unsqueeze(2) # 灰度图单通道 img = img.permute(2, 0, 1) # HWC -> CHW elif isinstance(img, np.ndarray): img = torch.from_numpy(img).float() / 255.0 if img.ndim == 2: img = img.unsqueeze(0) # 灰度图 else: img = img.permute(2, 0, 1) # HWC -> CHW elif isinstance(img, torch.Tensor): if img.max() > 1.0: img = img.float() / 255.0 if img.ndim == 3 and img.shape[0] not in [1,3,4]: # 如果形状是HWC,转成CHW img = img.permute(2, 0, 1) else: raise TypeError("img must be PIL.Image or numpy.ndarray or torch.Tensor") _, H, W = img.shape H_new = int(H * scale_factor) W_new = int(W * scale_factor) img = img.unsqueeze(0) # 增加batch维度:1 x C x H x W # 使用bicubic插值下采样 downsampled = F.interpolate(img, size=(H_new, W_new), mode='bicubic', align_corners=True) return downsampled.squeeze(0) # C x H_new x W_new if __name__ == "__main__": img_path = "your_image.jpg" # 替换成你的图片路径 scale_factor = 0.5 # 下采样到50% img = Image.open(img_path).convert('RGB') down_img = bicubic_downsample(img, scale_factor) # 转成PIL图像展示或保存 down_img_np = (down_img.permute(1, 2, 0).numpy() * 255).astype(np.uint8) down_img_pil = Image.fromarray(down_img_np) down_img_pil.show() # 如果要保存 # down_img_pil.save("downsampled_image.jpg")