Download app.py from Muhammad-Ahmed/digital-image-processing-project: direct link, hf CLI and curl.
- Browser
- Download file 3.79 kB
-
https://huggingface.co/spaces/Muhammad-Ahmed/digital-image-processing-project/resolve/main/app.py
- Command line
-
hf download hf://spaces/Muhammad-Ahmed/digital-image-processing-project/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Muhammad-Ahmed/digital-image-processing-project/resolve/main/app.py
3.79 kB
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torchvision import transforms | |
| from PIL import Image | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| import os | |
| # ========================= | |
| # 1. DEVICE CONFIG | |
| # ========================= | |
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| MODEL_PATH = "sharp_edge_unet.pth" # Path to trained model | |
| # ========================= | |
| # 2. DEFINE SHARP UNET | |
| # ========================= | |
| class SharpUNet(nn.Module): | |
| def __init__(self): | |
| super(SharpUNet, self).__init__() | |
| self.enc1 = self.conv_block(3, 64) | |
| self.enc2 = self.conv_block(64, 128) | |
| self.enc3 = self.conv_block(128, 256) | |
| self.bottleneck = self.conv_block(256, 512) | |
| self.up1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) | |
| self.dec1 = self.conv_block(512 + 256, 256) | |
| self.up2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) | |
| self.dec2 = self.conv_block(256 + 128, 128) | |
| self.up3 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) | |
| self.dec3 = self.conv_block(128 + 64, 64) | |
| self.final = nn.Conv2d(64, 3, kernel_size=1) | |
| def conv_block(self, in_c, out_c): | |
| return nn.Sequential( | |
| nn.Conv2d(in_c, out_c, 3, padding=1), | |
| nn.BatchNorm2d(out_c), | |
| nn.ReLU(inplace=True), | |
| nn.Conv2d(out_c, out_c, 3, padding=1), | |
| nn.BatchNorm2d(out_c), | |
| nn.ReLU(inplace=True) | |
| ) | |
| def forward(self, x): | |
| e1 = self.enc1(x) | |
| e2 = self.enc2(F.max_pool2d(e1, 2)) | |
| e3 = self.enc3(F.max_pool2d(e2, 2)) | |
| b = self.bottleneck(F.max_pool2d(e3, 2)) | |
| d1 = self.up1(b) | |
| if d1.size() != e3.size(): d1 = F.interpolate(d1, size=e3.shape[2:]) | |
| d1 = torch.cat((d1, e3), dim=1) | |
| d1 = self.dec1(d1) | |
| d2 = self.up2(d1) | |
| if d2.size() != e2.size(): d2 = F.interpolate(d2, size=e2.shape[2:]) | |
| d2 = torch.cat((d2, e2), dim=1) | |
| d2 = self.dec2(d2) | |
| d3 = self.up3(d2) | |
| if d3.size() != e1.size(): d3 = F.interpolate(d3, size=e1.shape[2:]) | |
| d3 = torch.cat((d3, e1), dim=1) | |
| d3 = self.dec3(d3) | |
| return torch.sigmoid(self.final(d3)) | |
| # ========================= | |
| # 3. LOAD MODEL | |
| # ========================= | |
| model = SharpUNet().to(DEVICE) | |
| if not os.path.exists(MODEL_PATH): | |
| raise FileNotFoundError(f"Model not found at {MODEL_PATH}") | |
| model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE)) | |
| model.eval() | |
| print("Model loaded successfully.") | |
| # ========================= | |
| # 4. INFERENCE FUNCTION | |
| # ========================= | |
| transform = transforms.Compose([ | |
| transforms.Resize((256, 256)), | |
| transforms.ToTensor() | |
| ]) | |
| def infer_image(user_img): | |
| # Convert uploaded image to RGB PIL | |
| img = user_img.convert("RGB") | |
| # Preprocess | |
| img_tensor = transform(img).unsqueeze(0).to(DEVICE) | |
| with torch.no_grad(): | |
| pred = model(img_tensor) | |
| pred_np = pred.squeeze(0).cpu().permute(1, 2, 0).numpy() | |
| pred_clean = pred_np.copy() | |
| pred_clean[pred_clean < 0.1] = 0 # Remove weak pixels for sharp display | |
| # Resize original image to match output size | |
| img_resized = img.resize((256, 256)) | |
| return img_resized, Image.fromarray((pred_clean * 255).astype(np.uint8)) | |
| # ========================= | |
| # 5. GRADIO INTERFACE | |
| # ========================= | |
| iface = gr.Interface( | |
| fn=infer_image, | |
| inputs=gr.Image(type="pil"), | |
| outputs=["image", "image"], | |
| title="""Automated Pseudo-Color Edge Detection | |
| in Images Using U-Net""", | |
| description="Upload any RGB image and see the predicted pseudo-colored edges." | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |