Spaces:
Build error
Build error
add ordered dithering function
#2
by hankwuii - opened
8 unmodified lines9101112131417 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667128 unmodified lines1961971981992002012022032042052062072082092108 unmodified linesimport torch.optim as optimimport torchvision.transforms as transformsfrom PIL import Imagedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")17 unmodified linesresult = cv2.inpaint(image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)return resultdef Ordered_Dithering(n, img):if n == 1:new_matrix = np.array([[0, 2], [3, 1]])else:smaller_matrix = generate_bayer_matrix(n - 1)size = 2 ** nnew_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_valuenew_matrix[i, j + 2 ** (n - 1)] = base_value + 2new_matrix[i + 2 ** (n - 1), j] = base_value + 3new_matrix[i + 2 ** (n - 1), j + 2 ** (n - 1)] = base_value + 1N = new_matrix.shape[0]thresholds_matrix = np.zeros_like(new_matrix, int)for i in range(N):for j in range(N):thresholds_matrix[i, j] = int((255 * (new_matrix[i, j] + 0.5)) / (N * N))height, width = img.shapeN = thresholds_matrix.shape[0]Ordered_Dithering_img = np.zeros_like(img)for i in range(height):for j in range(width):threshold = thresholds_matrix[i % N, j % N]Ordered_Dithering_img[i, j] = 255 if img[i, j] > threshold else 0return Ordered_Dithering_img# Super Resolution related functions'''class PositionalEncoding(nn.Module):128 unmodified linesinp_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():inp_input = gr.Image(type="numpy", label="Input Image")n_slider = gr.Slider(minimum=2, maximum=8, step=1, value=4, label="Bayer Matrix Size (n)")inp_button = gr.Button("Apply Ordered Dithering")with gr.Column():inp_output = gr.Image(type="numpy", label="Output Image")inp_button.click(Ordered_Dithering, inputs=[inp_input, n_slider], outputs=inp_output)'''with gr.Tab("Super Resolution"):with gr.Row():8 unmodified lines910111213141517 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107128 unmodified lines2362372382392402412422432442452462472482492502518 unmodified linesimport torch.optim as optimimport torchvision.transforms as transformsfrom PIL import Imagefrom scipy.ndimage import convolvedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")17 unmodified linesresult = cv2.inpaint(image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)return resultdef 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 ** nnew_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_valuenew_matrix[i, j + 2 ** (n - 1)] = base_value + 2new_matrix[i + 2 ** (n - 1), j] = base_value + 3new_matrix[i + 2 ** (n - 1), j + 2 ** (n - 1)] = base_value + 1return new_matrixbayer_matrix = generate_bayer_matrix(n)def Ordered_Dithering(img, bayer_matrix):# Ordered dithering processif len(img.shape) == 3: # Convert to grayscale if the image is in RGBimg = 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.shapeH = 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 0return ordered_dithering_imgordered_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 conversionimg = 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_valuehpsnr_value = Find_HPSNR(img, ordered_dithering_img)return ordered_dithering_img, f"{hpsnr_value:.2f}"# Super Resolution related functions'''class PositionalEncoding(nn.Module):128 unmodified linesinp_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():
app.py+77-36