Spaces:
david960156
/
Build error

david960156's picture hankwuii's picture
add ordered dithering function (#2)
9252de9 verified
Raw History Blame Contribute Delete
10 kB
import gradio as gr
import cv2
import numpy as np
import math
from skimage import segmentation, color
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms
from PIL import Image
from scipy.ndimage import convolve
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def edge_detection(image, threshold1, threshold2):
if len(image.shape) == 3:
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
else:
gray = image
edges = cv2.Canny(gray, threshold1, threshold2)
return cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
def image_segmentation(image, num_segments):
if image.shape[2] == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
segments = segmentation.felzenszwalb(image, scale=100, sigma=0.5, min_size=50)
labeled = color.label2rgb(segments, image, kind='avg')
return (labeled * 255).astype(np.uint8)
def image_inpainting(image, mask):
mask = (mask > 128).astype(np.uint8) * 255
result = cv2.inpaint(image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
return result
def Ordered_Dithering(img, n):
def generate_bayer_matrix(n):
if n == 1:
return np.array([[0, 2], [3, 1]])
else:
smaller_matrix = generate_bayer_matrix(n - 1)
size = 2 ** n
new_matrix = np.zeros((size, size), dtype=int)
for i in range(2 ** (n - 1)):
for j in range(2 ** (n - 1)):
base_value = 4 * smaller_matrix[i, j]
new_matrix[i, j] = base_value
new_matrix[i, j + 2 ** (n - 1)] = base_value + 2
new_matrix[i + 2 ** (n - 1), j] = base_value + 3
new_matrix[i + 2 ** (n - 1), j + 2 ** (n - 1)] = base_value + 1
return new_matrix
bayer_matrix = generate_bayer_matrix(n)
def Ordered_Dithering(img, bayer_matrix):
# Ordered dithering process
if len(img.shape) == 3: # Convert to grayscale if the image is in RGB
img = np.mean(img, axis=-1).astype(np.uint8)
N = bayer_matrix.shape[0]
thresholds_matrix = np.zeros_like(bayer_matrix, int)
for i in range(N):
for j in range(N):
thresholds_matrix[i, j] = int((255 * (bayer_matrix[i, j] + 0.5)) / (N * N))
height, width = img.shape
H = thresholds_matrix.shape[0]
ordered_dithering_img = np.zeros_like(img)
for x in range(height):
for y in range(width):
threshold = thresholds_matrix[x % H, y % H]
ordered_dithering_img[x, y] = 255 if img[x, y] > threshold else 0
return ordered_dithering_img
ordered_dithering_img = Ordered_Dithering(img, bayer_matrix)
def Find_HPSNR(img, ordered_dithering_img):
if len(img.shape) == 3 and img.shape[2] == 3:
# grayscale conversion
img = np.mean(img, axis=2)
if img.shape != ordered_dithering_img.shape:
raise ValueError(f"Image shapes do not match: {img.shape} vs {ordered_dithering_img.shape}")
diff = img.astype(float) - ordered_dithering_img.astype(float)
kernel_range = range(-3 // 2 + 1, 3 // 2 + 1)
x, y = np.meshgrid(kernel_range, kernel_range)
kernel = np.exp(-(x ** 2 + y ** 2) / (2 * 1 ** 2))
kernel /= kernel.sum()
filtered_img = convolve(diff, kernel, mode='reflect')
mse = mse = np.mean(filtered_img ** 2)
if mse == 0:
return float("inf")
hpsnr_value = 10 * np.log10((255 ** 2) / mse)
return hpsnr_value
hpsnr_value = Find_HPSNR(img, ordered_dithering_img)
return ordered_dithering_img, f"{hpsnr_value:.2f}"
# Super Resolution related functions
'''class PositionalEncoding(nn.Module):
def __init__(self, num_frequencies=10):
super(PositionalEncoding, self).__init__()
self.num_frequencies = num_frequencies
def forward(self, coords):
encodings = [coords]
for i in range(self.num_frequencies):
encodings.append(torch.sin(2**i * np.pi * coords))
encodings.append(torch.cos(2**i * np.pi * coords))
return torch.cat(encodings, dim=-1)
class ImprovedSuperResNet(nn.Module):
def __init__(self, input_dim):
super(ImprovedSuperResNet, self).__init__()
self.positional_encoding = PositionalEncoding()
self.net = nn.Sequential(
nn.Linear(input_dim, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 3),
)
def forward(self, x):
x = self.positional_encoding(x)
return self.net(x)
def create_coord_map(h, w):
x = torch.linspace(-1, 1, w)
y = torch.linspace(-1, 1, h)
xx, yy = torch.meshgrid(x, y)
return torch.stack([xx, yy], dim=-1)
def load_image(image, size=(64, 64)):
if isinstance(image, np.ndarray):
img = Image.fromarray(image)
else:
img = Image.open(image).convert('RGB')
transform = transforms.Compose([
transforms.Resize(size),
transforms.ToTensor(),
])
return transform(img).unsqueeze(0).to(device)
def train_progressive(model, low_res_img, num_epochs=100, max_size=800):
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)
sizes = [64, 96, 128, 192, 256]
for current_size in sizes:
for epoch in range(num_epochs):
optimizer.zero_grad()
coords = create_coord_map(current_size, current_size).to(device)
pred = model(coords.view(-1, 2)).view(1, 3, current_size, current_size)
target = F.interpolate(low_res_img, size=(current_size, current_size), mode='bilinear', align_corners=False)
loss = criterion(pred, target)
loss.backward()
optimizer.step()
scheduler.step()
return model
def generate_high_res(model, size=(400, 400)):
with torch.no_grad():
coords = create_coord_map(size[0], size[1]).to(device)
high_res = model(coords.view(-1, 2)).view(1, 3, size[0], size[1])
high_res = high_res.clamp(0, 1)
high_res = high_res.cpu().squeeze().permute(1, 2, 0).numpy()
high_res = (high_res * 255).astype(np.uint8)
return high_res
def super_resolution(image):
low_res_img = load_image(image)
model = ImprovedSuperResNet(input_dim=42).to(device)
trained_model = train_progressive(model, low_res_img, num_epochs=50)
high_res_img = generate_high_res(trained_model)
return high_res_img'''
# Define example images
example_images = [
["test/lena.png", "test/lena_mask.png"],
["test/monk.png", "test/monk_mask.png"],
["test/1.png", "test/1_mask.png"],
["test/2.png", "test/2_mask.png"]
]
# Define Gradio interface with tabs
with gr.Blocks(title="Computer Vision Toolkit") as demo:
gr.Markdown("# Computer Vision Toolkit")
gr.Markdown("Perform various computer vision tasks on images.")
with gr.Tab("Edge Detection"):
with gr.Row():
with gr.Column():
ed_input = gr.Image(type="numpy", label="Input Image")
ed_threshold1 = gr.Slider(0, 255, value=100, step=1, label="Threshold 1")
ed_threshold2 = gr.Slider(0, 255, value=200, step=1, label="Threshold 2")
ed_button = gr.Button("Detect Edges")
with gr.Column():
ed_output = gr.Image(type="numpy", label="Output Image")
ed_button.click(edge_detection, inputs=[ed_input, ed_threshold1, ed_threshold2], outputs=ed_output)
with gr.Tab("Image Segmentation"):
with gr.Row():
with gr.Column():
seg_input = gr.Image(type="numpy", label="Input Image")
seg_num = gr.Slider(2, 20, value=5, step=1, label="Number of Segments")
seg_button = gr.Button("Segment Image")
with gr.Column():
seg_output = gr.Image(type="numpy", label="Output Image")
seg_button.click(image_segmentation, inputs=[seg_input, seg_num], outputs=seg_output)
with gr.Tab("Image Inpainting"):
with gr.Row():
with gr.Column():
inp_input = gr.Image(type="numpy", label="Input Image")
inp_mask = gr.Image(type="numpy", label="Inpainting Mask", image_mode="L")
inp_button = gr.Button("Inpaint Image")
with gr.Column():
inp_output = gr.Image(type="numpy", label="Output Image")
inp_button.click(image_inpainting, inputs=[inp_input, inp_mask], outputs=inp_output)
with gr.Tab("Ordered Dithering"):
with gr.Row():
with gr.Column():
dit_input = gr.Image(type="numpy", label="Input Image")
bayer_matrix = gr.Slider(1, 9, value=1, step=1, label="bayer_matrix_size")
apply_dithering_button = gr.Button("Apply Ordered Dithering")
with gr.Column():
dit_output = gr.Image(type="numpy", label="Output Image")
hpsnr_output = gr.Label(label="HPSNR Value")
apply_dithering_button.click(Ordered_Dithering, inputs=[dit_input, bayer_matrix], outputs=[dit_output, hpsnr_output])
'''with gr.Tab("Super Resolution"):
with gr.Row():
with gr.Column():
sr_input = gr.Image(type="numpy", label="Input Image")
sr_button = gr.Button("Enhance Resolution")
with gr.Column():
sr_output = gr.Image(type="numpy", label="Output Image")
sr_button.click(super_resolution, inputs=[sr_input], outputs=sr_output)'''
gr.Examples(example_images, inputs=[ed_input, inp_mask])
demo.launch()