Debian Codegraph @

doc/intro/tutorials/custom_func.py

raw
1 # -*- coding: utf-8 -*-
2 """
3 Example of remote control of DataLab current session,
4 from a Python script running outside DataLab (e.g. in Spyder)
5
6 Created on Fri May 12 12:28:56 2023
7
8 @author: p.raybaut
9 """
10
11 # %% Importing necessary modules
12
13 import numpy as np
14 import scipy.ndimage as spi
15 from sigima.client import SimpleRemoteProxy
16
17 # %% Connecting to DataLab current session
18
19 proxy = SimpleRemoteProxy()
20 proxy.connect()
21
22 # %% Executing commands in DataLab (...)
23
24
25 # Define our custom processing function
26 def weighted_average_denoise(data: np.ndarray) -> np.ndarray:
27 """Apply a custom denoising filter to an image.
28
29 This filter averages the pixels in a 5x5 neighborhood, but gives less weight
30 to pixels that significantly differ from the central pixel.
31 """
32
33 def filter_func(values: np.ndarray) -> float:
34 """Filter function"""
35 central_pixel = values[len(values) // 2]
36 differences = np.abs(values - central_pixel)
37 weights = np.exp(-differences / np.mean(differences))
38 return np.average(values, weights=weights)
39
40 return spi.generic_filter(data, filter_func, size=5)
41
42
43 # Switch to the "Image Panel" and get the current image
44 proxy.set_current_panel("image")
45 image = proxy.get_object()
46 if image is None:
47 # We raise an explicit error if there is no image to process
48 raise RuntimeError("No image to process!")
49
50 # Get a copy of the image data, and apply the function to it
51 data = np.array(image.data, copy=True)
52 data = weighted_average_denoise(data)
53
54 # Add new image to the panel
55 proxy.add_image("Filtered using Spyder", data)