|
| 1 | +import itk |
| 2 | +import numpy as np |
| 3 | +import argparse |
| 4 | + |
| 5 | +parser = argparse.ArgumentParser(description="Convolve Image With Kernel") |
| 6 | +parser.add_argument("input_image") |
| 7 | +parser.add_argument("width", type=int) |
| 8 | +args = parser.parse_args() |
| 9 | + |
| 10 | +PixelType = itk.F |
| 11 | + |
| 12 | +# Read Image in float data type |
| 13 | +inputImage = itk.imread(args.input_image, PixelType) |
| 14 | + |
| 15 | +width = 10 |
| 16 | +if args.width: |
| 17 | + width = args.width |
| 18 | + |
| 19 | + |
| 20 | +def CreateSmoothKernel(width): |
| 21 | + return np.ones([width, width], "float32") / (width * width) |
| 22 | + |
| 23 | + |
| 24 | +kernel = CreateSmoothKernel(width) |
| 25 | +kernel_image = itk.image_from_array(kernel) |
| 26 | + |
| 27 | +# Convolve image with kernel. |
| 28 | +filteredImage = itk.convolution_image_filter(inputImage, kernel_image=kernel_image) |
| 29 | + |
| 30 | +# PNG requires an integer pixel type, so rescale the float result to 8-bit. |
| 31 | +rescaledImage = itk.rescale_intensity_image_filter( |
| 32 | + filteredImage, output_minimum=0, output_maximum=255 |
| 33 | +) |
| 34 | +outputImage = rescaledImage.astype(itk.UC) |
| 35 | + |
| 36 | +# Write the output Image |
| 37 | +itk.imwrite(outputImage, "ConvolveImageWithKernelPython.png") |
| 38 | + |
| 39 | +# Visualize the result using matplotlib |
| 40 | +import matplotlib.pyplot as plt |
| 41 | + |
| 42 | +plot_image = np.concatenate((inputImage, filteredImage), axis=1) |
| 43 | +plt.imshow(plot_image) |
| 44 | +plt.title("Visualize using Matplotlib, Kernel width = " + str(width)) |
| 45 | +plt.show(block=False) |
| 46 | +plt.pause(3) |
| 47 | +plt.close() |
0 commit comments