abhishek-gola's picture
added lapsrn an macbeth onnx (#16)
1387a61
Raw History Blame Contribute Delete
2.4 kB
import argparse
import os
import cv2 as cv
import numpy as np
here = os.path.dirname(os.path.abspath(__file__))
# The two heads of the Laplacian pyramid, and the scale each one produces.
OUTPUTS = [("NCHW_output_2x", 2), ("NCHW_output_4x", 4)]
def upsample(net, img, node_name, scale):
"""Run one pyramid head and rebuild a colour image from its luma output.
Mirrors dnn_superres' preprocess_YCrCb / reconstruct_YCrCb: the network only
ever sees the Y channel, and Cr/Cb are bicubically upscaled and merged back.
"""
ycrcb = cv.cvtColor(img, cv.COLOR_BGR2YCrCb).astype(np.float32) / 255.0
y, cr, cb = cv.split(ycrcb)
# This model takes NHWC [1, H, W, 1] even though its outputs are NCHW.
net.setInput(y.reshape(1, y.shape[0], y.shape[1], 1))
y_hr = net.forward(node_name)[0, 0]
cr_hr = cv.resize(cr, None, fx=scale, fy=scale)
cb_hr = cv.resize(cb, None, fx=scale, fy=scale)
merged = cv.merge([y_hr, cr_hr, cb_hr])
# np.rint, not a plain cast: convertTo(CV_8U) rounds, and truncating here
# would drift from the C++ demo by a few levels after YCrCb -> BGR.
merged_8u = np.rint(merged * 255.0).clip(0, 255).astype(np.uint8)
return cv.cvtColor(merged_8u, cv.COLOR_YCrCb2BGR)
def main():
parser = argparse.ArgumentParser(description="LapSRN x4 super-resolution (ONNX) demo")
parser.add_argument("--model", default=os.path.join(here, "lapsrn_x4_2026sep.onnx"))
parser.add_argument("--image", default=os.path.join(here, "example_outputs", "input_image.png"))
parser.add_argument("--output-dir", default=os.path.join(here, "example_outputs"))
parser.add_argument("--scale", type=int, choices=[2, 4], help="only run this scale (default: both)")
args = parser.parse_args()
img = cv.imread(args.image)
if img is None:
raise SystemExit("could not read image: %s" % args.image)
net = cv.dnn.readNetFromONNX(args.model)
wanted = [(n, s) for n, s in OUTPUTS if args.scale in (None, s)]
print("lapsrn_x4 input %dx%d" % (img.shape[1], img.shape[0]))
for node_name, scale in wanted:
out = upsample(net, img, node_name, scale)
path = os.path.join(args.output_dir, "output_image_%dx.png" % scale)
cv.imwrite(path, out)
print(" %-16s x%d -> %dx%d %s" % (node_name, scale, out.shape[1], out.shape[0], path))
if __name__ == "__main__":
main()