-
Notifications
You must be signed in to change notification settings - Fork 1
/
_correction.py
58 lines (43 loc) · 1.49 KB
/
_correction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""Mass spectrometry image correction
This module should be imported and contains the following:
* CorrectionInterface - Interface for msi correction.
* ZScoreCorrection - Class for z-score correction.
"""
import numpy as np
from abc import ABC, abstractmethod
from sklearn.preprocessing import StandardScaler
class CorrectionInterface(ABC):
"""Interface for msi correction.
"""
@abstractmethod
def correct(self, img: np.ndarray) -> np.ndarray:
"""Method to correct msi image.
Args:
img (np.ndarray): Mass spectrum image.
Returns:
np.ndarray: Corrected image.
"""
raise NotImplementedError
class ZScoreCorrection(CorrectionInterface):
def correct(self, img: np.ndarray, segment_img: np.ndarray) -> np.ndarray:
"""Method to correct msi image using zscore calculated from background
spectras.
Args:
img (np.ndarray): Mass spectrum image.
segment_img (np.ndarray): Segmentation image.
Returns:
np.ndarray: Corrected image.
"""
# Create z-score object using background spectras
scalar = StandardScaler().fit(img[~segment_img, :])
# Reshape image to 2d array
zscore_data = img.copy().reshape(
(img.shape[0] * img.shape[1], img.shape[2])
)
# Transform all spectras
zscore_data = scalar.transform(zscore_data)
# Reshape image to original shape
zscore_data = zscore_data.reshape(
(img.shape[0], img.shape[1], img.shape[2])
)
return zscore_data