蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行图像预处理、增强组合与 MNIST 对比实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-image-transforms.py
explore-image-transforms.py213 行
"""Verify torchvision.transforms basic ops, augmentations, Compose, custom transforms and MNIST grid."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import platform

import numpy as np
from PIL import Image, __version__ as pillow_version
import torch
from torch.utils.data import DataLoader, Dataset
import torchvision
from torchvision import transforms


MNIST_SHA256 = "731c5ac602752760c8e48fbffcf8c3b850d9dc2a2aedcf2cc48468fc17b673d1"


class CustomScaleTransform:
    def __init__(self, factor=2.0):
        self.factor = factor

    def __call__(self, tensor):
        return tensor * self.factor


class OfflineMNISTDataset(Dataset):
    def __init__(self, images, labels, transform=None):
        self.images = images
        self.labels = labels
        self.transform = transform

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        img = Image.fromarray(self.images[idx], mode="L")
        if self.transform is not None:
            img = self.transform(img)
        return img, int(self.labels[idx])


def record(cases, name, inputs, conditions, action, expected, actual, **measurements):
    assert actual == expected, (name, expected, actual)
    cases.append(dict(name=name, inputs=inputs, prerequisites=conditions, action=action,
                      expected=expected, actual=actual, passed=True, measurements=measurements))


def make_rgb_gradient(width, height):
    arr = np.zeros((height, width, 3), dtype=np.uint8)
    arr[:, :, 0] = np.linspace(0, 255, width, dtype=np.uint8)[None, :]
    arr[:, :, 1] = np.linspace(0, 255, height, dtype=np.uint8)[:, None]
    arr[:, :, 2] = 128
    return Image.fromarray(arr, mode="RGB")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mnist", type=Path, required=True, help="path to checksum-verified mnist.npz")
    parser.add_argument("--figures", type=Path, default=Path("charts"))
    args = parser.parse_args()
    torch.set_num_threads(1)
    cases = []

    to_tensor = transforms.ToTensor()
    pil_small = make_rgb_gradient(6, 4)
    t_uint8 = to_tensor(pil_small)
    f32_arr = np.full((4, 6, 3), 2.5, dtype=np.float32)
    t_float = to_tensor(f32_arr)
    record(cases, "to_tensor_uint8_vs_float", {"pil_size_wh": [6, 4], "float_val": 2.5},
           "PIL uint8 image vs float32 NumPy HWC array",
           "Check HWC->CHW permutation and scaling only on uint8 input",
           [[3, 4, 6], True, [3, 4, 6], 2.5],
           [list(t_uint8.shape), bool(t_uint8.min() >= 0.0 and t_uint8.max() <= 1.0 and t_uint8.dtype == torch.float32),
            list(t_float.shape), float(t_float[0, 0, 0])])

    rgb = torch.tensor([[[0.5]], [[0.5]], [[0.5]]], dtype=torch.float32)
    norm_imgnet = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(rgb)
    expected_imgnet = [(0.5 - m) / s for m, s in zip((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]
    gray = torch.tensor([[[0.0, 0.5, 1.0]]], dtype=torch.float32)
    norm_gray = transforms.Normalize(mean=[0.5], std=[0.5])(gray)
    record(cases, "normalize_channel_stats", {"imagenet_mean": [0.485, 0.456, 0.406], "gray_vals": [0.0, 0.5, 1.0]},
           "Channel-wise (x - mean) / std on float tensors",
           "Compare ImageNet RGB normalization and single-channel [-1, 1] mapping",
           [True, [-1.0, 0.0, 1.0]],
           [np.allclose(norm_imgnet.squeeze().tolist(), expected_imgnet, atol=1e-6),
            norm_gray.squeeze().tolist()])

    rect = make_rgb_gradient(200, 100)
    r_exact = transforms.Resize((128, 128))(rect)
    r_short = transforms.Resize(128)(rect)
    r_256 = transforms.Resize((256, 256))(rect)
    crop_128 = transforms.CenterCrop(128)(r_256)
    crop_224 = transforms.CenterCrop(224)(r_256)
    record(cases, "resize_and_center_crop", {"source_wh": [200, 100]},
           "Tuple (H, W) vs integer shorter-edge Resize, plus CenterCrop",
           "Check output PIL sizes (width, height) for Resize and CenterCrop",
           [[128, 128], [256, 128], [256, 256], [128, 128], [224, 224]],
           [list(r_exact.size), list(r_short.size), list(r_256.size),
            list(crop_128.size), list(crop_224.size)])

    base_img = make_rgb_gradient(256, 256)
    base_t = to_tensor(base_img)
    flip_always = to_tensor(transforms.RandomHorizontalFlip(p=1.0)(base_img))
    flip_never = to_tensor(transforms.RandomHorizontalFlip(p=0.0)(base_img))
    torch.manual_seed(42)
    rot45 = to_tensor(transforms.RandomRotation(degrees=45)(base_img))
    jitter = to_tensor(transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)(base_img))
    rcrop = to_tensor(transforms.RandomCrop(128)(base_img))
    rrcrop = to_tensor(transforms.RandomResizedCrop(224)(base_img))
    record(cases, "augmentation_transforms", {"source_wh": [256, 256], "seed": 42},
           "Deterministic p=1/p=0 flips and seeded rotation, color jitter and random crops",
           "Verify mirror equivalence, non-identity transforms and target tensor shapes",
           [True, True, [3, 256, 256], True, [3, 256, 256], True, [3, 128, 128], [3, 224, 224]],
           [torch.equal(flip_always, torch.flip(base_t, dims=[2])),
            torch.equal(flip_never, base_t),
            list(rot45.shape), not torch.equal(rot45, base_t),
            list(jitter.shape), not torch.equal(jitter, base_t),
            list(rcrop.shape), list(rrcrop.shape)])

    pipe_pil = transforms.Compose([
        transforms.Resize((128, 128)),
        transforms.RandomHorizontalFlip(p=1.0),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
    ])
    pipe_tensor_resize = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
        transforms.Resize((256, 256), antialias=True),
    ])
    out_pil = pipe_pil(base_img)
    out_tr = pipe_tensor_resize(base_img)
    scaled = CustomScaleTransform(2.0)(torch.tensor([1.5, -2.0]))
    record(cases, "compose_and_custom_transform", {"scale": 2.0},
           "Compose order on PIL-first vs Tensor-resize pipelines, plus callable custom transform",
           "Verify output shapes, value bounds and CustomScaleTransform output",
           [[3, 128, 128], True, [3, 256, 256], [3.0, -4.0]],
           [list(out_pil.shape), bool(out_pil.min() >= -1.0 and out_pil.max() <= 1.0),
            list(out_tr.shape), scaled.tolist()])

    digest = sha256(args.mnist.read_bytes()).hexdigest()
    if digest != MNIST_SHA256:
        raise ValueError("MNIST archive checksum mismatch.")
    with np.load(args.mnist, allow_pickle=False) as arc:
        raw_imgs = arc["x_train"][:64]
        raw_lbls = arc["y_train"][:64]

    mnist_pipe = transforms.Compose([
        transforms.Resize((128, 128)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5], std=[0.5]),
    ])
    mnist_ds = OfflineMNISTDataset(raw_imgs, raw_lbls, transform=mnist_pipe)
    b_imgs, b_lbls = next(iter(DataLoader(mnist_ds, batch_size=32, shuffle=False)))
    record(cases, "mnist_composed_batch", {"sha256": digest, "batch_size": 32, "resize": [128, 128]},
           "Verified local MNIST archive converted through Resize(128,128) + ToTensor + Normalize",
           "Verify batch tensor shape [32, 1, 128, 128] and normalized range [-1, 1]",
           [[32, 1, 128, 128], [32], True],
           [list(b_imgs.shape), list(b_lbls.shape), bool(b_imgs.min() >= -1.0 and b_imgs.max() <= 1.0)])

    import matplotlib
    matplotlib.use("Agg")
    from matplotlib import pyplot as plt

    torch.manual_seed(2025)
    aug_pipe = transforms.Compose([
        transforms.RandomHorizontalFlip(p=0.5),
        transforms.RandomRotation(30),
        transforms.ToTensor(),
    ])
    aug_ds = OfflineMNISTDataset(raw_imgs[:5], raw_lbls[:5], transform=aug_pipe)
    args.figures.mkdir(parents=True, exist_ok=True)
    fig, axes = plt.subplots(2, 5, figsize=(9.6, 4.2), layout="constrained")
    fig.suptitle("MNIST / Original (top) vs RandomFlip + RandomRotation(30) (bottom)",
                 color="#173b55", fontweight="bold")
    changed = 0
    for idx in range(5):
        orig = raw_imgs[idx]
        aug_t, lbl = aug_ds[idx]
        aug_np = aug_t.squeeze(0).numpy()
        if not np.allclose(orig / 255.0, aug_np, atol=1e-4):
            changed += 1
        axes[0, idx].imshow(orig, cmap="gray", vmin=0, vmax=255, interpolation="nearest")
        axes[0, idx].set_title(f"Orig {lbl}", fontsize=10, color="#174d79")
        axes[0, idx].axis("off")
        axes[1, idx].imshow(aug_np, cmap="gray", vmin=0, vmax=1, interpolation="nearest")
        axes[1, idx].set_title(f"Aug {lbl}", fontsize=10, color="#8f4518")
        axes[1, idx].axis("off")
    out_png = args.figures / "mnist-transforms-compare.png"
    fig.savefig(out_png, dpi=125, facecolor="#f7fafb")
    plt.close(fig)
    with Image.open(out_png) as png:
        assert png.format == "PNG"
        width, height = png.size
    record(cases, "observed_transforms_figure", {"samples": 5, "seed": 2025},
           "Matplotlib Agg comparison of 5 original vs augmented MNIST digits",
           "Verify rendered PNG dimensions and that augmented samples differ from originals",
           [True, 1200, 525],
           [changed >= 4, width, height],
           labels=raw_lbls[:5].tolist(), changed_count=changed)

    print(json.dumps(dict(
        version=platform.python_version(), system=platform.system(), torch=torch.__version__,
        torchvision=torchvision.__version__, pillow=pillow_version, numpy=np.__version__,
        matplotlib=matplotlib.__version__, cases=cases,
        figures={out_png.name: sha256(out_png.read_bytes()).hexdigest()},
    ), allow_nan=False))


if __name__ == "__main__":
    main()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-transforms-lab/explore-image-transforms.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-image-transforms.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a445.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习