| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
""" |
| 4 |
Custom denoising filter plugin |
| 5 |
============================== |
| 6 |
|
| 7 |
This is a simple example of a DataLab image processing plugin. |
| 8 |
|
| 9 |
It is part of the DataLab custom function tutorial. |
| 10 |
|
| 11 |
.. note:: |
| 12 |
|
| 13 |
This plugin is not installed by default. To install it, copy this file to |
| 14 |
your DataLab plugins directory (see `DataLab documentation |
| 15 |
<https://datalab-platform.com/en/features/advanced/plugins.html>`_). |
| 16 |
""" |
| 17 |
|
| 18 |
import numpy as np |
| 19 |
import scipy.ndimage as spi |
| 20 |
import sigima.proc.image as sipi |
| 21 |
|
| 22 |
import datalab.plugins |
| 23 |
|
| 24 |
|
| 25 |
def weighted_average_denoise(data: np.ndarray) -> np.ndarray: |
| 26 |
"""Apply a custom denoising filter to an image. |
| 27 |
|
| 28 |
This filter averages the pixels in a 5x5 neighborhood, but gives less weight |
| 29 |
to pixels that significantly differ from the central pixel. |
| 30 |
""" |
| 31 |
|
| 32 |
def filter_func(values: np.ndarray) -> float: |
| 33 |
"""Filter function""" |
| 34 |
central_pixel = values[len(values) // 2] |
| 35 |
differences = np.abs(values - central_pixel) |
| 36 |
weights = np.exp(-differences / np.mean(differences)) |
| 37 |
return np.average(values, weights=weights) |
| 38 |
|
| 39 |
return spi.generic_filter(data, filter_func, size=5) |
| 40 |
|
| 41 |
|
| 42 |
class CustomFilters(datalab.plugins.PluginBase): |
| 43 |
"""DataLab Custom Filters Plugin""" |
| 44 |
|
| 45 |
PLUGIN_INFO = datalab.plugins.PluginInfo( |
| 46 |
name="My custom filters", |
| 47 |
version="1.0.0", |
| 48 |
description="This is an example plugin", |
| 49 |
) |
| 50 |
|
| 51 |
def create_actions(self) -> None: |
| 52 |
"""Create actions""" |
| 53 |
acth = self.imagepanel.acthandler |
| 54 |
proc = self.imagepanel.processor |
| 55 |
with acth.new_menu(self.PLUGIN_INFO.name): |
| 56 |
for name, func in (("Weighted average denoise", weighted_average_denoise),): |
| 57 |
# Wrap function to handle ``ImageObj`` objects instead of NumPy arrays |
| 58 |
wrapped_func = sipi.Wrap1to1Func(func) |
| 59 |
acth.new_action( |
| 60 |
name, |
| 61 |
triggered=lambda: proc.compute_1_to_1(wrapped_func, title=name), |
| 62 |
) |