diff --git a/src/filters.py b/src/filters.py index 2567186..fc1b849 100644 --- a/src/filters.py +++ b/src/filters.py @@ -10,16 +10,25 @@ import cv2 as cv # Parent class for all the filters class filter: + ''' + Parent class for all the filters + ''' def __init__(self, img): self.img = img - -class average(filter): + +class convolve(filter): + ''' Convolve using custom kernel, + if no kernel is given, use default 3x3 kernel for averaging''' def __init__(self, img): super().__init__(img) - def apply(self): - kernel = np.ones((3, 3), np.float32) / 9 + def apply(self, params): + # Set default values + ksize = int(params["ksize"]) if params["ksize"] else 3 + kernel = np.array(params["kernel"]) if params["kernel"] else np.ones((ksize, ksize), np.float32) / np.sqrt(ksize) + + #print("with params: " + " ksize: " + str(ksize) + " kernel: \n" + str(kernel)) self.img = cv.filter2D(self.img, -1, kernel) @@ -27,88 +36,111 @@ class blur(filter): def __init__(self, img): super().__init__(img) - def apply(self): - self.img = cv.blur(self.img, (3, 3)) + def apply(self, params): + # Set default values + if(params["anchor"]): + try: + anchor = tuple(map(int, params["anchor"].split(','))) + except AttributeError: + anchor = tuple(params["anchor"]) + else: + anchor = (-1, -1) + ksize = int(params["ksize"]) if params["ksize"] else 3 + + #print("with params: " + " ksize: " + str(ksize) + " anchor: " + str(anchor)) + self.img = cv.blur(self.img, ksize=(ksize, ksize), anchor=anchor) class gaussian(filter): def __init__(self, img): super().__init__(img) - def apply(self): - self.img = cv.GaussianBlur(self.img, (3, 3), 0) + def apply(self, params): + # Set default values + ksize = int(params["ksize"]) if params["ksize"] else 3 + sigmaX = float(params["sigmaX"]) if params["sigmaX"] else 0 + sigmaY = float(params["sigmaY"]) if params["sigmaY"] else 0 + + #print("with params: " + " ksize: " + str(ksize) + " sigmaX: " + str(sigmaX) + " sigmaY: " + str(sigmaY)) + self.img = cv.GaussianBlur(self.img, (ksize, ksize), sigmaX, sigmaY) class median(filter): def __init__(self, img): super().__init__(img) - def apply(self): - self.img = cv.medianBlur(self.img, 1) + def apply(self, params): + # Set default values + ksize = int(params["ksize"]) if params["ksize"] else 3 + + #print("with params: " + " ksize: " + str(ksize)) + self.img = cv.medianBlur(self.img, ksize) class bilateral(filter): def __init__(self, img): super().__init__(img) - def apply(self): - self.img = cv.bilateralFilter(self.img, 1, 75, 75) + def apply(self, params): + # Set default values + d = int(params["d"]) if params["d"] else 1 + sigmaColor = int(params["sigmaColor"]) if params["sigmaColor"] else 75 + sigmaSpace = int(params["sigmaSpace"]) if params["sigmaSpace"] else 75 + + #print("with params: " + " d: " + str(d) + " sigmaColor: " + str(sigmaColor) + " sigmaSpace: " + str(sigmaSpace)) + self.img = cv.bilateralFilter(self.img, d, sigmaColor, sigmaSpace) class denoise(filter): def __init__(self, img): super().__init__(img) - def apply(self): - pass - #does not work + def apply(self, params): + # Set default values + h = int(params["h"]) if params["h"] else 20 + tWS = int(params["templateWindowSize"]) if params["templateWindowSize"] else 7 + sWS = int(params["searchWindowSize"]) if params["searchWindowSize"] else 21 + + #print("with params: " + " h: " + str(h) + " tWS: " + str(tWS) + " sWS: " + str(sWS)) self.img = np.uint8(self.img) - self.img = cv.fastNlMeansDenoising( - self.img, h=10, searchWindowSize=21, templateWindowSize=7) + self.img = cv.fastNlMeansDenoising(self.img, h, tWS, sWS) class sharpen(filter): def __init__(self, img): super().__init__(img) - def apply(self): - kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) - self.img = cv.filter2D(self.img, ddepth=-1, kernel=kernel) - + def apply(self, params): + # Set default values + kernel = np.matrix(params["kernel"]) if params["kernel"] else np.array( + [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) -class erode(filter): - def __init__(self, img): - super().__init__(img) - - def apply(self): - kernel = np.ones((3, 3), np.uint8) - self.img = cv.erode(self.img, kernel, 1) - - -class dilate(filter): - def __init__(self, img): - super().__init__(img) - - def apply(self): - kernel = np.ones((3, 3), np.uint8) - self.img = cv.dilate(self.img, kernel, 1) - - -# Erosion, then dilatation -class opening(filter): - def __init__(self, img): - super().__init__(img) + #print("with params: " + " kernel: \n" + str(kernel)) + self.img = cv.filter2D(self.img, ddepth=-1, kernel=kernel) - def apply(self): - kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3)) - self.img = cv.morphologyEx(self.img, cv.MORPH_CLOSE, kernel) +class morph(filter): + ''' General morphological operations. -# Dilatation, then erosion -class closing(filter): + Can be used with MORPH_OPEN, MORPH_CLOSE, MORPH_DILATE, MORPH_ERODE as op. + ''' def __init__(self, img): super().__init__(img) - def apply(self): - kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3)) - self.img = cv.morphologyEx(self.img, cv.MORPH_OPEN, kernel) + def apply(self, params): + # Set default values + kernel = np.matrix(params["kernel"]) if params["kernel"] else np.ones((3, 3), np.uint8) + iterations = int(params["iterations"]) if params["iterations"] else 1 + op = getattr(cv, params["op"]) if params["op"] else cv.MORPH_OPEN + if(params["anchor"]): + try: + anchor = tuple(map(int, params["anchor"].split(','))) + except AttributeError: + anchor = tuple(params["anchor"]) + else: + anchor = (-1, -1) + + + #print("with params: " + " kernel: \n" + str(kernel) + " anchor: " + str(anchor) + " iterations: " + str(iterations) + " op: " + str(op)) + self.img = cv.morphologyEx( + self.img, op=op, kernel=kernel, anchor=anchor, iterations=iterations) diff --git a/src/main.py b/src/main.py index 2bd666a..4528b4f 100644 --- a/src/main.py +++ b/src/main.py @@ -23,29 +23,42 @@ class apply_filters: def __init__(self): # Parse arguments from command line self.parse_arguments() - self.input_file = self.args.input_file - self.output_file = self.args.output_file - self.dpi = self.args.dpi - self.filters = self.args.filters - self.mirror = self.args.mirror if self.args.mirror else 0 - + self.params = {} + self.filters = [] + # Parse configuration from json file if self.args.config: self.config_file = self.args.config[0] self.preset_name = self.args.config[1] self.config = json.load(open(self.config_file)) + print("Config loaded") self.parse_conf() # If no config file given, expect filters in command line else: - self.filters = self.args.filters + print("No config file given, using command line arguments") + i = 0 + for filter in self.args.filters: + if filter.find('=') == -1: + self.filters.append(filter) + i += 1 + self.params[i] = {} + else: + key, value = filter.split('=') + self.params[i][key] = value + self.parse_params(self.params[i]) + + self.input_file = self.args.input_file + self.output_file = self.args.output_file + self.dpi = self.args.dpi + self.mirror = self.args.mirror if self.args.mirror else 0 #read as numpy.array - self.img = plt.imread(self.input_file) + self.img = cv.imread(self.input_file, cv.IMREAD_GRAYSCALE) self.width = self.img.shape[1] self.height = self.img.shape[0] - print(self.width, self.height) + #print(self.width, self.height) fig = plt.figure(figsize = (self.width, self.height), frameon = False, dpi = self.dpi / 100) # dpi is in cm @@ -57,14 +70,38 @@ class apply_filters: if self.mirror: self.mirror_image() - # Apply all filters - self.apply_filter(fig, ax) + # Apply all filters and save image + self.apply_filter() + self.save_image(fig, ax) + + + def check_param(self, params, key): + try: + params[key] = params[key] + except KeyError: + params[key] = None + + + def parse_params(self, params): + possible_params = {"h", "searchWindowSize","templateWindowSize", + "ksize", "kernel", "sigmaX" , "sigmaY", + "sigmaColor", "sigmaSpace", "d", "anchor", "iterations", "op"} + for key in possible_params: + self.check_param(params, key) def parse_conf(self): # Parse configuration file if given. try: - self.filters = self.config[self.preset_name] + filter_array = self.config[self.preset_name] + for i, filter in enumerate(range(len(filter_array)), start=1): + self.filters.append(filter_array[filter]["name"]) + self.params[i] = {} + for attribute, value in filter_array[filter].items(): + if attribute != "name": + self.params[i][attribute] = value + self.parse_params(self.params[i]) + except(KeyError): print("Preset not found", file = sys.stderr) @@ -72,25 +109,27 @@ class apply_filters: def parse_arguments(self): # Parse arguments - parser = ap.ArgumentParser(prog = 'main.py', description = - 'Program for processing a 2D image into 3D fingerprint.') + parser = ap.ArgumentParser(prog = 'main.py', + description = 'Program for processing a 2D image into 3D fingerprint.', + usage='%(prog)s [-h] [-m | --mirror | --no-mirror] input_file output_file dpi ([-c config_file preset | --config config_file preset] | [filters ...])') # positional arguments - parser.add_argument("input_file", type = str, help = "Location with input file") - parser.add_argument("output_file", type = str, help = "Output file location") - parser.add_argument("dpi", type = int, help = "Scanner dpi") + parser.add_argument("input_file", type = str, help = "location with input file") + parser.add_argument("output_file", type = str, help = "output file location") + parser.add_argument("dpi", type = int, help = "scanner dpi") # boolean switch - parser.add_argument('-m', "--mirror", help = "Mirror input image", + parser.add_argument('-m', "--mirror", help = "mirror input image", type = bool, action = ap.BooleanOptionalAction) # file with configuration containing presets, new preset name # pair argument - give both or none - parser.add_argument('--config', nargs=2, metavar=('config_file', 'preset'), - help='Config file with presets, name of the preset') + parser.add_argument('-c','--config', nargs = 2, metavar = ('config_file', 'preset'), + help = 'pair: name of the config file with presets, name of the preset') # array of unknown length, all filter names saved inside - parser.add_argument('filters', type = str, nargs = '*', help = "List of filter names") + parser.add_argument('filters', type = str, nargs = '*', + help="list of filter names and their parameters in form [filter_name1 param1=value1 param2=value2 filter_name2 param1=value1...]") self.args = parser.parse_args() @@ -104,10 +143,7 @@ class apply_filters: def resize_image(self): - # open image as python image object print("Resize image", file = sys.stderr) - - self.convert_dpi() self.img = self.img.resize((np.array(self.width, self.height)).astype(int)) @@ -119,17 +155,17 @@ class apply_filters: self.img = cv.flip(self.img, 1) # 1 for vertical mirror - def apply_filter(self, fig, ax): + def apply_filter(self): if len(self.filters) == 0: # No filter given, just save the image pass else: - for filter_name in self.filters: + # Apply all filters + for i, filter_name in enumerate(self.filters): filter = self.filter_factory(filter_name) - filter.apply(self) - self.save_image(fig, ax) - + filter.apply(self, self.params[i+1]) + def print_size(self, size): print("Width: " + str(size[0]), file = sys.stderr) @@ -139,7 +175,7 @@ class apply_filters: def save_image(self, fig, ax): # Save processed image. print("Saving image", file = sys.stderr) - ax.imshow(self.img) + ax.imshow(self.img, cmap="gray") fig.savefig(fname=self.output_file)