Created
June 6, 2017 11:00
-
-
Save dboyliao/0c12bb4f206e61aa48d1c373134ccb12 to your computer and use it in GitHub Desktop.
Image derivative with smoothed derivative kernel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # -*- coding: utf8 -*- | |
| #https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy | |
| import numpy as np | |
| from scipy.ndimage import convolve | |
| def gauss_kernel(size=5, sigma=None): | |
| if sigma is None: | |
| sigma = size/5 | |
| xs = np.arange(-size//2 + 1, size//2 + 1) | |
| grid_x, grid_y = np.meshgrid(xs, xs) | |
| kernel = np.exp(-(grid_x**2 + grid_y**2)/(2 * sigma**2)) | |
| return kernel/kernel.sum() | |
| def smooth_derive(img, along_x = False, size=5, sigma=None): | |
| kernel = gauss_kernel(size, sigma) | |
| w = np.array([[-1, 0, 1]])/2 | |
| if not along_x: | |
| w = w.T | |
| d_op = convolve(kernel, w) # construct smoothed derivative operator | |
| deriv_img = convolve(img, d_op) # convolve the derivative operator | |
| return deriv_img | |
| if __name__ == "__main__": | |
| import argparse, sys | |
| import matplotlib.pyplot as plt | |
| import cv2 | |
| if sys.version_info.major < 3: | |
| input = raw_input | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("src_img", metavar="IMAGE_PATH", help="source image path") | |
| parser.add_argument("-x", "--along-x", dest="along_x", action="store_true", help="along x direction") | |
| args = vars(parser.parse_args()) | |
| img = cv2.imread(args["src_img"], cv2.IMREAD_GRAYSCALE) | |
| derv = smooth_derive(img, args["along_x"], 15) | |
| plt.interactive(True) | |
| plt.imshow(derv, cmap='gray') | |
| input("press enter/return to exit") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment