sharpy 0.2.1

High-performance image sharpening library for Rust
Documentation
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# Sharpy

[![CI](https://github.com/maxenko/sharpy/actions/workflows/ci.yml/badge.svg)](https://github.com/maxenko/sharpy/actions/workflows/ci.yml)

High-performance image sharpening library and CLI tool for Rust.

> **Want to play with it first?** There's an [optional Windows GUI demo]#optional-gui-demo
> with live sliders for every parameter — the fastest way to see what
> sharpy can do.

## Quick Start

### Library Usage

```rust
use sharpy::Image;

// Load and sharpen an image
let image = Image::load("photo.jpg")?;
let sharpened = image.unsharp_mask(1.0, 1.0, 0)?;
sharpened.save("photo_sharp.jpg")?;
```

### CLI Usage

```bash
# Install the CLI tool
cargo install sharpy

# Sharpen an image
sharpy unsharp photo.jpg photo_sharp.jpg

# Use a preset
sharpy preset portrait.jpg portrait_enhanced.jpg -p portrait
```

## Features

- **Performance-focused** - Parallel processing with Rayon
- **Multiple algorithms** - Unsharp mask, high-pass, edge enhancement, clarity
- **Flexible API** - Builder pattern for complex workflows
- **Minimal dependencies** - Core functionality with carefully selected dependencies
- **CLI included** - Full-featured command-line tool
- **Optional GUI demo** - Windows desktop app with live slider preview (see [`sharpy-gui/`]sharpy-gui/)

## Installation

### As a Library

Add to your `Cargo.toml`:

```toml
[dependencies]
sharpy = "0.2"
```

### As a CLI Tool

```bash
cargo install sharpy
```

Or build from source:

```bash
git clone https://github.com/maxenko/sharpy
cd sharpy
cargo build --release
```

## Library Usage

### Basic Sharpening

```rust
use sharpy::{Image, EdgeMethod};

// Unsharp mask - the classic sharpening method
let image = Image::load("input.jpg")?;
let sharpened = image.unsharp_mask(
    1.0,  // radius
    1.0,  // amount
    0     // threshold
)?;

// High-pass sharpening
let sharpened = image.high_pass_sharpen(0.5)?;

// Edge enhancement
let sharpened = image.enhance_edges(1.0, EdgeMethod::Sobel)?;

// Clarity (local contrast enhancement)
let sharpened = image.clarity(1.0, 2.0)?;
```

### Using the Builder Pattern

```rust
use sharpy::{Image, EdgeMethod};

let result = Image::load("landscape.jpg")?
    .sharpen()
    .unsharp_mask(1.0, 1.2, 1)
    .edge_enhance(0.5, EdgeMethod::Sobel)
    .clarity(0.4, 3.0)
    .apply()?;

result.save("landscape_enhanced.jpg")?;
```

### Using Presets

```rust
use sharpy::{Image, SharpeningPresets};

// Built-in presets for common use cases
let image = Image::load("photo.jpg")?;

// Subtle sharpening
let result = SharpeningPresets::subtle(image).apply()?;

// Portrait enhancement (avoids over-sharpening skin)
let result = SharpeningPresets::portrait(image).apply()?;

// Landscape enhancement (enhanced detail)
let result = SharpeningPresets::landscape(image).apply()?;
```

### Advanced Examples

#### Custom Sharpening Pipeline

```rust
use sharpy::{Image, SharpeningBuilder, EdgeMethod};

fn custom_enhancement(image: Image) -> sharpy::Result<Image> {
    image.sharpen()
        // Start with subtle unsharp mask
        .unsharp_mask(0.8, 0.6, 2)
        // Add edge enhancement
        .edge_enhance(0.3, EdgeMethod::Sobel)
        // Finish with clarity for local contrast
        .clarity(0.5, 5.0)
        .apply()
}
```

#### Inspecting and Replaying Operations

Pipelines built with `SharpeningBuilder` can be inspected (e.g. for tests
that verify a preset still emits the expected stages) and individual
`Operation` values can be re-applied to any image:

```rust
use sharpy::{Image, Operation, SharpeningPresets};

let image = Image::load("photo.jpg")?;
let builder = SharpeningPresets::landscape(image.clone());

// Inspect what stages the builder will run, in execution order.
for op in builder.operations() {
    println!("will apply: {}", op.name());
}

// Apply a single Operation directly.
let unsharp = Operation::UnsharpMask { radius: 1.0, amount: 1.0, threshold: 0 };
let sharpened = unsharp.apply(image)?;
```

#### Processing Multiple Images

```rust
use sharpy::Image;
use rayon::prelude::*;
use std::path::Path;

fn batch_process(input_dir: &Path, output_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let images: Vec<_> = std::fs::read_dir(input_dir)?
        .filter_map(|entry| entry.ok())
        .filter(|entry| {
            entry.path().extension()
                .map(|ext| ext == "jpg" || ext == "png")
                .unwrap_or(false)
        })
        .collect();

    images.par_iter().try_for_each(|entry| -> Result<(), Box<dyn std::error::Error>> {
        let path = entry.path();
        let image = Image::load(&path)?;
        
        let enhanced = image.unsharp_mask(1.0, 1.0, 0)?;
        
        let output_path = output_dir.join(path.file_name().unwrap());
        enhanced.save(output_path)?;
        
        Ok(())
    })?;
    
    Ok(())
}
```

#### Working with Image Data

```rust
use sharpy::Image;
use image::{RgbImage, DynamicImage};

// From various image types (both return Result — see below)
let rgb_image = RgbImage::new(800, 600);
let image = Image::from_rgb(rgb_image)?;

let dynamic_image = DynamicImage::new_rgb8(800, 600);
let image = Image::from_dynamic(dynamic_image)?;

// Get dimensions and histogram
let (width, height) = image.dimensions();
let histogram = image.histogram(); // [u32; 256] luminance histogram

// Convert back to standard image types
let rgb: RgbImage = image.clone().into_rgb();
let dynamic: DynamicImage = image.into_dynamic();
```

## CLI Tool (sharpy)

### Basic Commands

```bash
# Unsharp mask with default settings
sharpy unsharp input.jpg output.jpg

# Specify parameters
sharpy unsharp input.jpg output.jpg -r 2.0 -a 1.5 -t 10

# High-pass sharpening
sharpy highpass input.jpg output.jpg -s 0.7

# Edge enhancement
sharpy edges input.jpg output.jpg -s 1.0 -m sobel

# Clarity enhancement
sharpy clarity input.jpg output.jpg -s 1.0 -r 3.0

# Use a preset
sharpy preset photo.jpg enhanced.jpg -p moderate
```

### Available Presets

- `subtle` - Light sharpening for general use
- `moderate` - Balanced sharpening with clarity
- `strong` - Heavy sharpening for soft images
- `edge-aware` - Emphasizes edges while preserving smooth areas
- `portrait` - Optimized for portraits (avoids over-sharpening skin)
- `landscape` - Enhanced detail extraction for landscapes

### Batch Processing

```bash
# Process all JPG files in current directory
sharpy batch "*.jpg" -o sharpened/

# Process with custom suffix
sharpy batch "photos/*.jpg" -o processed/ -s "_enhanced"

# Apply multiple operations
sharpy batch "*.png" -o output/ -p "unsharp:1.0:1.0:0,clarity:0.5:2.0"
```

### Advanced CLI Usage

#### Dry Run Mode

```bash
# Preview what would happen without processing
sharpy batch "*.jpg" -o processed/ --dry-run
```

#### Verbose Output

```bash
# See detailed processing information
sharpy unsharp photo.jpg sharp.jpg -v
```

#### Overwrite Protection

```bash
# Force overwrite existing files
sharpy unsharp input.jpg output.jpg --overwrite
```

#### Chaining Operations in Batch Mode

```bash
# Format: "operation:param1:param2:..."
sharpy batch "*.jpg" -o enhanced/ -p "unsharp:1.0:1.0:0,edges:0.5:sobel,clarity:0.3:2.0"
```

Operation formats:
- `unsharp:radius:amount:threshold`
- `highpass:strength`
- `edges:strength:method` (method: sobel or prewitt)
- `clarity:strength:radius`

### CLI Examples by Use Case

#### Portrait Photography

```bash
# Gentle sharpening for portraits
sharpy preset portrait.jpg portrait_final.jpg -p portrait

# Custom portrait enhancement
sharpy unsharp portrait.jpg enhanced.jpg -r 1.2 -a 0.7 -t 10
```

#### Landscape Photography

```bash
# Enhanced detail for landscapes
sharpy preset landscape.jpg landscape_final.jpg -p landscape

# Custom landscape workflow
sharpy batch "landscapes/*.jpg" -o final/ -p "unsharp:1.0:1.2:1,edges:0.5:sobel,clarity:0.4:3.0"
```

#### Web Images

```bash
# Batch process for web upload
sharpy batch "products/*.jpg" -o web/ -p "unsharp:0.8:0.8:2,clarity:0.3:2.0"
```

#### Scanned Documents

```bash
# Enhance text clarity
sharpy edges scan.png scan_enhanced.png -s 1.5 -m prewitt
```

## Optional GUI Demo

`sharpy-gui` is an optional Windows desktop app that lets you try every
sharpening parameter interactively. Drop an image onto the window, drag the
sliders, and watch the preview update in real time. Save when you're happy.

It's the easiest way to see what each algorithm does without writing any code.

**What you get:**

- Drag-drop or *Open…* to load any JPEG, PNG, BMP, TIFF, or WebP
- Live preview as you move sliders — runs on a downscaled copy for speed
- Six built-in presets in the toolbar dropdown (subtle, moderate, strong,
  edge-aware, portrait, landscape)
- Per-stage enable checkboxes and reset buttons
- *Save As…* runs the full-resolution pipeline on a worker thread, so the
  UI never freezes — even at the heaviest clarity settings

### Run it from a checkout

```bash
git clone https://github.com/maxenko/sharpy
cd sharpy

# Debug build (faster to compile, slower to run)
cargo run -p sharpy-gui

# Release build (recommended for actual use)
cargo run -p sharpy-gui --release
```

The GUI is a separate workspace member, so this won't touch the library
or CLI build. Plain `cargo build` and `cargo test` at the root stay
lib-only.

### Build a standalone `.exe` to share

```bash
cargo build -p sharpy-gui --release
# Binary: target/release/sharpy-gui.exe
```

The MSVC Rust toolchain links the C runtime statically, so the binary
is **portable** — copy the `.exe` to any Windows machine and double-click
to run. No installer, no Visual C++ Redistributable, no registry entries.

### First-launch walkthrough

1. **Drag an image** onto the window (or click *Open…*).
2. **Pick a preset** from the toolbar dropdown to see a quick result.
3. **Tweak individual sliders** in the right panel — radius, amount,
   threshold, etc. The preview updates as you drag.
4. **Save As…** to write the result to disk at full resolution. The
   status bar shows progress and elapsed time.

For known limitations, the architecture overview, and details on the
preset-order quirk for `edge-aware`, see
[`sharpy-gui/README.md`](sharpy-gui/README.md).

## Performance

Sharpy uses parallel processing for optimal performance:

- Separable convolution for Gaussian blur
- Parallel pixel processing with Rayon
- Efficient memory usage with copy-on-write
- Optimized memory operations

Benchmark results on typical hardware (1024x1024 image):
- Unsharp mask: ~45ms
- High-pass sharpen: ~25ms
- Edge enhancement: ~35ms
- Clarity: ~65ms

*Performance may vary based on hardware and image characteristics.

## Algorithm Details

### Unsharp Mask
Creates a blurred version of the image and subtracts it from the original to enhance edges.

Parameters:
- `radius`: Blur radius (0.5-10.0)
- `amount`: Strength multiplier (0.0-5.0)
- `threshold`: Minimum difference to sharpen (0-255)

### High-Pass Sharpen
Uses a 3x3 convolution kernel to enhance high-frequency details.

Parameters:
- `strength`: Blend with original (0.0-3.0)

### Edge Enhancement
Detects edges using Sobel or Prewitt operators and enhances them.

Parameters:
- `strength`: Enhancement amount (0.0-3.0)
- `method`: Edge detection algorithm (Sobel/Prewitt)

### Clarity
Enhances local contrast by comparing each pixel to its surrounding area.

Parameters:
- `strength`: Enhancement amount (0.0-3.0)
- `radius`: Local area size (1.0-20.0)

## Building from Source

This is a Cargo workspace. The root crate (`sharpy`, library + `sharpy`
CLI) is the default member, so most commands at the root only touch the
library — the optional `sharpy-gui` member is built explicitly with `-p`.

```bash
# Clone the repository
git clone https://github.com/maxenko/sharpy
cd sharpy

# Build library + CLI (does NOT pull in GUI deps)
cargo build --release

# Run tests (root crate only)
cargo test

# Run benchmarks
cargo bench

# Install CLI globally
cargo install --path .

# Build the optional GUI demo (Windows-only target)
cargo build -p sharpy-gui --release
```

## License

Licensed under the MIT License ([LICENSE](LICENSE)).

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Acknowledgments

- Built with [image]https://github.com/image-rs/image crate for image I/O
- Parallel processing with [rayon]https://github.com/rayon-rs/rayon
- CLI interface using [clap]https://github.com/clap-rs/clap