1 ver1

mail@pastecode.io avatar
unknown
python
2 years ago
2.9 kB
0
Indexable
Never
from pickletools import uint8
import numpy as np
import cv2
import math

from sqlalchemy import false


def show(image):
    cv2.imshow('image',image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def get_gs(window_size, sigma_s):
    '''return gs, size: (window_size, window_size)'''
    p = int(window_size/2)
    gs = np.zeros((window_size, window_size))
    for i in range(window_size):
        for j in range(i, window_size):
            result = np.exp( -((i-p)**2 + (j-p)**2) * 0.5 / (sigma_s**2) )
            gs[i][j] = result
            gs[j][i] = result
    return gs

def get_gr_value(p, q, gr_dict):
    p_red, p_green, p_blue = p[0], p[1], p[2]
    q_red, q_green, q_blue = q[0], q[1], q[2]
    gr = gr_dict[abs(p_red - q_red)] * gr_dict[abs(p_green -  q_green)] * gr_dict[abs(p_blue-q_blue)]
    return gr



class Joint_bilateral_filter(object):
    def __init__(self, sigma_s, sigma_r):
        self.sigma_r = sigma_r
        self.sigma_s = sigma_s
        self.wndw_size = 6*sigma_s+1 # ws
        self.pad_w = 3*sigma_s # r
    
    def joint_bilateral_filter(self, img, guidance):
        BORDER_TYPE = cv2.BORDER_REFLECT
        padded_img = cv2.copyMakeBorder(img, self.pad_w, self.pad_w, self.pad_w, self.pad_w, BORDER_TYPE).astype(np.int32)
        padded_guidance = cv2.copyMakeBorder(guidance, self.pad_w, self.pad_w, self.pad_w, self.pad_w, BORDER_TYPE).astype(np.int32)
        window_size = self.wndw_size
        
        
        ### TODO ###
        # save Gs kernel dict
        print("window size: ", window_size)
        print("padded image size: ", padded_img.shape)
        print("padded guidance size: ", padded_guidance.shape)
        gs = get_gs(window_size, self.sigma_s)
        print("gs shape:", gs.shape)
        print("=============")
        print("gr")
        gr_dict = [np.exp(-(x * 0.5 / ((self.sigma_r**2)* (255**2)))) for x in range(256)]
        
        
        output = np.zeros(img.shape)
        
        shift = 0
        print("output shape",img.shape)
        assert(False)
        i, j = 0, 0
        shift_x, shift_y = 0, 0
        
        # for a window
        
        for i in range(window_size): 
           for j in range(window_size):
               print(i, j)
               print(i+shift_x, j+shift_y)
               gr_value = get_gr_value(padded_guidance[i+shift_x][j+shift_y], padded_guidance[int(window_size/2)+shift_x][int(window_size/2)+shift_y], gr_dict)
               denominator = gs[i+shift_x][j+shift_y] * gr_value
               numerator = denominator * padded_guidance[i+shift_x][j+shift_y]
               output[shift_x][shift_y] = numerator/denominator
               print(output[shift_x][shift_y])


                
        print("=============")
        print(output)
        return np.clip(output, 0, 255).astype(np.uint8)