Resize, blur & sharpen
Resizing changes the scale at which every other pixel operation acts. blur(sigma: 6) means “6 pixels of blur”, and 6 pixels on a 1600-pixel image is a small fraction of what 6 pixels is on a 640-pixel image.
let image = try Hokusai(url: URL(fileURLWithPath: "scene.png"))let focus = (x: 360, y: 40, width: 220, height: 220) // the lighthouse, after resizing to 640 px
// A: blur the full-size image, then shrink it. B: shrink, then blur at the final size.let blurThenResize = try image.blur(sigma: 6).resize(width: 640)let resizeThenBlur = try image.resize(width: 640).blur(sigma: 6)
for (name, pipeline) in [("blur-then-resize", blurThenResize), ("resize-then-blur", resizeThenBlur)] { try await pipeline.extract(x: focus.x, y: focus.y, width: focus.width, height: focus.height) .png().write(to: URL(fileURLWithPath: "\(name).png"))}// Blurring at 1600 px with sigma 6 is a much smaller blur once scaled to 640 px.print("mean difference:", try await meanDifference(blurThenResize, resizeThenBlur))
blur → resizePNG · 220 × 220 · 47 KB 
resize → blurPNG · 220 × 220 · 58 KB
The two pipelines differ on average by 2.28 grey levels per pixel (0 to 255). Blurring at 1600 px with sigma: 6 and then shrinking leaves an image that is only slightly soft; shrinking and then blurring with the same sigma blurs much more, because 6 pixels is now a larger part of the picture. Choose the order for the effect you want, but for a result that looks the same at every output size, resize first and compute sigma for the final size. Blurring before a large reduction is also wasted work, since the reduction averages the pixels anyway.
Sharpen
Section titled “Sharpen”Shrinking softens an image, and sharpening before the reduction is mostly averaged away:
let image = try Hokusai(url: URL(fileURLWithPath: "scene.png"))let focus = (x: 360, y: 40, width: 220, height: 220)
let sharpenThenResize = try image.sharpen(sigma: 1.5).resize(width: 640)let resizeThenSharpen = try image.resize(width: 640).sharpen(sigma: 1.5)let plain = try image.resize(width: 640)
for (name, pipeline) in [("plain", plain), ("sharpen-then-resize", sharpenThenResize), ("resize-then-sharpen", resizeThenSharpen)] { try await pipeline.extract(x: focus.x, y: focus.y, width: focus.width, height: focus.height) .png().write(to: URL(fileURLWithPath: "\(name).png"))}print("sharpen-then-resize vs plain:", try await meanDifference(sharpenThenResize, plain))print("resize-then-sharpen vs plain:", try await meanDifference(resizeThenSharpen, plain))
resize onlyPNG · 220 × 220 · 40 KB 
sharpen → resizePNG · 220 × 220 · 41 KB 
resize → sharpenPNG · 220 × 220 · 41 KB
Measured against the plain resize, the average change per pixel is 0.17 for sharpen → resize and 0.51 for resize → sharpen, three times as much. Sharpen after resizing, with a sigma chosen for the output size.