File size: 3,410 Bytes
4dca198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""Single-image FFA-Net ONNX inference with side-by-side comparison output."""

import argparse
import sys
from pathlib import Path

import numpy as np
import onnxruntime as ort
from PIL import Image, ImageDraw, ImageFont


FILE = Path(__file__).resolve()
NET_DIR = FILE.parent
ROOT_DIR = NET_DIR.parent
sys.path.insert(0, str(NET_DIR))


def parse_args():
    parser = argparse.ArgumentParser(description="FFA-Net ONNX single-image inference.")
    parser.add_argument("--onnx", default='onnx/ffa_ots_512x512.onnx', help="ONNX model path.")
    parser.add_argument("--input", default='outdoor_natural/nh(2).jpg', help="Path to input hazy image.")
    parser.add_argument("--output", default="onnx_compare.png", help="Output comparison image path (hazy | dehazed).")
    parser.add_argument("--height", type=int, default=512, help="ONNX input height.")
    parser.add_argument("--width", type=int, default=512, help="ONNX input width.")
    parser.add_argument("--no_label", action="store_true", help="Do not draw hazy/dehazed labels.")
    return parser.parse_args()


MEAN = np.array([0.64, 0.6, 0.58], dtype=np.float32).reshape(3, 1, 1)
STD = np.array([0.14, 0.15, 0.152], dtype=np.float32).reshape(3, 1, 1)


def preprocess(image_path, height, width):
    image = Image.open(image_path).convert("RGB")
    image = image.resize((width, height), Image.BICUBIC)
    arr = np.asarray(image).astype(np.float32) / 255.0
    arr = arr.transpose(2, 0, 1)
    arr = (arr - MEAN) / STD          # 训练同款归一化
    return arr[None, ...].astype(np.float32)


def postprocess(output):
    arr = np.squeeze(output, axis=0).transpose(1, 2, 0)
    arr = np.clip(arr, 0.0, 1.0)
    return Image.fromarray((arr * 255.0 + 0.5).astype(np.uint8))


def draw_label(img, text):
    draw = ImageDraw.Draw(img)
    try:
        font = ImageFont.truetype("DejaVuSans-Bold.ttf", max(16, img.height // 40))
    except Exception:
        font = ImageFont.load_default()
    padding = max(5, img.height // 140)
    bbox = draw.textbbox((0, 0), text, font=font)
    box_w = bbox[2] - bbox[0] + padding * 2
    box_h = bbox[3] - bbox[1] + padding * 2
    draw.rectangle([0, 0, box_w, box_h], fill=(0, 0, 0))
    draw.text((padding, padding), text, fill=(255, 255, 255), font=font)


def make_compare(hazy, dehazed, with_label=True):
    hazy = hazy.convert("RGB")
    dehazed = dehazed.convert("RGB")
    if with_label:
        hazy = hazy.copy()
        dehazed = dehazed.copy()
        draw_label(hazy, "hazy")
        draw_label(dehazed, "dehazed")
    canvas = Image.new("RGB", (hazy.width + dehazed.width, hazy.height), color=(255, 255, 255))
    canvas.paste(hazy, (0, 0))
    canvas.paste(dehazed, (hazy.width, 0))
    return canvas


def main():
    args = parse_args()

    hazy_img = Image.open(args.input).convert("RGB").resize((args.width, args.height), Image.BICUBIC)
    inp = preprocess(args.input, args.height, args.width)
    session = ort.InferenceSession(args.onnx, providers=["CPUExecutionProvider"])
    input_name = session.get_inputs()[0].name
    out = session.run(None, {input_name: inp})[0]

    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    dehazed = postprocess(out)
    compare = make_compare(hazy_img, dehazed, with_label=not args.no_label)
    compare.save(str(output_path))
    print(f"Saved: {output_path}")


if __name__ == "__main__":
    main()