Repository navigation
AI denoiser #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
AI denoiser #95
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
aedcbdc
AI denoiser
meesoft a142333
Fix warnings
meesoft ecae936
Tiling
meesoft 5fab915
Upgrade OnnxRuntime
meesoft 889dd73
Use single file onnx
meesoft a5c105a
Multiple patches per epoch
meesoft d32223c
Save validation image with checkpoints
meesoft 5ce71c6
Allow resuming training
meesoft 3cfae00
Support grayscale images
meesoft 778d5df
Ramp interpolation between tiles
meesoft 07df59f
Denoising in local contrasl dialog
meesoft e504eb5
Fix test
meesoft 47bad45
Fix interpolation
meesoft 22d30bf
Stabilize test
meesoft 67c559e
Overwrite params after resume
meesoft 2160b70
Convert format if necessary
meesoft b5a2edd
Move AI folder
meesoft 3f97d60
Review fixes
meesoft 3559f40
Include denoise in Reset
meesoft 4e534ac
Add ResidualBlock layer
meesoft b80a316
Log denoising time
meesoft f061c51
Increase overlap
meesoft dda31ca
Optimize tile size
meesoft c6b38db
Merge branch 'main' into features/AiDenoiser
meesoft 76091d8
Optimize tile processing
meesoft a7768bf
U-net training script
meesoft f7d53c9
Update operation name
meesoft 5e27f82
Fix grayscale processing
meesoft 06b9f9c
Review fixes
meesoft 46080c8
Add test
meesoft 4632f30
Calc validation loss per epoch
meesoft 70c2c1f
Extract shared training code
meesoft 63e52e6
Fix RGB vs BGR in DnCNN denoiser
meesoft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| * Ask questions about the prompt to clarify any uncertainties. | ||
| * Ensure that new code compiles without warnings or errors. | ||
| * Prioritize making new code efficient and compact | ||
| * Prefer file scoped namespaces | ||
| * Prefer "is null" over "== null" for null checks. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| from pathlib import Path | ||
|
|
||
| import onnx | ||
| from onnx import TensorProto, helper, numpy_helper | ||
|
|
||
|
|
||
| def create_identity_model(output_path: Path): | ||
| input_tensor = helper.make_tensor_value_info("input", TensorProto.FLOAT, ["batch", "channels", "height", "width"]) | ||
| output_tensor = helper.make_tensor_value_info("output", TensorProto.FLOAT, ["batch", "channels", "height", "width"]) | ||
|
|
||
| identity_node = helper.make_node( | ||
| "Identity", | ||
| inputs=["input"], | ||
| outputs=["output"], | ||
| name="identity_test", | ||
| ) | ||
|
|
||
| graph = helper.make_graph( | ||
| [identity_node], | ||
| "minimal_denoise_test_graph", | ||
| [input_tensor], | ||
| [output_tensor], | ||
| ) | ||
|
|
||
| model = helper.make_model(graph, producer_name="PhotoLocatorTest") | ||
| model.opset_import[0].version = 17 | ||
|
meesoft marked this conversation as resolved.
Resolved
|
||
| model.ir_version = 13 | ||
|
|
||
| output_path.parent.mkdir(parents=True, exist_ok=True) | ||
| onnx.save(model, str(output_path)) | ||
| print(f"Saved minimal ONNX smoke-test model to {output_path}") | ||
|
|
||
|
|
||
| def main(): | ||
| repo_root = Path(__file__).resolve().parents[1] | ||
| output_path = repo_root / "PhotoLocatorTest" / "TestData" / "dncnn_test.onnx" | ||
| create_identity_model(output_path) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import argparse | ||
| from pathlib import Path | ||
|
|
||
| import cv2 | ||
| import torch | ||
|
|
||
| from denoising_common import checkpoint_model_state, denoise_image | ||
| from train_dncnn import DnCNN | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description="Denoise an image using a trained PyTorch DnCNN checkpoint.") | ||
| parser.add_argument("--model", type=str, required=True, help="Path to the trained PyTorch checkpoint (.pt)") | ||
| parser.add_argument("--input", type=str, required=True, help="Path to the image to denoise") | ||
| parser.add_argument("--output", type=str, required=True, help="Path for the denoised image") | ||
| parser.add_argument("--channels", type=int, default=3, choices=[1, 3], help="Model input channels") | ||
| parser.add_argument("--tile-size", type=int, default=512, help="Maximum tile width and height") | ||
| parser.add_argument("--overlap", type=int, default=64, help="Overlap between adjacent inference tiles") | ||
| parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu", help="Inference device, e.g. cpu or cuda") | ||
| args = parser.parse_args() | ||
|
|
||
| image = cv2.imread(args.input, cv2.IMREAD_UNCHANGED) | ||
| if image is None: | ||
| raise FileNotFoundError(f"Unable to read input image: {args.input}") | ||
| if args.channels == 3 and image.ndim == 3: | ||
| if image.shape[2] == 4: | ||
| image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGB) | ||
| else: | ||
| image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | ||
|
|
||
| model = DnCNN(channels=args.channels).to(args.device) | ||
| checkpoint = torch.load(args.model, map_location=args.device) | ||
| model.load_state_dict(checkpoint_model_state(checkpoint)) | ||
| print(f"Inference device: {args.device}") | ||
| result = denoise_image(model, image, args.channels, args.device, args.tile_size, args.overlap) | ||
| if args.channels == 3: | ||
| result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR) | ||
| if result.shape[2] == 1: | ||
| result = result[:, :, 0] | ||
|
|
||
| output_path = Path(args.output) | ||
| output_path.parent.mkdir(parents=True, exist_ok=True) | ||
| if not cv2.imwrite(str(output_path), result): | ||
| raise OSError(f"Unable to save denoised image: {output_path}") | ||
| print(f"Saved denoised image to {output_path}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| from pathlib import Path | ||
|
|
||
| import cv2 | ||
| import numpy as np | ||
| import torch | ||
| from torch.utils.data import Dataset | ||
|
|
||
| MONITOR_GAMMA = 1 | ||
|
|
||
|
|
||
| class PairedImageDataset(Dataset): | ||
| def __init__(self, image_dir: str, clean_postfix: str, patch_size: int, channels, patches_per_image, use_augment: bool = True): | ||
| self.image_dir = Path(image_dir) | ||
| self.clean_postfix = clean_postfix | ||
| self.patch_size = patch_size | ||
| self.channels = channels | ||
| self.patches_per_image = max(1, patches_per_image) | ||
| self.use_augment = use_augment | ||
|
|
||
| image_files = sorted(self.image_dir.glob("*")) | ||
| noisy_map = {} | ||
| clean_map = {} | ||
|
|
||
| for path in image_files: | ||
| if not path.is_file(): | ||
| continue | ||
| if path.name.endswith(f"{self.clean_postfix}{path.suffix}"): | ||
| base_name = path.stem.removesuffix(self.clean_postfix) | ||
| clean_map[base_name] = path | ||
| else: | ||
| noisy_map[path.stem] = path | ||
|
meesoft marked this conversation as resolved.
Resolved
|
||
|
|
||
| unmatched_noisy_names = sorted(set(noisy_map) - set(clean_map)) | ||
| for name in unmatched_noisy_names: | ||
| print(f"No matching clean image for noisy file: {noisy_map[name].name}") | ||
|
|
||
| common_names = sorted(set(noisy_map).intersection(clean_map)) | ||
| if not common_names: | ||
| raise FileNotFoundError( | ||
| f"No matching noisy/clean image pairs found in {image_dir} using clean postfix '{self.clean_postfix}'." | ||
| ) | ||
|
|
||
| self.samples = [(noisy_map[name], clean_map[name]) for name in common_names] | ||
|
|
||
| def __len__(self): | ||
| return len(self.samples) * self.patches_per_image | ||
|
|
||
| def _load_image(self, path: Path): | ||
| encoded = path.read_bytes() | ||
| image = cv2.imdecode(np.frombuffer(encoded, dtype=np.uint8), cv2.IMREAD_UNCHANGED) | ||
| if image is None: | ||
| raise FileNotFoundError(f"Unable to read image: {path}") | ||
|
|
||
| if image.ndim == 2: | ||
| image = image[:, :, None] | ||
| image = image.astype(np.float32) / _image_max_value(image) | ||
| image = np.power(image, MONITOR_GAMMA) | ||
|
|
||
| if image.shape[2] == 1 and self.channels == 3: | ||
| image = np.repeat(image, 3, axis=2) | ||
| elif image.shape[2] == 3 and self.channels == 1: | ||
| image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)[:, :, None] | ||
|
|
||
| if image.shape[2] != self.channels: | ||
| raise ValueError(f"Unexpected channel count {image.shape[2]} for channel setting {self.channels}: {path}") | ||
|
meesoft marked this conversation as resolved.
Resolved
|
||
|
|
||
| return image | ||
|
|
||
| def __getitem__(self, index): | ||
| base_index = index // self.patches_per_image | ||
| noisy_path, clean_path = self.samples[base_index] | ||
| noisy = self._load_image(noisy_path) | ||
| clean = self._load_image(clean_path) | ||
|
|
||
| if noisy.shape[:2] != clean.shape[:2]: | ||
| raise ValueError(f"Noisy and clean dimensions do not match for {noisy_path.name}: {noisy.shape[:2]} vs {clean.shape[:2]}") | ||
|
|
||
| height, width = noisy.shape[:2] | ||
| if height < self.patch_size or width < self.patch_size: | ||
| raise ValueError(f"Image too small for patch size {self.patch_size}: {noisy_path}") | ||
|
|
||
| if self.use_augment: | ||
| top = np.random.randint(0, height - self.patch_size + 1) | ||
| left = np.random.randint(0, width - self.patch_size + 1) | ||
| noisy = noisy[top:top + self.patch_size, left:left + self.patch_size] | ||
| clean = clean[top:top + self.patch_size, left:left + self.patch_size] | ||
|
|
||
| if np.random.rand() > 0.5: | ||
| noisy = noisy[:, ::-1, :].copy() | ||
| clean = clean[:, ::-1, :].copy() | ||
|
|
||
| if np.random.rand() > 0.5: | ||
| noisy = noisy[::-1, :, :].copy() | ||
| clean = clean[::-1, :, :].copy() | ||
| else: | ||
| noisy = noisy[0:self.patch_size, 0:self.patch_size] | ||
| clean = clean[0:self.patch_size, 0:self.patch_size] | ||
|
|
||
| noisy = noisy.transpose(2, 0, 1).copy() | ||
| clean = clean.transpose(2, 0, 1).copy() | ||
| return torch.from_numpy(noisy), torch.from_numpy(clean) | ||
|
|
||
|
|
||
| class RGBPairedImageDataset(PairedImageDataset): | ||
| def _load_image(self, path: Path): | ||
| image = super()._load_image(path) | ||
| if self.channels == 3: | ||
| image = image[:, :, ::-1].copy() | ||
| return image | ||
|
|
||
|
|
||
| def checkpoint_model_state(checkpoint): | ||
| if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint: | ||
| return checkpoint["model_state_dict"] | ||
| return checkpoint | ||
|
|
||
|
|
||
| def _image_max_value(image: np.ndarray): | ||
| if image.dtype not in (np.uint8, np.uint16): | ||
| raise ValueError(f"Unsupported image dtype {image.dtype}; expected 8-bit or 16-bit unsigned pixels.") | ||
| return np.iinfo(image.dtype).max | ||
|
|
||
|
|
||
| def _tile_starts(length: int, tile_size: int, overlap: int): | ||
| if length <= tile_size: | ||
| return [0] | ||
| step = tile_size - overlap | ||
| starts = list(range(0, length - tile_size + 1, step)) | ||
| if starts[-1] != length - tile_size: | ||
| starts.append(length - tile_size) | ||
| return starts | ||
|
|
||
|
|
||
| def denoise_image(model, image: np.ndarray, channels: int, device: str, tile_size: int = 512, overlap: int = 64): | ||
| if tile_size <= 0 or overlap < 0 or overlap >= tile_size: | ||
| raise ValueError("Tile size must be positive and overlap must be between 0 and tile size.") | ||
| edge_margin = min(getattr(model, "tile_edge_margin", getattr(model, "num_layers", 0)), tile_size // 2) | ||
| if overlap < 2 * edge_margin and image.ndim >= 2 and max(image.shape[:2]) > tile_size: | ||
| raise ValueError(f"Tile overlap must be at least {2 * edge_margin} pixels for this model.") | ||
|
|
||
| if image.ndim == 2: | ||
| image = image[:, :, None] | ||
| output_dtype = image.dtype | ||
| image_max_value = _image_max_value(image) | ||
| if image.shape[2] == 4: | ||
| image = image[:, :, :3] | ||
|
meesoft marked this conversation as resolved.
Resolved
|
||
| image = image.astype(np.float32) / image_max_value | ||
| image = np.power(image, MONITOR_GAMMA) | ||
| if image.shape[2] == 1 and channels == 3: | ||
| image = np.repeat(image, 3, axis=2) | ||
| elif image.shape[2] == 3 and channels == 1: | ||
| image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)[:, :, None] | ||
| if image.shape[2] != channels: | ||
| raise ValueError(f"Expected {channels} image channels, got {image.shape[2]}.") | ||
|
|
||
| height, width = image.shape[:2] | ||
| output = np.zeros((height, width, channels), dtype=np.float32) | ||
| weights = np.zeros((height, width, 1), dtype=np.float32) | ||
| was_training = model.training | ||
| model.eval() | ||
| try: | ||
| with torch.inference_mode(): | ||
| for top in _tile_starts(height, tile_size, overlap): | ||
| for left in _tile_starts(width, tile_size, overlap): | ||
| bottom = min(top + tile_size, height) | ||
| right = min(left + tile_size, width) | ||
| tile = image[top:bottom, left:right].transpose(2, 0, 1).copy() | ||
| tensor = torch.from_numpy(tile).unsqueeze(0).to(device) | ||
| denoised = model(tensor).squeeze(0).cpu().numpy().transpose(1, 2, 0) | ||
|
meesoft marked this conversation as resolved.
Resolved
|
||
| tile_height, tile_width = denoised.shape[:2] | ||
| tile_weights = np.ones((tile_height, tile_width), dtype=np.float32) | ||
| if edge_margin: | ||
| ramp = np.linspace(1.0 / (edge_margin + 1), 1.0, edge_margin, dtype=np.float32) | ||
| if top > 0: | ||
| tile_weights[:edge_margin, :] *= ramp[:, None] | ||
| if bottom < height: | ||
| tile_weights[-edge_margin:, :] *= ramp[::-1, None] | ||
| if left > 0: | ||
| tile_weights[:, :edge_margin] *= ramp[None, :] | ||
| if right < width: | ||
| tile_weights[:, -edge_margin:] *= ramp[None, ::-1] | ||
| output[top:bottom, left:right] += denoised * tile_weights[:, :, None] | ||
|
meesoft marked this conversation as resolved.
Resolved
|
||
| weights[top:bottom, left:right] += tile_weights[:, :, None] | ||
| finally: | ||
| model.train(was_training) | ||
|
|
||
| output = np.power(np.clip(output / weights, 0.0, 1.0), 1.0 / MONITOR_GAMMA) | ||
| return np.rint(output * image_max_value).astype(output_dtype) | ||
|
|
||
|
|
||
| def validate_dataset(image_dir: str, clean_postfix: str): | ||
| image_path = Path(image_dir) | ||
| if not image_path.exists() or not image_path.is_dir(): | ||
| raise FileNotFoundError(f"Training dataset directory must exist: {image_dir}") | ||
|
|
||
| files = sorted(image_path.glob("*")) | ||
| if not any(path.is_file() for path in files): | ||
| raise FileNotFoundError(f"Training dataset directory is empty: {image_dir}") | ||
|
|
||
| matching_files = [path for path in files if path.is_file() and path.name.endswith(f"{clean_postfix}{path.suffix}")] | ||
| if not matching_files: | ||
| raise FileNotFoundError(f"No clean images with postfix '{clean_postfix}' were found in {image_dir}") | ||
|
|
||
|
|
||
| def calculate_validation_loss(model, noisy_image: np.ndarray, clean_image: np.ndarray, channels: int, device: str, tile_size: int, tile_overlap: int): | ||
| prediction = denoise_image(model, noisy_image, channels, device, tile_size, tile_overlap) | ||
| prediction = prediction.astype(np.float32) / _image_max_value(prediction) | ||
| prediction = np.power(prediction, MONITOR_GAMMA) | ||
| if prediction.ndim == 2: | ||
| prediction = prediction[:, :, None] | ||
| if prediction.shape != clean_image.shape: | ||
| raise ValueError(f"Validation prediction and target shapes differ: {prediction.shape} vs {clean_image.shape}") | ||
| return float(np.mean(np.square(prediction - clean_image), dtype=np.float64)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import argparse | ||
| import os | ||
|
|
||
| import onnx | ||
| import torch | ||
|
|
||
| from denoising_common import checkpoint_model_state | ||
| from train_dncnn import DnCNN | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description="Export a trained DnCNN denoiser to a single-file embedded ONNX model.") | ||
| parser.add_argument("--model", type=str, default="dncnn_model.pt", help="Path to the saved PyTorch weights (.pt)") | ||
| parser.add_argument("--output", type=str, default="dncnn_model.onnx", help="Path for the ONNX model") | ||
| parser.add_argument("--channels", type=int, default=3, choices=[1, 3], help="Input image channels") | ||
| parser.add_argument("--height", type=int, default=256, help="Example input height") | ||
| parser.add_argument("--width", type=int, default=256, help="Example input width") | ||
| parser.add_argument("--opset", type=int, default=17, help="ONNX opset version") | ||
| args = parser.parse_args() | ||
|
|
||
| model = DnCNN(channels=args.channels) | ||
| checkpoint = torch.load(args.model, map_location="cpu") | ||
| model.load_state_dict(checkpoint_model_state(checkpoint)) | ||
| model.eval() | ||
|
|
||
| dummy_input = torch.randn(1, args.channels, args.height, args.width) | ||
| temp_path = args.output + ".tmp" | ||
| torch.onnx.export( | ||
| model, | ||
| (dummy_input,), | ||
| temp_path, | ||
| export_params=True, | ||
| opset_version=args.opset, | ||
| do_constant_folding=True, | ||
| input_names=["input"], | ||
| output_names=["output"], | ||
| dynamic_axes={ | ||
| "input": {0: "batch_size", 2: "height", 3: "width"}, | ||
| "output": {0: "batch_size", 2: "height", 3: "width"}, | ||
| }, | ||
| ) | ||
|
|
||
| model_onnx = onnx.load(temp_path) | ||
| onnx.save_model( | ||
| model_onnx, | ||
| args.output, | ||
| save_as_external_data=False, | ||
| all_tensors_to_one_file=True, | ||
| ) | ||
|
|
||
| os.remove(temp_path) | ||
| if os.path.exists(temp_path + ".data"): | ||
| os.remove(temp_path + ".data") | ||
|
|
||
| print(f"Exported ONNX model to {args.output}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.