Our Image Sharpening model enhances the clarity and detail of an input image by applying a specialized 2D filter through convolution.
Input Format: RGB image tensor of shape (3, 200, 200), with pixel values in the [0,1] range.
Output: Sharpened image preserving original dimensions.
The equivalent pytorch code for the operator is:
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
# Load image as numpy ndarray (ignore alpha channel if it exists)
np_img = plt.imread('my_img')[..., :3] # shape (200, 200, 3) : (H, W, C)
# Normalize pixel values
if np_img.dtype == np.uint8:
np_img = np_img / 255.0
# Convert to PyTorch tensor and arrange dimensions as (3, 200, 200) : (C, H, W)
pt = torch.tensor(np_img, dtype=torch.float64).permute(2, 0, 1)
# Resize image to expected input size
pt = torch.nn.functional.interpolate(pt.unsqueeze(0), size=(200, 200), mode='bilinear').squeeze(0)
# Define sharpening kernel
sharpen_kernel = torch.tensor([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=torch.float64)
# Apply convolution for each channel separately (3 for RGB)
res = F.conv2d(pt, sharpen_kernel.expand(3, 1, 3, 3), groups=3, padding=1)
# Clamp to range [0, 1]
res = torch.clamp(res, 0, 1)
# Display the original and sharpened images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(pt.permute(1, 2, 0))
plt.axis("off")
plt.subplot(1, 2, 2)
plt.title("Sharpened Image")
plt.imshow(res.permute(1, 2, 0))
plt.axis("off")
plt.tight_layout()
plt.show()
Achieving Full Privacy with LatticaAI
In order to convert this simple code to use homomorphic operations, all you need are the following few extra steps:
Install Lattica python package and obtain a JWT token
Generate encryption keys
Replace the actual convolution with our function that will:
preprocess the image and encrypt it
send the encrypted data to the cloud for computation
receive and decrypt the encrypted result using your private key
Everything else remains the same.
from lattica_query.auth import get_demo_token
from lattica_query.lattica_query_client import QueryClient
model_id = "imageEnhancement"
my_token = get_demo_token(model_id)
client = QueryClient(my_token)
context, secret_key, client_blocks, = client.generate_key()
# `pt` and `res` are torch.Tensor, same as in the plain example above
res = client.run_query(context, secret_key, pt, client_blocks)
# Display the original and sharpened images...
import { getDemoToken, LatticaQueryClient } from '@Lattica-ai/lattica-query-client';
const modelId = "imageEnhancement"
const token = await getDemoToken(modelId);
const client = new LatticaQueryClient(myToken);
await client.init();
const result = await client.runQuery(pt);
First our client package
See our for a detailed explanation of each step in this flow.
To use the image sharpening model use the imageEnhancement model ID