def apply_C_filter(image, dll, c_function, filter_size, mode='constant', cval=0): """ Apply a C function based filter on image Parameters ---------- image : 2D array Input image. dll: str or a ctypes dll object If str: A dll name (including full path if not on the default search path). c_function: str or int If str: The name of the variable in the dll pointing to the function. If int: A Function pointer. filter_size : (2,) array Filter shape. mode : str Padding mode. cval : a scalar Padding fill value (applicable is mode == 'const') Returns ------- output : array A 2D array of the same dtype and shape as the input array. """ # A temporary confinment to float32 image = convert(image, np.float32) if type(dll) is str: dll = ctypes.cdll.LoadLibrary(dll) if type(c_function) is str: # pfcn = ctypes.c_voidp.in_dll(dll, c_function).value pfcn = ctypes.cast(getattr(dll, c_function), ctypes.c_void_p).value #pfcn = getattr(dll, c_function) else: pfcn = c_function #pfcn = ctypes.cast(pfcn, ctypes.pointer) # Prepare paded data padded = fiter.gen_filter_matrix(image, filter_size, mode=mode, cval=cval) output = np.empty_like(image) padded.filter_with_C_callback_float(pfcn, output) return output
import gen_filter import _filter_iter as fiter def py_rand_select(buffer): buf = buffer.ravel() return buf[np.random.randint(len(buf))] x = np.linspace(-3,3,51).astype(np.float32) z = np.exp(-(x**2+x[:,None]**2)) z[::2, ::2] = 0.0 C_filtered = gen_filter.apply_C_filter(z, './example_C_filters.so', 'rand_select_addr', (3,3)) prepare = fiter.gen_filter_matrix(z, (3,3)) Py_filtered = prepare.filter_with_py_callback(py_rand_select) fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(9, 4)) ax1.imshow(z, interpolation='nearest') ax1.set_title('Original data') ax2.imshow(C_filtered, interpolation='nearest') ax2.set_title('C filtered data') ax3.imshow(Py_filtered, interpolation='nearest') ax3.set_title('Python filtered data') plt.show()