Skip to content

Presidio Image Redactor API Reference

Image Redactor root module.

BboxProcessor

Common module for general bounding box operators.

Source code in presidio_image_redactor/bbox.py
  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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class BboxProcessor:
    """Common module for general bounding box operators."""

    @staticmethod
    def get_bboxes_from_ocr_results(
        ocr_results: Dict[str, List[Union[int, str]]],
    ) -> List[Dict[str, Union[int, float, str]]]:
        """Get bounding boxes on padded image for all detected words from ocr_results.

        :param ocr_results: Raw results from OCR.
        :return: Bounding box information per word.
        """
        bboxes = []
        for i in range(len(ocr_results["text"])):
            detected_text = ocr_results["text"][i]
            if detected_text:
                bbox = {
                    "left": ocr_results["left"][i],
                    "top": ocr_results["top"][i],
                    "width": ocr_results["width"][i],
                    "height": ocr_results["height"][i],
                    "conf": float(ocr_results["conf"][i]),
                    "label": detected_text,
                }
                bboxes.append(bbox)

        return bboxes

    @staticmethod
    def get_bboxes_from_analyzer_results(
        analyzer_results: List[ImageRecognizerResult],
    ) -> List[Dict[str, Union[str, float, int]]]:
        """Organize bounding box info from analyzer results.

        :param analyzer_results: Results from using ImageAnalyzerEngine.

        :return: Bounding box info organized.
        """
        bboxes = []
        for i in range(len(analyzer_results)):
            result = analyzer_results[i].to_dict()

            bbox_item = {
                "entity_type": result["entity_type"],
                "score": result["score"],
                "left": result["left"],
                "top": result["top"],
                "width": result["width"],
                "height": result["height"],
            }
            bboxes.append(bbox_item)

        return bboxes

    @staticmethod
    def remove_bbox_padding(
        analyzer_bboxes: List[Dict[str, Union[str, float, int]]],
        padding_width: int,
    ) -> List[Dict[str, int]]:
        """Remove added padding in bounding box coordinates.

        :param analyzer_bboxes: The bounding boxes from analyzer results.
        :param padding_width: Pixel width used for padding (0 if no padding).

        :return: Bounding box information per word.
        """
        if padding_width < 0:
            raise ValueError("Padding width must be a non-negative integer.")

        if len(analyzer_bboxes) > 0:
            # Get fields
            has_label = False
            has_entity_type = False
            try:
                _ = analyzer_bboxes[0]["label"]
                has_label = True
            except KeyError:
                has_label = False
            try:
                _ = analyzer_bboxes[0]["entity_type"]
                has_entity_type = True
            except KeyError:
                has_entity_type = False

            # Remove padding from all bounding boxes
            if has_label is True and has_entity_type is True:
                bboxes = [
                    {
                        "left": max(0, bbox["left"] - padding_width),
                        "top": max(0, bbox["top"] - padding_width),
                        "width": bbox["width"],
                        "height": bbox["height"],
                        "label": bbox["label"],
                        "entity_type": bbox["entity_type"]
                    }
                    for bbox in analyzer_bboxes
                ]
            elif has_label is True and has_entity_type is False:
                bboxes = [
                    {
                        "left": max(0, bbox["left"] - padding_width),
                        "top": max(0, bbox["top"] - padding_width),
                        "width": bbox["width"],
                        "height": bbox["height"],
                        "label": bbox["label"]
                    }
                    for bbox in analyzer_bboxes
                ]
            elif has_label is False and has_entity_type is True:
                bboxes = [
                    {
                        "left": max(0, bbox["left"] - padding_width),
                        "top": max(0, bbox["top"] - padding_width),
                        "width": bbox["width"],
                        "height": bbox["height"],
                        "entity_type": bbox["entity_type"]
                    }
                    for bbox in analyzer_bboxes
                ]
            elif has_label is False and has_entity_type is False:
                bboxes = [
                    {
                        "left": max(0, bbox["left"] - padding_width),
                        "top": max(0, bbox["top"] - padding_width),
                        "width": bbox["width"],
                        "height": bbox["height"]
                    }
                    for bbox in analyzer_bboxes
                ]
        else:
            bboxes = analyzer_bboxes

        return bboxes

    @staticmethod
    def match_with_source(
        all_pos: List[Dict[str, Union[str, int, float]]],
        pii_source_dict: List[Dict[str, Union[str, int, float]]],
        detected_pii: Dict[str, Union[str, float, int]],
        tolerance: int = 50,
    ) -> Tuple[List[Dict[str, Union[str, int, float]]], bool]:
        """Match returned redacted PII bbox data with some source of truth for PII.

        :param all_pos: Dictionary storing all positives.
        :param pii_source_dict: List of PII labels for this instance.
        :param detected_pii: Detected PII (single entity from analyzer_results).
        :param tolerance: Tolerance for exact coordinates and size data.
        :return: List of all positive with PII mapped back as possible
        and whether a match was found.
        """
        all_pos_match = all_pos.copy()

        # Get info from detected PII (positive)
        results_left = detected_pii["left"]
        results_top = detected_pii["top"]
        results_width = detected_pii["width"]
        results_height = detected_pii["height"]
        try:
            results_score = detected_pii["score"]
        except KeyError:
            # Handle matching when no score available
            results_score = 0
        match_found = False

        # See what in the ground truth this positive matches
        for label in pii_source_dict:
            source_left = label["left"]
            source_top = label["top"]
            source_width = label["width"]
            source_height = label["height"]

            match_left = abs(source_left - results_left) <= tolerance
            match_top = abs(source_top - results_top) <= tolerance
            match_width = abs(source_width - results_width) <= tolerance
            match_height = abs(source_height - results_height) <= tolerance
            matching = [match_left, match_top, match_width, match_height]

            if False not in matching:
                # If match is found, carry over ground truth info
                positive = label
                positive["score"] = results_score
                all_pos_match.append(positive)
                match_found = True

        return all_pos_match, match_found

get_bboxes_from_analyzer_results(analyzer_results) staticmethod

Organize bounding box info from analyzer results.

Parameters:

Name Type Description Default
analyzer_results List[ImageRecognizerResult]

Results from using ImageAnalyzerEngine.

required

Returns:

Type Description
List[Dict[str, Union[str, float, int]]]

Bounding box info organized.

Source code in presidio_image_redactor/bbox.py
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
@staticmethod
def get_bboxes_from_analyzer_results(
    analyzer_results: List[ImageRecognizerResult],
) -> List[Dict[str, Union[str, float, int]]]:
    """Organize bounding box info from analyzer results.

    :param analyzer_results: Results from using ImageAnalyzerEngine.

    :return: Bounding box info organized.
    """
    bboxes = []
    for i in range(len(analyzer_results)):
        result = analyzer_results[i].to_dict()

        bbox_item = {
            "entity_type": result["entity_type"],
            "score": result["score"],
            "left": result["left"],
            "top": result["top"],
            "width": result["width"],
            "height": result["height"],
        }
        bboxes.append(bbox_item)

    return bboxes

get_bboxes_from_ocr_results(ocr_results) staticmethod

Get bounding boxes on padded image for all detected words from ocr_results.

Parameters:

Name Type Description Default
ocr_results Dict[str, List[Union[int, str]]]

Raw results from OCR.

required

Returns:

Type Description
List[Dict[str, Union[int, float, str]]]

Bounding box information per word.

Source code in presidio_image_redactor/bbox.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@staticmethod
def get_bboxes_from_ocr_results(
    ocr_results: Dict[str, List[Union[int, str]]],
) -> List[Dict[str, Union[int, float, str]]]:
    """Get bounding boxes on padded image for all detected words from ocr_results.

    :param ocr_results: Raw results from OCR.
    :return: Bounding box information per word.
    """
    bboxes = []
    for i in range(len(ocr_results["text"])):
        detected_text = ocr_results["text"][i]
        if detected_text:
            bbox = {
                "left": ocr_results["left"][i],
                "top": ocr_results["top"][i],
                "width": ocr_results["width"][i],
                "height": ocr_results["height"][i],
                "conf": float(ocr_results["conf"][i]),
                "label": detected_text,
            }
            bboxes.append(bbox)

    return bboxes

match_with_source(all_pos, pii_source_dict, detected_pii, tolerance=50) staticmethod

Match returned redacted PII bbox data with some source of truth for PII.

Parameters:

Name Type Description Default
all_pos List[Dict[str, Union[str, int, float]]]

Dictionary storing all positives.

required
pii_source_dict List[Dict[str, Union[str, int, float]]]

List of PII labels for this instance.

required
detected_pii Dict[str, Union[str, float, int]]

Detected PII (single entity from analyzer_results).

required
tolerance int

Tolerance for exact coordinates and size data.

50

Returns:

Type Description
Tuple[List[Dict[str, Union[str, int, float]]], bool]

List of all positive with PII mapped back as possible and whether a match was found.

Source code in presidio_image_redactor/bbox.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@staticmethod
def match_with_source(
    all_pos: List[Dict[str, Union[str, int, float]]],
    pii_source_dict: List[Dict[str, Union[str, int, float]]],
    detected_pii: Dict[str, Union[str, float, int]],
    tolerance: int = 50,
) -> Tuple[List[Dict[str, Union[str, int, float]]], bool]:
    """Match returned redacted PII bbox data with some source of truth for PII.

    :param all_pos: Dictionary storing all positives.
    :param pii_source_dict: List of PII labels for this instance.
    :param detected_pii: Detected PII (single entity from analyzer_results).
    :param tolerance: Tolerance for exact coordinates and size data.
    :return: List of all positive with PII mapped back as possible
    and whether a match was found.
    """
    all_pos_match = all_pos.copy()

    # Get info from detected PII (positive)
    results_left = detected_pii["left"]
    results_top = detected_pii["top"]
    results_width = detected_pii["width"]
    results_height = detected_pii["height"]
    try:
        results_score = detected_pii["score"]
    except KeyError:
        # Handle matching when no score available
        results_score = 0
    match_found = False

    # See what in the ground truth this positive matches
    for label in pii_source_dict:
        source_left = label["left"]
        source_top = label["top"]
        source_width = label["width"]
        source_height = label["height"]

        match_left = abs(source_left - results_left) <= tolerance
        match_top = abs(source_top - results_top) <= tolerance
        match_width = abs(source_width - results_width) <= tolerance
        match_height = abs(source_height - results_height) <= tolerance
        matching = [match_left, match_top, match_width, match_height]

        if False not in matching:
            # If match is found, carry over ground truth info
            positive = label
            positive["score"] = results_score
            all_pos_match.append(positive)
            match_found = True

    return all_pos_match, match_found

remove_bbox_padding(analyzer_bboxes, padding_width) staticmethod

Remove added padding in bounding box coordinates.

Parameters:

Name Type Description Default
analyzer_bboxes List[Dict[str, Union[str, float, int]]]

The bounding boxes from analyzer results.

required
padding_width int

Pixel width used for padding (0 if no padding).

required

Returns:

Type Description
List[Dict[str, int]]

Bounding box information per word.

Source code in presidio_image_redactor/bbox.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@staticmethod
def remove_bbox_padding(
    analyzer_bboxes: List[Dict[str, Union[str, float, int]]],
    padding_width: int,
) -> List[Dict[str, int]]:
    """Remove added padding in bounding box coordinates.

    :param analyzer_bboxes: The bounding boxes from analyzer results.
    :param padding_width: Pixel width used for padding (0 if no padding).

    :return: Bounding box information per word.
    """
    if padding_width < 0:
        raise ValueError("Padding width must be a non-negative integer.")

    if len(analyzer_bboxes) > 0:
        # Get fields
        has_label = False
        has_entity_type = False
        try:
            _ = analyzer_bboxes[0]["label"]
            has_label = True
        except KeyError:
            has_label = False
        try:
            _ = analyzer_bboxes[0]["entity_type"]
            has_entity_type = True
        except KeyError:
            has_entity_type = False

        # Remove padding from all bounding boxes
        if has_label is True and has_entity_type is True:
            bboxes = [
                {
                    "left": max(0, bbox["left"] - padding_width),
                    "top": max(0, bbox["top"] - padding_width),
                    "width": bbox["width"],
                    "height": bbox["height"],
                    "label": bbox["label"],
                    "entity_type": bbox["entity_type"]
                }
                for bbox in analyzer_bboxes
            ]
        elif has_label is True and has_entity_type is False:
            bboxes = [
                {
                    "left": max(0, bbox["left"] - padding_width),
                    "top": max(0, bbox["top"] - padding_width),
                    "width": bbox["width"],
                    "height": bbox["height"],
                    "label": bbox["label"]
                }
                for bbox in analyzer_bboxes
            ]
        elif has_label is False and has_entity_type is True:
            bboxes = [
                {
                    "left": max(0, bbox["left"] - padding_width),
                    "top": max(0, bbox["top"] - padding_width),
                    "width": bbox["width"],
                    "height": bbox["height"],
                    "entity_type": bbox["entity_type"]
                }
                for bbox in analyzer_bboxes
            ]
        elif has_label is False and has_entity_type is False:
            bboxes = [
                {
                    "left": max(0, bbox["left"] - padding_width),
                    "top": max(0, bbox["top"] - padding_width),
                    "width": bbox["width"],
                    "height": bbox["height"]
                }
                for bbox in analyzer_bboxes
            ]
    else:
        bboxes = analyzer_bboxes

    return bboxes

BilateralFilter

Bases: ImagePreprocessor

BilateralFilter class.

The class applies bilateral filtering to an image. and returns the filtered image and metadata.

Source code in presidio_image_redactor/image_processing_engine.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
class BilateralFilter(ImagePreprocessor):
    """BilateralFilter class.

    The class applies bilateral filtering to an image. and returns the filtered
      image and metadata.
    """

    def __init__(
        self, diameter: int = 3, sigma_color: int = 40, sigma_space: int = 40
    ) -> None:
        """Initialize the BilateralFilter class.

        :param diameter: Diameter of each pixel neighborhood.
        :param sigma_color: value of sigma in the color space.
        :param sigma_space: value of sigma in the coordinate space.
        """
        super().__init__(use_greyscale=True)

        self.diameter = diameter
        self.sigma_color = sigma_color
        self.sigma_space = sigma_space

    def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
        """Preprocess the image to be analyzed.

        :param image: Loaded PIL image.

        :return: The processed image and metadata (diameter, sigma_color, sigma_space).
        """
        image = self.convert_image_to_array(image)

        # Apply bilateral filtering
        filtered_image = cv2.bilateralFilter(
            image,
            self.diameter,
            self.sigma_color,
            self.sigma_space,
        )

        metadata = {
            "diameter": self.diameter,
            "sigma_color": self.sigma_color,
            "sigma_space": self.sigma_space,
        }

        return Image.fromarray(filtered_image), metadata

__init__(diameter=3, sigma_color=40, sigma_space=40)

Initialize the BilateralFilter class.

Parameters:

Name Type Description Default
diameter int

Diameter of each pixel neighborhood.

3
sigma_color int

value of sigma in the color space.

40
sigma_space int

value of sigma in the coordinate space.

40
Source code in presidio_image_redactor/image_processing_engine.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def __init__(
    self, diameter: int = 3, sigma_color: int = 40, sigma_space: int = 40
) -> None:
    """Initialize the BilateralFilter class.

    :param diameter: Diameter of each pixel neighborhood.
    :param sigma_color: value of sigma in the color space.
    :param sigma_space: value of sigma in the coordinate space.
    """
    super().__init__(use_greyscale=True)

    self.diameter = diameter
    self.sigma_color = sigma_color
    self.sigma_space = sigma_space

preprocess_image(image)

Preprocess the image to be analyzed.

Parameters:

Name Type Description Default
image Image

Loaded PIL image.

required

Returns:

Type Description
Tuple[Image, dict]

The processed image and metadata (diameter, sigma_color, sigma_space).

Source code in presidio_image_redactor/image_processing_engine.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
    """Preprocess the image to be analyzed.

    :param image: Loaded PIL image.

    :return: The processed image and metadata (diameter, sigma_color, sigma_space).
    """
    image = self.convert_image_to_array(image)

    # Apply bilateral filtering
    filtered_image = cv2.bilateralFilter(
        image,
        self.diameter,
        self.sigma_color,
        self.sigma_space,
    )

    metadata = {
        "diameter": self.diameter,
        "sigma_color": self.sigma_color,
        "sigma_space": self.sigma_space,
    }

    return Image.fromarray(filtered_image), metadata

ContrastSegmentedImageEnhancer

Bases: ImagePreprocessor

Class containing all logic to perform contrastive segmentation.

Contrastive segmentation is a preprocessing step that aims to enhance the text in an image by increasing the contrast between the text and the background. The parameters used to run the preprocessing are selected based on the contrast level of the image.

Source code in presidio_image_redactor/image_processing_engine.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
class ContrastSegmentedImageEnhancer(ImagePreprocessor):
    """Class containing all logic to perform contrastive segmentation.

    Contrastive segmentation is a preprocessing step that aims to enhance the
    text in an image by increasing the contrast between the text and the
    background. The parameters used to run the preprocessing are selected based
    on the contrast level of the image.
    """

    def __init__(
        self,
        bilateral_filter: Optional[BilateralFilter] = None,
        adaptive_threshold: Optional[SegmentedAdaptiveThreshold] = None,
        image_rescaling: Optional[ImageRescaling] = None,
        low_contrast_threshold: int = 40,
    ) -> None:
        """Initialize the class.

        :param bilateral_filter: Optional BilateralFilter instance.
        :param adaptive_threshold: Optional AdaptiveThreshold instance.
        :param image_rescaling: Optional ImageRescaling instance.
        :param low_contrast_threshold: Threshold for low contrast images.
        """

        super().__init__(use_greyscale=True)
        if not bilateral_filter:
            self.bilateral_filter = BilateralFilter()
        else:
            self.bilateral_filter = bilateral_filter

        if not adaptive_threshold:
            self.adaptive_threshold = SegmentedAdaptiveThreshold()
        else:
            self.adaptive_threshold = adaptive_threshold

        if not image_rescaling:
            self.image_rescaling = ImageRescaling()
        else:
            self.image_rescaling = image_rescaling

        self.low_contrast_threshold = low_contrast_threshold

    def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
        """Preprocess the image to be analyzed.

        :param image: Loaded PIL image.

        :return: The processed image and metadata (background color, scale percentage,
             contrast level, and C value).
        """
        image = self.convert_image_to_array(image)

        # Apply bilateral filtering
        filtered_image, _ = self.bilateral_filter.preprocess_image(image)

        # Convert to grayscale
        pil_filtered_image = Image.fromarray(np.uint8(filtered_image))
        pil_grayscale_image = pil_filtered_image.convert("L")
        grayscale_image = np.asarray(pil_grayscale_image)

        # Improve contrast
        adjusted_image, _, adjusted_contrast = self._improve_contrast(grayscale_image)

        # Adaptive Thresholding
        adaptive_threshold_image, _ = self.adaptive_threshold.preprocess_image(
            adjusted_image
        )
        # Increase contrast
        _, threshold_image = cv2.threshold(
            np.asarray(adaptive_threshold_image),
            0,
            255,
            cv2.THRESH_BINARY | cv2.THRESH_OTSU,
        )

        # Rescale image
        rescaled_image, scale_metadata = self.image_rescaling.preprocess_image(
            threshold_image
        )

        return rescaled_image, scale_metadata

    def _improve_contrast(self, image: np.ndarray) -> Tuple[np.ndarray, str, str]:
        """Improve the contrast of an image based on its initial contrast level.

        :param image: Input image.

        :return: A tuple containing the improved image, the initial contrast level,
             and the adjusted contrast level.
        """
        contrast, mean_intensity = self._get_image_contrast(image)

        if contrast <= self.low_contrast_threshold:
            alpha = 1.5
            beta = -mean_intensity * alpha
            adjusted_image = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
            adjusted_contrast, _ = self._get_image_contrast(adjusted_image)
        else:
            adjusted_image = image
            adjusted_contrast = contrast
        return adjusted_image, contrast, adjusted_contrast

__init__(bilateral_filter=None, adaptive_threshold=None, image_rescaling=None, low_contrast_threshold=40)

Initialize the class.

Parameters:

Name Type Description Default
bilateral_filter Optional[BilateralFilter]

Optional BilateralFilter instance.

None
adaptive_threshold Optional[SegmentedAdaptiveThreshold]

Optional AdaptiveThreshold instance.

None
image_rescaling Optional[ImageRescaling]

Optional ImageRescaling instance.

None
low_contrast_threshold int

Threshold for low contrast images.

40
Source code in presidio_image_redactor/image_processing_engine.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def __init__(
    self,
    bilateral_filter: Optional[BilateralFilter] = None,
    adaptive_threshold: Optional[SegmentedAdaptiveThreshold] = None,
    image_rescaling: Optional[ImageRescaling] = None,
    low_contrast_threshold: int = 40,
) -> None:
    """Initialize the class.

    :param bilateral_filter: Optional BilateralFilter instance.
    :param adaptive_threshold: Optional AdaptiveThreshold instance.
    :param image_rescaling: Optional ImageRescaling instance.
    :param low_contrast_threshold: Threshold for low contrast images.
    """

    super().__init__(use_greyscale=True)
    if not bilateral_filter:
        self.bilateral_filter = BilateralFilter()
    else:
        self.bilateral_filter = bilateral_filter

    if not adaptive_threshold:
        self.adaptive_threshold = SegmentedAdaptiveThreshold()
    else:
        self.adaptive_threshold = adaptive_threshold

    if not image_rescaling:
        self.image_rescaling = ImageRescaling()
    else:
        self.image_rescaling = image_rescaling

    self.low_contrast_threshold = low_contrast_threshold

preprocess_image(image)

Preprocess the image to be analyzed.

Parameters:

Name Type Description Default
image Image

Loaded PIL image.

required

Returns:

Type Description
Tuple[Image, dict]

The processed image and metadata (background color, scale percentage, contrast level, and C value).

Source code in presidio_image_redactor/image_processing_engine.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
    """Preprocess the image to be analyzed.

    :param image: Loaded PIL image.

    :return: The processed image and metadata (background color, scale percentage,
         contrast level, and C value).
    """
    image = self.convert_image_to_array(image)

    # Apply bilateral filtering
    filtered_image, _ = self.bilateral_filter.preprocess_image(image)

    # Convert to grayscale
    pil_filtered_image = Image.fromarray(np.uint8(filtered_image))
    pil_grayscale_image = pil_filtered_image.convert("L")
    grayscale_image = np.asarray(pil_grayscale_image)

    # Improve contrast
    adjusted_image, _, adjusted_contrast = self._improve_contrast(grayscale_image)

    # Adaptive Thresholding
    adaptive_threshold_image, _ = self.adaptive_threshold.preprocess_image(
        adjusted_image
    )
    # Increase contrast
    _, threshold_image = cv2.threshold(
        np.asarray(adaptive_threshold_image),
        0,
        255,
        cv2.THRESH_BINARY | cv2.THRESH_OTSU,
    )

    # Rescale image
    rescaled_image, scale_metadata = self.image_rescaling.preprocess_image(
        threshold_image
    )

    return rescaled_image, scale_metadata

DicomImagePiiVerifyEngine

Bases: ImagePiiVerifyEngine, DicomImageRedactorEngine

Class to handle verification and evaluation for DICOM de-identification.

Source code in presidio_image_redactor/dicom_image_pii_verify_engine.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
class DicomImagePiiVerifyEngine(ImagePiiVerifyEngine, DicomImageRedactorEngine):
    """Class to handle verification and evaluation for DICOM de-identification."""

    def __init__(
        self,
        ocr_engine: Optional[OCR] = None,
        image_analyzer_engine: Optional[ImageAnalyzerEngine] = None,
    ):
        """Initialize DicomImagePiiVerifyEngine object.

        :param ocr_engine: OCR engine to use.
        :param image_analyzer_engine: Image analyzer engine to use.
        """
        # Initialize OCR engine
        if not ocr_engine:
            self.ocr_engine = TesseractOCR()
        else:
            self.ocr_engine = ocr_engine

        # Initialize image analyzer engine
        if not image_analyzer_engine:
            self.image_analyzer_engine = ImageAnalyzerEngine()
        else:
            self.image_analyzer_engine = image_analyzer_engine

        # Initialize bbox processor
        self.bbox_processor = BboxProcessor()

    def verify_dicom_instance(
        self,
        instance: pydicom.dataset.FileDataset,
        padding_width: int = 25,
        display_image: bool = True,
        show_text_annotation: bool = True,
        use_metadata: bool = True,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> Tuple[Optional[PIL.Image.Image], dict, list]:
        """Verify PII on a single DICOM instance.

        :param instance: Loaded DICOM instance including pixel data and metadata.
        :param padding_width: Padding width to use when running OCR.
        :param display_image: If the verificationimage is displayed and returned.
        :param show_text_annotation: True to display entity type when displaying
        image with bounding boxes.
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in ImageAnalyzerEngine.

        :return: Image with boxes identifying PHI, OCR results,
        and analyzer results.
        """
        instance_copy = deepcopy(instance)

        try:
            instance_copy.PixelData
        except AttributeError:
            raise AttributeError("Provided DICOM instance lacks pixel data.")

        # Load image for processing
        with tempfile.TemporaryDirectory() as tmpdirname:
            # Convert DICOM to PNG and add padding for OCR (during analysis)
            is_greyscale = self._check_if_greyscale(instance_copy)
            image = self._rescale_dcm_pixel_array(instance_copy, is_greyscale)
            self._save_pixel_array_as_png(image, is_greyscale, "tmp_dcm", tmpdirname)

            png_filepath = f"{tmpdirname}/tmp_dcm.png"
            loaded_image = Image.open(png_filepath)
            image = self._add_padding(loaded_image, is_greyscale, padding_width)

        # Get OCR results
        perform_ocr_kwargs, ocr_threshold = self.image_analyzer_engine._parse_ocr_kwargs(ocr_kwargs)  # noqa: E501
        ocr_results = self.ocr_engine.perform_ocr(image, **perform_ocr_kwargs)
        if ocr_threshold:
            ocr_results = self.image_analyzer_engine.threshold_ocr_result(
                ocr_results,
                ocr_threshold
            )
        ocr_bboxes = self.bbox_processor.get_bboxes_from_ocr_results(
            ocr_results
        )

        # Get analyzer results
        analyzer_results = self._get_analyzer_results(
            image, instance, use_metadata, ocr_kwargs, ad_hoc_recognizers,
            **text_analyzer_kwargs
        )
        analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
            analyzer_results
        )

        # Prepare for plotting
        pii_bboxes = self.image_analyzer_engine.get_pii_bboxes(
            ocr_bboxes,
            analyzer_bboxes
        )
        if is_greyscale:
            use_greyscale_cmap = True
        else:
            use_greyscale_cmap = False

        # Get image with verification boxes
        verify_image = (
            self.image_analyzer_engine.add_custom_bboxes(
                image, pii_bboxes, show_text_annotation, use_greyscale_cmap
            )
            if display_image
            else None
        )

        return verify_image, ocr_bboxes, analyzer_bboxes

    def eval_dicom_instance(
        self,
        instance: pydicom.dataset.FileDataset,
        ground_truth: dict,
        padding_width: int = 25,
        tolerance: int = 50,
        display_image: bool = False,
        use_metadata: bool = True,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> Tuple[Optional[PIL.Image.Image], dict]:
        """Evaluate performance for a single DICOM instance.

        :param instance: Loaded DICOM instance including pixel data and metadata.
        :param ground_truth: Dictionary containing ground truth labels for the instance.
        :param padding_width: Padding width to use when running OCR.
        :param tolerance: Pixel distance tolerance for matching to ground truth.
        :param display_image: If the verificationimage is displayed and returned.
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in ImageAnalyzerEngine.

        :return: Evaluation comparing redactor engine results vs ground truth.
        """
        # Verify detected PHI
        verify_image, ocr_results, analyzer_results = self.verify_dicom_instance(
            instance,
            padding_width,
            display_image,
            use_metadata,
            ocr_kwargs=ocr_kwargs,
            ad_hoc_recognizers=ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )
        formatted_ocr_results = self.bbox_processor.get_bboxes_from_ocr_results(
            ocr_results
        )
        detected_phi = self.bbox_processor.get_bboxes_from_analyzer_results(
            analyzer_results
        )

        # Remove duplicate entities in results
        detected_phi = self._remove_duplicate_entities(detected_phi)

        # Get correct PHI text (all TP and FP)
        all_pos = self._label_all_positives(
            ground_truth, formatted_ocr_results, detected_phi, tolerance
        )

        # Calculate evaluation metrics
        precision = self.calculate_precision(ground_truth, all_pos)
        recall = self.calculate_recall(ground_truth, all_pos)

        eval_results = {
            "all_positives": all_pos,
            "ground_truth": ground_truth,
            "precision": precision,
            "recall": recall,
        }

        return verify_image, eval_results

    @staticmethod
    def _remove_duplicate_entities(
        results: List[dict], dup_pix_tolerance: int = 5
    ) -> List[dict]:
        """Handle when a word is detected multiple times as different types of entities.

        :param results: List of detected PHI with bbox info.
        :param dup_pix_tolerance: Pixel difference tolerance for identifying duplicates.
        :return: Detected PHI with no duplicate entities.
        """
        dups = []
        sorted(results, key=lambda x: x['score'], reverse=True)
        results_no_dups = []
        dims = ["left", "top", "width", "height"]

        # Check for duplicates
        for i in range(len(results) - 1):
            i_dims = {dim: results[i][dim] for dim in dims}

            # Ignore if we've already detected this dup combination
            for other in range(i + 1, len(results)):
                if i not in results_no_dups:
                    other_dims = {dim: results[other][dim] for dim in dims}
                    matching_dims = {
                        dim: abs(i_dims[dim] - other_dims[dim]) <= dup_pix_tolerance
                        for dim in dims
                    }
                    matching = list(matching_dims.values())

                    if all(matching):
                        lower_scored_index = other if \
                            results[other]['score'] < results[i]['score'] else i
                        dups.append(lower_scored_index)

        # Remove duplicates
        for i in range(len(results)):
            if i not in dups:
                results_no_dups.append(results[i])

        return results_no_dups

    def _label_all_positives(
        self,
        gt_labels_dict: dict,
        ocr_results: List[dict],
        detected_phi: List[dict],
        tolerance: int = 50,
    ) -> List[dict]:
        """Label all entities detected as PHI by using ground truth and OCR results.

        All positives (detected_phi) do not contain PHI labels and are thus
        difficult to work with intuitively. This method maps back to the
        actual PHI to each detected sensitive entity.

        :param gt_labels_dict: Dictionary with ground truth labels for a
        single DICOM instance.
        :param ocr_results: All detected text.
        :param detected_phi: Formatted analyzer_results.
        :param tolerance: Tolerance for exact coordinates and size data.
        :return: List of all positives, labeled.
        """
        all_pos = []

        # Cycle through each positive (TP or FP)
        for analyzer_result in detected_phi:

            # See if there are any ground truth matches
            all_pos, gt_match_found = self.bbox_processor.match_with_source(
                all_pos, gt_labels_dict, analyzer_result, tolerance
            )

            # If not, check back with OCR
            if not gt_match_found:
                all_pos, _ = self.bbox_processor.match_with_source(
                    all_pos, ocr_results, analyzer_result, tolerance
                )

        # Remove any duplicates
        all_pos = self._remove_duplicate_entities(all_pos)

        return all_pos

    @staticmethod
    def calculate_precision(gt: List[dict], all_pos: List[dict]) -> float:
        """Calculate precision.

        :param gt: List of ground truth labels.
        :param all_pos: All Detected PHI (mapped back to have actual PHI text).
        :return: Precision value.
        """
        # Find True Positive (TP) and precision
        tp = [i for i in all_pos if i in gt]
        try:
            precision = len(tp) / len(all_pos)
        except ZeroDivisionError:
            precision = 0

        return precision

    @staticmethod
    def calculate_recall(gt: List[dict], all_pos: List[dict]) -> float:
        """Calculate recall.

        :param gt: List of ground truth labels.
        :param all_pos: All Detected PHI (mapped back to have actual PHI text).
        :return: Recall value.
        """
        # Find True Positive (TP) and precision
        tp = [i for i in all_pos if i in gt]
        try:
            recall = len(tp) / len(gt)
        except ZeroDivisionError:
            recall = 0

        return recall

__init__(ocr_engine=None, image_analyzer_engine=None)

Initialize DicomImagePiiVerifyEngine object.

Parameters:

Name Type Description Default
ocr_engine Optional[OCR]

OCR engine to use.

None
image_analyzer_engine Optional[ImageAnalyzerEngine]

Image analyzer engine to use.

None
Source code in presidio_image_redactor/dicom_image_pii_verify_engine.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def __init__(
    self,
    ocr_engine: Optional[OCR] = None,
    image_analyzer_engine: Optional[ImageAnalyzerEngine] = None,
):
    """Initialize DicomImagePiiVerifyEngine object.

    :param ocr_engine: OCR engine to use.
    :param image_analyzer_engine: Image analyzer engine to use.
    """
    # Initialize OCR engine
    if not ocr_engine:
        self.ocr_engine = TesseractOCR()
    else:
        self.ocr_engine = ocr_engine

    # Initialize image analyzer engine
    if not image_analyzer_engine:
        self.image_analyzer_engine = ImageAnalyzerEngine()
    else:
        self.image_analyzer_engine = image_analyzer_engine

    # Initialize bbox processor
    self.bbox_processor = BboxProcessor()

calculate_precision(gt, all_pos) staticmethod

Calculate precision.

Parameters:

Name Type Description Default
gt List[dict]

List of ground truth labels.

required
all_pos List[dict]

All Detected PHI (mapped back to have actual PHI text).

required

Returns:

Type Description
float

Precision value.

Source code in presidio_image_redactor/dicom_image_pii_verify_engine.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
@staticmethod
def calculate_precision(gt: List[dict], all_pos: List[dict]) -> float:
    """Calculate precision.

    :param gt: List of ground truth labels.
    :param all_pos: All Detected PHI (mapped back to have actual PHI text).
    :return: Precision value.
    """
    # Find True Positive (TP) and precision
    tp = [i for i in all_pos if i in gt]
    try:
        precision = len(tp) / len(all_pos)
    except ZeroDivisionError:
        precision = 0

    return precision

calculate_recall(gt, all_pos) staticmethod

Calculate recall.

Parameters:

Name Type Description Default
gt List[dict]

List of ground truth labels.

required
all_pos List[dict]

All Detected PHI (mapped back to have actual PHI text).

required

Returns:

Type Description
float

Recall value.

Source code in presidio_image_redactor/dicom_image_pii_verify_engine.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
@staticmethod
def calculate_recall(gt: List[dict], all_pos: List[dict]) -> float:
    """Calculate recall.

    :param gt: List of ground truth labels.
    :param all_pos: All Detected PHI (mapped back to have actual PHI text).
    :return: Recall value.
    """
    # Find True Positive (TP) and precision
    tp = [i for i in all_pos if i in gt]
    try:
        recall = len(tp) / len(gt)
    except ZeroDivisionError:
        recall = 0

    return recall

eval_dicom_instance(instance, ground_truth, padding_width=25, tolerance=50, display_image=False, use_metadata=True, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Evaluate performance for a single DICOM instance.

Parameters:

Name Type Description Default
instance FileDataset

Loaded DICOM instance including pixel data and metadata.

required
ground_truth dict

Dictionary containing ground truth labels for the instance.

required
padding_width int

Padding width to use when running OCR.

25
tolerance int

Pixel distance tolerance for matching to ground truth.

50
display_image bool

If the verificationimage is displayed and returned.

False
use_metadata bool

Whether to redact text in the image that are present in the metadata.

True
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in ImageAnalyzerEngine.

{}

Returns:

Type Description
Tuple[Optional[Image], dict]

Evaluation comparing redactor engine results vs ground truth.

Source code in presidio_image_redactor/dicom_image_pii_verify_engine.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def eval_dicom_instance(
    self,
    instance: pydicom.dataset.FileDataset,
    ground_truth: dict,
    padding_width: int = 25,
    tolerance: int = 50,
    display_image: bool = False,
    use_metadata: bool = True,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> Tuple[Optional[PIL.Image.Image], dict]:
    """Evaluate performance for a single DICOM instance.

    :param instance: Loaded DICOM instance including pixel data and metadata.
    :param ground_truth: Dictionary containing ground truth labels for the instance.
    :param padding_width: Padding width to use when running OCR.
    :param tolerance: Pixel distance tolerance for matching to ground truth.
    :param display_image: If the verificationimage is displayed and returned.
    :param use_metadata: Whether to redact text in the image that
    are present in the metadata.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in ImageAnalyzerEngine.

    :return: Evaluation comparing redactor engine results vs ground truth.
    """
    # Verify detected PHI
    verify_image, ocr_results, analyzer_results = self.verify_dicom_instance(
        instance,
        padding_width,
        display_image,
        use_metadata,
        ocr_kwargs=ocr_kwargs,
        ad_hoc_recognizers=ad_hoc_recognizers,
        **text_analyzer_kwargs,
    )
    formatted_ocr_results = self.bbox_processor.get_bboxes_from_ocr_results(
        ocr_results
    )
    detected_phi = self.bbox_processor.get_bboxes_from_analyzer_results(
        analyzer_results
    )

    # Remove duplicate entities in results
    detected_phi = self._remove_duplicate_entities(detected_phi)

    # Get correct PHI text (all TP and FP)
    all_pos = self._label_all_positives(
        ground_truth, formatted_ocr_results, detected_phi, tolerance
    )

    # Calculate evaluation metrics
    precision = self.calculate_precision(ground_truth, all_pos)
    recall = self.calculate_recall(ground_truth, all_pos)

    eval_results = {
        "all_positives": all_pos,
        "ground_truth": ground_truth,
        "precision": precision,
        "recall": recall,
    }

    return verify_image, eval_results

verify_dicom_instance(instance, padding_width=25, display_image=True, show_text_annotation=True, use_metadata=True, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Verify PII on a single DICOM instance.

Parameters:

Name Type Description Default
instance FileDataset

Loaded DICOM instance including pixel data and metadata.

required
padding_width int

Padding width to use when running OCR.

25
display_image bool

If the verificationimage is displayed and returned.

True
show_text_annotation bool

True to display entity type when displaying image with bounding boxes.

True
use_metadata bool

Whether to redact text in the image that are present in the metadata.

True
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in ImageAnalyzerEngine.

{}

Returns:

Type Description
Tuple[Optional[Image], dict, list]

Image with boxes identifying PHI, OCR results, and analyzer results.

Source code in presidio_image_redactor/dicom_image_pii_verify_engine.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def verify_dicom_instance(
    self,
    instance: pydicom.dataset.FileDataset,
    padding_width: int = 25,
    display_image: bool = True,
    show_text_annotation: bool = True,
    use_metadata: bool = True,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> Tuple[Optional[PIL.Image.Image], dict, list]:
    """Verify PII on a single DICOM instance.

    :param instance: Loaded DICOM instance including pixel data and metadata.
    :param padding_width: Padding width to use when running OCR.
    :param display_image: If the verificationimage is displayed and returned.
    :param show_text_annotation: True to display entity type when displaying
    image with bounding boxes.
    :param use_metadata: Whether to redact text in the image that
    are present in the metadata.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in ImageAnalyzerEngine.

    :return: Image with boxes identifying PHI, OCR results,
    and analyzer results.
    """
    instance_copy = deepcopy(instance)

    try:
        instance_copy.PixelData
    except AttributeError:
        raise AttributeError("Provided DICOM instance lacks pixel data.")

    # Load image for processing
    with tempfile.TemporaryDirectory() as tmpdirname:
        # Convert DICOM to PNG and add padding for OCR (during analysis)
        is_greyscale = self._check_if_greyscale(instance_copy)
        image = self._rescale_dcm_pixel_array(instance_copy, is_greyscale)
        self._save_pixel_array_as_png(image, is_greyscale, "tmp_dcm", tmpdirname)

        png_filepath = f"{tmpdirname}/tmp_dcm.png"
        loaded_image = Image.open(png_filepath)
        image = self._add_padding(loaded_image, is_greyscale, padding_width)

    # Get OCR results
    perform_ocr_kwargs, ocr_threshold = self.image_analyzer_engine._parse_ocr_kwargs(ocr_kwargs)  # noqa: E501
    ocr_results = self.ocr_engine.perform_ocr(image, **perform_ocr_kwargs)
    if ocr_threshold:
        ocr_results = self.image_analyzer_engine.threshold_ocr_result(
            ocr_results,
            ocr_threshold
        )
    ocr_bboxes = self.bbox_processor.get_bboxes_from_ocr_results(
        ocr_results
    )

    # Get analyzer results
    analyzer_results = self._get_analyzer_results(
        image, instance, use_metadata, ocr_kwargs, ad_hoc_recognizers,
        **text_analyzer_kwargs
    )
    analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
        analyzer_results
    )

    # Prepare for plotting
    pii_bboxes = self.image_analyzer_engine.get_pii_bboxes(
        ocr_bboxes,
        analyzer_bboxes
    )
    if is_greyscale:
        use_greyscale_cmap = True
    else:
        use_greyscale_cmap = False

    # Get image with verification boxes
    verify_image = (
        self.image_analyzer_engine.add_custom_bboxes(
            image, pii_bboxes, show_text_annotation, use_greyscale_cmap
        )
        if display_image
        else None
    )

    return verify_image, ocr_bboxes, analyzer_bboxes

DicomImageRedactorEngine

Bases: ImageRedactorEngine

Performs OCR + PII detection + bounding box redaction.

Parameters:

Name Type Description Default
image_analyzer_engine ImageAnalyzerEngine

Engine which performs OCR + PII detection.

None
Source code in presidio_image_redactor/dicom_image_redactor_engine.py
  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
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
class DicomImageRedactorEngine(ImageRedactorEngine):
    """Performs OCR + PII detection + bounding box redaction.

    :param image_analyzer_engine: Engine which performs OCR + PII detection.
    """

    def redact_and_return_bbox(
        self,
        image: pydicom.dataset.FileDataset,
        fill: str = "contrast",
        padding_width: int = 25,
        crop_ratio: float = 0.75,
        use_metadata: bool = True,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> Tuple[pydicom.dataset.FileDataset, List[Dict[str, int]]]:
        """Redact method to redact the given DICOM image and return redacted bboxes.

        Please note, this method duplicates the image, creates a
        new instance and manipulates it.

        :param image: Loaded DICOM instance including pixel data and metadata.
        :param fill: Fill setting to use for redaction box ("contrast" or "background").
        :param padding_width: Padding width to use when running OCR.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.

        :return: DICOM instance with redacted pixel data.
        """
        # Check input
        if type(image) not in [pydicom.dataset.FileDataset, pydicom.dataset.Dataset]:
            raise TypeError("The provided image must be a loaded DICOM instance.")
        try:
            image.PixelData
        except AttributeError as e:
            raise AttributeError(f"Provided DICOM instance lacks pixel data: {e}")
        except PermissionError as e:
            raise PermissionError(f"Unable to access pixel data (may not exist): {e}")
        except IsADirectoryError as e:
            raise IsADirectoryError(f"DICOM instance is a directory: {e}")

        instance = deepcopy(image)

        # Load image for processing
        with tempfile.TemporaryDirectory() as tmpdirname:
            # Convert DICOM to PNG and add padding for OCR (during analysis)
            is_greyscale = self._check_if_greyscale(instance)
            image = self._rescale_dcm_pixel_array(instance, is_greyscale)
            image_name = str(uuid.uuid4())
            self._save_pixel_array_as_png(image, is_greyscale, image_name, tmpdirname)

            png_filepath = f"{tmpdirname}/{image_name}.png"
            loaded_image = Image.open(png_filepath)
            image = self._add_padding(loaded_image, is_greyscale, padding_width)

        # Detect PII
        analyzer_results = self._get_analyzer_results(
            image,
            instance,
            use_metadata,
            ocr_kwargs,
            ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )

        # Redact all bounding boxes from DICOM file
        analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
            analyzer_results
        )
        bboxes = self.bbox_processor.remove_bbox_padding(analyzer_bboxes, padding_width)
        redacted_image = self._add_redact_box(instance, bboxes, crop_ratio, fill)

        return redacted_image, bboxes

    def redact(
        self,
        image: pydicom.dataset.FileDataset,
        fill: str = "contrast",
        padding_width: int = 25,
        crop_ratio: float = 0.75,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> pydicom.dataset.FileDataset:
        """Redact method to redact the given DICOM image.

        Please note, this method duplicates the image, creates a
        new instance and manipulates it.

        :param image: Loaded DICOM instance including pixel data and metadata.
        :param fill: Fill setting to use for redaction box ("contrast" or "background").
        :param padding_width: Padding width to use when running OCR.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.

        :return: DICOM instance with redacted pixel data.
        """
        redacted_image, _ = self.redact_and_return_bbox(
            image=image,
            fill=fill,
            padding_width=padding_width,
            crop_ratio=crop_ratio,
            ocr_kwargs=ocr_kwargs,
            ad_hoc_recognizers=ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )

        return redacted_image

    def redact_from_file(
        self,
        input_dicom_path: str,
        output_dir: str,
        padding_width: int = 25,
        crop_ratio: float = 0.75,
        fill: str = "contrast",
        use_metadata: bool = True,
        save_bboxes: bool = False,
        verbose: bool = True,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> None:
        """Redact method to redact from a given file.

        Please notice, this method duplicates the file, creates
        new instance and manipulate them.

        :param input_dicom_path: String path to DICOM image.
        :param output_dir: String path to parent output directory.
        :param padding_width : Padding width to use when running OCR.
        :param fill: Color setting to use for redaction box
        ("contrast" or "background").
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param save_bboxes: True if we want to save boundings boxes.
        :param verbose: True to print where redacted file was written to.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.
        """
        # Verify the given paths
        if Path(input_dicom_path).is_dir() is True:
            raise TypeError("input_dicom_path must be file (not dir)")
        if Path(input_dicom_path).is_file() is False:
            raise TypeError("input_dicom_path must be a valid file")
        if Path(output_dir).is_file() is True:
            raise TypeError(
                "output_dir must be a directory (does not need to exist yet)"
            )

        # Create duplicate
        dst_path = self._copy_files_for_processing(input_dicom_path, output_dir)

        # Process DICOM file
        output_location = self._redact_single_dicom_image(
            dcm_path=dst_path,
            crop_ratio=crop_ratio,
            fill=fill,
            padding_width=padding_width,
            use_metadata=use_metadata,
            overwrite=True,
            dst_parent_dir=".",
            save_bboxes=save_bboxes,
            ocr_kwargs=ocr_kwargs,
            ad_hoc_recognizers=ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )

        if verbose:
            print(f"Output written to {output_location}")

        return None

    def redact_from_directory(
        self,
        input_dicom_path: str,
        output_dir: str,
        padding_width: int = 25,
        crop_ratio: float = 0.75,
        fill: str = "contrast",
        use_metadata: bool = True,
        save_bboxes: bool = False,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> None:
        """Redact method to redact from a directory of files.

        Please notice, this method duplicates the files, creates
        new instances and manipulate them.

        :param input_dicom_path: String path to directory of DICOM images.
        :param output_dir: String path to parent output directory.
        :param padding_width : Padding width to use when running OCR.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param fill: Color setting to use for redaction box
        ("contrast" or "background").
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param save_bboxes: True if we want to save boundings boxes.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.
        """
        # Verify the given paths
        if Path(input_dicom_path).is_dir() is False:
            raise TypeError("input_dicom_path must be a valid directory")
        if Path(input_dicom_path).is_file() is True:
            raise TypeError("input_dicom_path must be a directory (not file)")
        if Path(output_dir).is_file() is True:
            raise TypeError(
                "output_dir must be a directory (does not need to exist yet)"
            )

        # Create duplicates
        dst_path = self._copy_files_for_processing(input_dicom_path, output_dir)

        # Process DICOM files
        output_location = self._redact_multiple_dicom_images(
            dcm_dir=dst_path,
            crop_ratio=crop_ratio,
            fill=fill,
            padding_width=padding_width,
            use_metadata=use_metadata,
            ad_hoc_recognizers=ad_hoc_recognizers,
            overwrite=True,
            dst_parent_dir=".",
            save_bboxes=save_bboxes,
            ocr_kwargs=ocr_kwargs,
            **text_analyzer_kwargs,
        )

        print(f"Output written to {output_location}")

        return None

    @staticmethod
    def _get_all_dcm_files(dcm_dir: Path) -> List[Path]:
        """Return paths to all DICOM files in a directory and its sub-directories.

        :param dcm_dir: pathlib Path to a directory containing at least one .dcm file.

        :return: List of pathlib Path objects.
        """
        # Define applicable extensions
        extensions = ["[dD][cC][mM]", "[dD][iI][cC][oO][mM]"]

        # Get all files with any applicable extension
        all_files = []
        for extension in extensions:
            p = dcm_dir.glob(f"**/*.{extension}")
            files = [x for x in p if x.is_file()]
            all_files += files

        return all_files

    @staticmethod
    def _check_if_greyscale(instance: pydicom.dataset.FileDataset) -> bool:
        """Check if a DICOM image is in greyscale.

        :param instance: A single DICOM instance.

        :return: FALSE if the Photometric Interpretation is RGB.
        """
        # Check if image is grayscale using the Photometric Interpretation element
        try:
            color_scale = instance.PhotometricInterpretation
        except AttributeError:
            color_scale = None
        is_greyscale = color_scale in ["MONOCHROME1", "MONOCHROME2"]

        return is_greyscale

    @staticmethod
    def _rescale_dcm_pixel_array(
        instance: pydicom.dataset.FileDataset, is_greyscale: bool
    ) -> np.ndarray:
        """Rescale DICOM pixel_array.

        :param instance: A singe DICOM instance.
        :param is_greyscale: FALSE if the Photometric Interpretation is RGB.

        :return: Rescaled DICOM pixel_array.
        """
        # Normalize contrast
        if "WindowWidth" in instance:
            if is_greyscale:
                image_2d = apply_voi_lut(instance.pixel_array, instance)
            else:
                image_2d = instance.pixel_array
        else:
            image_2d = instance.pixel_array

        # Convert to float to avoid overflow or underflow losses.
        image_2d_float = image_2d.astype(float)

        if not is_greyscale:
            image_2d_scaled = image_2d_float
        else:
            # Rescaling grey scale between 0-255
            image_2d_scaled = ((image_2d_float.max() - image_2d_float) / (
                    image_2d_float.max() - image_2d_float.min())) * 255.0

        # Convert to uint
        image_2d_scaled = np.uint8(image_2d_scaled)

        return image_2d_scaled

    @staticmethod
    def _save_pixel_array_as_png(
        pixel_array: np.array,
        is_greyscale: bool,
        output_file_name: str = "example",
        output_dir: str = "temp_dir",
    ) -> None:
        """Save the pixel data from a loaded DICOM instance as PNG.

        :param pixel_array: Pixel data from the instance.
        :param is_greyscale: True if image is greyscale.
        :param output_file_name: Name of output file (no file extension).
        :param output_dir: String path to output directory.
        """
        shape = pixel_array.shape

        # Write the PNG file
        os.makedirs(output_dir, exist_ok=True)
        if is_greyscale:
            with open(f"{output_dir}/{output_file_name}.png", "wb") as png_file:
                w = png.Writer(shape[1], shape[0], greyscale=True)
                w.write(png_file, pixel_array)
        else:
            with open(f"{output_dir}/{output_file_name}.png", "wb") as png_file:
                w = png.Writer(shape[1], shape[0], greyscale=False)
                # Semi-flatten the pixel array to RGB representation in 2D
                pixel_array = np.reshape(pixel_array, (shape[0], shape[1] * 3))
                w.write(png_file, pixel_array)

        return None

    @classmethod
    def _convert_dcm_to_png(cls, filepath: Path, output_dir: str = "temp_dir") -> tuple:
        """Convert DICOM image to PNG file.

        :param filepath: pathlib Path to a single dcm file.
        :param output_dir: String path to output directory.

        :return: Shape of pixel array and if image mode is greyscale.
        """
        ds = pydicom.dcmread(filepath)

        # Check if image is grayscale using the Photometric Interpretation element
        is_greyscale = cls._check_if_greyscale(ds)

        # Rescale pixel array
        image = cls._rescale_dcm_pixel_array(ds, is_greyscale)
        shape = image.shape

        # Write to PNG file
        cls._save_pixel_array_as_png(image, is_greyscale, filepath.stem, output_dir)

        return shape, is_greyscale

    @staticmethod
    def _get_bg_color(
        image: Image.Image, is_greyscale: bool, invert: bool = False
    ) -> Union[int, Tuple[int, int, int]]:
        """Select most common color as background color.

        :param image: Loaded PIL image.
        :param colorscale: Colorscale of image (e.g., 'grayscale', 'RGB')
        :param invert: TRUE if you want to get the inverse of the bg color.

        :return: Background color.
        """
        # Invert colors if invert flag is True
        if invert:
            if image.mode == "RGBA":
                # Handle transparency as needed
                r, g, b, a = image.split()
                rgb_image = Image.merge("RGB", (r, g, b))
                inverted_image = ImageOps.invert(rgb_image)
                r2, g2, b2 = inverted_image.split()

                image = Image.merge("RGBA", (r2, g2, b2, a))

            else:
                image = ImageOps.invert(image)

        # Get background color
        if is_greyscale:
            # Select most common color as color
            bg_color = int(np.bincount(list(image.getdata())).argmax())
        else:
            # Reduce size of image to 1 pixel to get dominant color
            tmp_image = image.copy()
            tmp_image = tmp_image.resize((1, 1), resample=0)
            bg_color = tmp_image.getpixel((0, 0))

        return bg_color

    @staticmethod
    def _get_array_corners(pixel_array: np.ndarray, crop_ratio: float) -> np.ndarray:
        """Crop a pixel array to just return the corners in a single array.

        :param pixel_array: Numpy array containing the pixel data.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.

        :return: Cropped input array.
        """
        if crop_ratio >= 1.0 or crop_ratio <= 0:
            raise ValueError("crop_ratio must be between 0 and 1")

        # Set dimensions
        width = pixel_array.shape[0]
        height = pixel_array.shape[1]
        crop_width = int(np.floor(width * crop_ratio / 2))
        crop_height = int(np.floor(height * crop_ratio / 2))

        # Get coordinates for corners
        # (left, top, right, bottom)
        box_top_left = (0, 0, crop_width, crop_height)
        box_top_right = (width - crop_width, 0, width, crop_height)
        box_bottom_left = (0, height - crop_height, crop_width, height)
        box_bottom_right = (width - crop_width, height - crop_height, width, height)
        boxes = [box_top_left, box_top_right, box_bottom_left, box_bottom_right]

        # Only keep box pixels
        cropped_pixel_arrays = [
            pixel_array[box[0] : box[2], box[1] : box[3]] for box in boxes
        ]

        # Combine the cropped pixel arrays
        cropped_array = np.vstack(cropped_pixel_arrays)

        return cropped_array

    @classmethod
    def _get_most_common_pixel_value(
        cls,
        instance: pydicom.dataset.FileDataset,
        crop_ratio: float,
        fill: str = "contrast",
    ) -> Union[int, Tuple[int, int, int]]:
        """Find the most common pixel value.

        :param instance: A singe DICOM instance.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param fill: Determines how box color is selected.
        'contrast' - Masks stand out relative to background.
        'background' - Masks are same color as background.

        :return: Most or least common pixel value (depending on fill).
        """
        # Crop down to just only look at image corners
        cropped_array = cls._get_array_corners(instance.pixel_array, crop_ratio)

        # Get flattened pixel array
        flat_pixel_array = np.array(cropped_array).flatten()

        is_greyscale = cls._check_if_greyscale(instance)
        if is_greyscale:
            # Get most common value
            values, counts = np.unique(flat_pixel_array, return_counts=True)
            flat_pixel_array = np.array(flat_pixel_array)
            common_value = values[np.argmax(counts)]
        else:
            raise TypeError(
                "Most common pixel value retrieval is only supported for greyscale images at this point."  # noqa: E501
            )

        # Invert color as necessary
        if fill.lower() in ["contrast", "invert", "inverted", "inverse"]:
            pixel_value = np.max(flat_pixel_array) - common_value
        elif fill.lower() in ["background", "bg"]:
            pixel_value = common_value

        return pixel_value

    @classmethod
    def _add_padding(
        cls,
        image: Image.Image,
        is_greyscale: bool,
        padding_width: int,
    ) -> Image.Image:
        """Add border to image using most common color.

        :param image: Loaded PIL image.
        :param is_greyscale: Whether image is in grayscale or not.
        :param padding_width: Pixel width of padding (uniform).

        :return: PIL image with padding.
        """
        # Check padding width value
        if padding_width <= 0:
            raise ValueError("Enter a positive value for padding")
        elif padding_width >= 100:
            raise ValueError(
                "Excessive padding width entered. Please use a width under 100 pixels."  # noqa: E501
            )

        # Select most common color as border color
        border_color = cls._get_bg_color(image, is_greyscale)

        # Add padding
        right = padding_width
        left = padding_width
        top = padding_width
        bottom = padding_width

        width, height = image.size

        new_width = width + right + left
        new_height = height + top + bottom

        image_with_padding = Image.new(
            image.mode, (new_width, new_height), border_color
        )
        image_with_padding.paste(image, (left, top))

        return image_with_padding

    @staticmethod
    def _copy_files_for_processing(src_path: str, dst_parent_dir: str) -> Path:
        """Copy DICOM files. All processing should be done on the copies.

        :param src_path: String path to DICOM file or directory containing DICOM files.
        :param dst_parent_dir: String path to parent directory of output location.

        :return: Output location of the file(s).
        """
        # Identify output path
        tail = list(Path(src_path).parts)[-1]
        dst_path = Path(dst_parent_dir, tail)

        # Copy file(s)
        if Path(src_path).is_dir() is True:
            try:
                shutil.copytree(src_path, dst_path)
            except FileExistsError:
                raise FileExistsError(
                    "Destination files already exist. Please clear the destination files or specify a different dst_parent_dir."  # noqa: E501
                )
        elif Path(src_path).is_file() is True:
            # Create the output dir manually if working with a single file
            os.makedirs(Path(dst_path).parent, exist_ok=True)
            shutil.copyfile(src_path, dst_path)
        else:
            raise FileNotFoundError(f"{src_path} does not exist")

        return dst_path

    @staticmethod
    def _get_text_metadata(
        instance: pydicom.dataset.FileDataset,
    ) -> Tuple[list, list, list]:
        """Retrieve all text metadata from the DICOM image.

        :param instance: Loaded DICOM instance.

        :return: List of all the instance's element values (excluding pixel data),
        bool for if the element is specified as being a name,
        bool for if the element is specified as being related to the patient.
        """
        metadata_text = list()
        is_name = list()
        is_patient = list()

        for element in instance:
            # Save all metadata except the DICOM image itself
            if element.name != "Pixel Data":
                # Save the metadata
                metadata_text.append(element.value)

                # Track whether this particular element is a name
                if "name" in element.name.lower():
                    is_name.append(True)
                else:
                    is_name.append(False)

                # Track whether this particular element is directly tied to the patient
                if "patient" in element.name.lower():
                    is_patient.append(True)
                else:
                    is_patient.append(False)
            else:
                metadata_text.append("")
                is_name.append(False)
                is_patient.append(False)

        return metadata_text, is_name, is_patient

    @staticmethod
    def augment_word(word: str, case_sensitive: bool = False) -> list:
        """Apply multiple types of casing to the provided string.

        :param words: String containing the word or term of interest.
        :param case_sensitive: True if we want to preserve casing.

        :return: List of the same string with different casings and spacing.
        """
        word_list = []
        if word != "":
            # Replacing separator character with space, if any
            text_no_separator = word.replace("^", " ")
            text_no_separator = text_no_separator.replace("-", " ")
            text_no_separator = " ".join(text_no_separator.split())

            if case_sensitive:
                word_list.append(text_no_separator)
                word_list.extend(
                    [
                        text_no_separator.split(" "),
                    ]
                )
            else:
                # Capitalize all characters in string
                text_upper = text_no_separator.upper()

                # Lowercase all characters in string
                text_lower = text_no_separator.lower()

                # Capitalize first letter in each part of string
                text_title = text_no_separator.title()

                # Append iterations
                word_list.extend(
                    [text_no_separator, text_upper, text_lower, text_title]
                )

                # Adding each term as a separate item in the list
                word_list.extend(
                    [
                        text_no_separator.split(" "),
                        text_upper.split(" "),
                        text_lower.split(" "),
                        text_title.split(" "),
                    ]
                )

            # Flatten list
            flat_list = []
            for item in word_list:
                if isinstance(item, list):
                    flat_list.extend(item)
                else:
                    flat_list.append(item)

            # Remove any duplicates and empty strings
            word_list = list(set(flat_list))
            word_list = list(filter(None, word_list))

        return word_list

    @classmethod
    def _process_names(cls, text_metadata: list, is_name: list) -> list:
        """Process names to have multiple iterations in our PHI list.

        :param metadata_text: List of all the instance's element values
        (excluding pixel data).
        :param is_name: True if the element is specified as being a name.

        :return: Metadata text with additional name iterations appended.
        """
        phi_list = text_metadata.copy()

        for i in range(0, len(text_metadata)):
            if is_name[i] is True:
                original_text = str(text_metadata[i])
                phi_list += cls.augment_word(original_text)

        return phi_list

    @staticmethod
    def _add_known_generic_phi(phi_list: list) -> list:
        """Add known potential generic PHI values.

        :param phi_list: List of PHI to use with Presidio ad-hoc recognizer.

        :return: Same list with added known values.
        """
        known_generic_phi = ["[M]", "[F]", "[X]", "[U]", "M", "F", "X", "U"]
        phi_list.extend(known_generic_phi)

        return phi_list

    @classmethod
    def _make_phi_list(
        cls,
        original_metadata: List[Union[pydicom.multival.MultiValue, list, tuple]],
        is_name: List[bool],
        is_patient: List[bool],
    ) -> list:
        """Make the list of PHI to use in Presidio ad-hoc recognizer.

        :param original_metadata: List of all the instance's element values
        (excluding pixel data).
        :param is_name: True if the element is specified as being a name.
        :param is_patient: True if the element is specified as being
        related to the patient.

        :return: List of PHI (str) to use with Presidio ad-hoc recognizer.
        """
        # Process names
        phi_list = cls._process_names(original_metadata, is_name)

        # Add known potential phi values
        phi_list = cls._add_known_generic_phi(phi_list)

        # Flatten any nested lists
        for phi in phi_list:
            if type(phi) in [pydicom.multival.MultiValue, list, tuple]:
                for item in phi:
                    phi_list.append(item)
                phi_list.remove(phi)

        # Convert all items to strings
        phi_str_list = [str(phi) for phi in phi_list]

        # Remove duplicates
        phi_str_list = list(set(phi_str_list))

        return phi_str_list

    @classmethod
    def _set_bbox_color(
        cls, instance: pydicom.dataset.FileDataset, fill: str
    ) -> Union[int, Tuple[int, int, int]]:
        """Set the bounding box color.

        :param instance: A single DICOM instance.
        :param fill: Determines how box color is selected.
        'contrast' - Masks stand out relative to background.
        'background' - Masks are same color as background.

        :return: int or tuple of int values determining masking box color.
        """
        # Check if we want the box color to contrast with the background
        if fill.lower() in ["contrast", "invert", "inverted", "inverse"]:
            invert_flag = True
        elif fill.lower() in ["background", "bg"]:
            invert_flag = False
        else:
            raise ValueError("fill must be 'contrast' or 'background'")

        # Temporarily save as PNG to get color
        with tempfile.TemporaryDirectory() as tmpdirname:
            dst_path = Path(f"{tmpdirname}/temp.dcm")
            instance.save_as(dst_path)
            _, is_greyscale = cls._convert_dcm_to_png(dst_path, output_dir=tmpdirname)

            png_filepath = f"{tmpdirname}/{dst_path.stem}.png"
            loaded_image = Image.open(png_filepath)
            box_color = cls._get_bg_color(loaded_image, is_greyscale, invert_flag)

        return box_color

    @staticmethod
    def _check_if_compressed(instance: pydicom.dataset.FileDataset) -> bool:
        """Check if the pixel data is compressed.

        :param instance: DICOM instance.

        :return: Boolean for whether the pixel data is compressed.
        """
        # Calculate expected bytes
        rows = instance.Rows
        columns = instance.Columns
        samples_per_pixel = instance.SamplesPerPixel
        bits_allocated = instance.BitsAllocated
        try:
            number_of_frames = instance[0x0028, 0x0008].value
        except KeyError:
            number_of_frames = 1
        expected_num_bytes = (
            rows * columns * number_of_frames * samples_per_pixel * (bits_allocated / 8)
        )

        # Compare expected vs actual
        is_compressed = (int(expected_num_bytes)) > len(instance.PixelData)

        return is_compressed

    @staticmethod
    def _compress_pixel_data(
        instance: pydicom.dataset.FileDataset,
    ) -> pydicom.dataset.FileDataset:
        """Recompress pixel data that was decompressed during redaction.

        :param instance: Loaded DICOM instance.

        :return: Instance with compressed pixel data.
        """
        compression_method = pydicom.uid.RLELossless

        # Temporarily change syntax to an "uncompressed" method
        instance.file_meta.TransferSyntaxUID = pydicom.uid.UID("1.2.840.10008.1.2")

        # Compress and update syntax
        instance.compress(compression_method, encoding_plugin="gdcm")
        instance.file_meta.TransferSyntaxUID = compression_method

        return instance

    @staticmethod
    def _check_if_has_image_icon_sequence(
        instance: pydicom.dataset.FileDataset,
    ) -> bool:
        """Check if there is an image icon sequence tag in the metadata.

        This leads to pixel data being present in multiple locations.

        :param instance: DICOM instance.

        :return: Boolean for whether the instance has an image icon sequence tag.
        """
        has_image_icon_sequence = False
        try:
            _ = instance[0x0088, 0x0200]
            has_image_icon_sequence = True
        except KeyError:
            has_image_icon_sequence = False

        return has_image_icon_sequence

    @classmethod
    def _add_redact_box(
        cls,
        instance: pydicom.dataset.FileDataset,
        bounding_boxes_coordinates: list,
        crop_ratio: float,
        fill: str = "contrast",
    ) -> pydicom.dataset.FileDataset:
        """Add redaction bounding boxes on a DICOM instance.

        :param instance: A single DICOM instance.
        :param bounding_boxes_coordinates: Bounding box coordinates.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param fill: Determines how box color is selected.
        'contrast' - Masks stand out relative to background.
        'background' - Masks are same color as background.

        :return: A new dicom instance with redaction bounding boxes.
        """
        # Copy instance
        redacted_instance = deepcopy(instance)
        is_compressed = cls._check_if_compressed(redacted_instance)
        has_image_icon_sequence = cls._check_if_has_image_icon_sequence(
            redacted_instance
        )

        # Select masking box color
        is_greyscale = cls._check_if_greyscale(instance)
        if is_greyscale:
            box_color = cls._get_most_common_pixel_value(instance, crop_ratio, fill)
        else:
            box_color = cls._set_bbox_color(redacted_instance, fill)

        # Apply mask
        for i in range(0, len(bounding_boxes_coordinates)):
            bbox = bounding_boxes_coordinates[i]
            top = bbox["top"]
            left = bbox["left"]
            width = bbox["width"]
            height = bbox["height"]
            redacted_instance.pixel_array[
                top : top + height, left : left + width
            ] = box_color

        redacted_instance.PixelData = redacted_instance.pixel_array.tobytes()

        # If original pixel data is compressed, recompress after redaction
        if is_compressed or has_image_icon_sequence:
            # Temporary "fix" to manually set all YBR photometric interp as YBR_FULL
            if "YBR" in redacted_instance.PhotometricInterpretation:
                redacted_instance.PhotometricInterpretation = "YBR_FULL"
            redacted_instance = cls._compress_pixel_data(redacted_instance)

        return redacted_instance

    def _get_analyzer_results(
        self,
        image: Image.Image,
        instance: pydicom.dataset.FileDataset,
        use_metadata: bool,
        ocr_kwargs: Optional[dict],
        ad_hoc_recognizers: Optional[List[PatternRecognizer]],
        **text_analyzer_kwargs,
    ) -> List[ImageRecognizerResult]:
        """Analyze image with selected redaction approach.

        :param image: DICOM pixel data as PIL image.
        :param instance: DICOM instance (with metadata).
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine (e.g., allow_list).

        :return: Analyzer results.
        """
        # Check the ad-hoc recognizers list
        self._check_ad_hoc_recognizer_list(ad_hoc_recognizers)

        # Create custom recognizer using DICOM metadata
        if use_metadata:
            original_metadata, is_name, is_patient = self._get_text_metadata(instance)
            phi_list = self._make_phi_list(original_metadata, is_name, is_patient)
            deny_list_recognizer = PatternRecognizer(
                supported_entity="PERSON", deny_list=phi_list
            )

            if ad_hoc_recognizers is None:
                ad_hoc_recognizers = [deny_list_recognizer]
            elif type(ad_hoc_recognizers) is list:
                ad_hoc_recognizers.append(deny_list_recognizer)

        # Detect PII
        if ad_hoc_recognizers is None:
            analyzer_results = self.image_analyzer_engine.analyze(
                image,
                ocr_kwargs=ocr_kwargs,
                **text_analyzer_kwargs,
            )
        else:
            analyzer_results = self.image_analyzer_engine.analyze(
                image,
                ocr_kwargs=ocr_kwargs,
                ad_hoc_recognizers=ad_hoc_recognizers,
                **text_analyzer_kwargs,
            )

        return analyzer_results

    @staticmethod
    def _save_bbox_json(output_dcm_path: str, bboxes: List[Dict[str, int]]) -> None:
        """Save the redacted bounding box info as a json file.

        :param output_dcm_path: Path to the redacted DICOM file.

        :param bboxes: Bounding boxes used in redaction.
        """
        output_json_path = Path(output_dcm_path).with_suffix(".json")

        with open(output_json_path, "w") as write_file:
            json.dump(bboxes, write_file, indent=4)

    def _redact_single_dicom_image(
        self,
        dcm_path: str,
        crop_ratio: float,
        fill: str,
        padding_width: int,
        use_metadata: bool,
        overwrite: bool,
        dst_parent_dir: str,
        save_bboxes: bool,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> str:
        """Redact text PHI present on a DICOM image.

        :param dcm_path: String path to the DICOM file.
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param fill: Color setting to use for bounding boxes
        ("contrast" or "background").
        :param padding_width: Pixel width of padding (uniform).
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param overwrite: Only set to True if you are providing the
        duplicated DICOM path in dcm_path.
        :param dst_parent_dir: String path to parent directory of where to store copies.
        :param save_bboxes: True if we want to save boundings boxes.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.

        :return: Path to the output DICOM file.
        """
        # Ensure we are working on a single file
        if Path(dcm_path).is_dir():
            raise FileNotFoundError("Please ensure dcm_path is a single file")
        elif Path(dcm_path).is_file() is False:
            raise FileNotFoundError(f"{dcm_path} does not exist")

        # Copy file before processing if overwrite==False
        if overwrite is False:
            dst_path = self._copy_files_for_processing(dcm_path, dst_parent_dir)
        else:
            dst_path = dcm_path

        # Load instance
        instance = pydicom.dcmread(dst_path)

        try:
            instance.PixelData
        except AttributeError:
            raise AttributeError("Provided DICOM file lacks pixel data.")

        # Load image for processing
        with tempfile.TemporaryDirectory() as tmpdirname:
            # Convert DICOM to PNG and add padding for OCR (during analysis)
            _, is_greyscale = self._convert_dcm_to_png(dst_path, output_dir=tmpdirname)
            png_filepath = f"{tmpdirname}/{dst_path.stem}.png"
            loaded_image = Image.open(png_filepath)
            image = self._add_padding(loaded_image, is_greyscale, padding_width)

        # Detect PII
        analyzer_results = self._get_analyzer_results(
            image,
            instance,
            use_metadata,
            ocr_kwargs,
            ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )

        # Redact all bounding boxes from DICOM file
        analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
            analyzer_results
        )
        bboxes = self.bbox_processor.remove_bbox_padding(analyzer_bboxes, padding_width)
        redacted_dicom_instance = self._add_redact_box(
            instance, bboxes, crop_ratio, fill
        )
        redacted_dicom_instance.save_as(dst_path)

        # Save redacted bboxes
        if save_bboxes:
            self._save_bbox_json(dst_path, bboxes)

        return dst_path

    def _redact_multiple_dicom_images(
        self,
        dcm_dir: str,
        crop_ratio: float,
        fill: str,
        padding_width: int,
        use_metadata: bool,
        overwrite: bool,
        dst_parent_dir: str,
        save_bboxes: bool,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> str:
        """Redact text PHI present on all DICOM images in a directory.

        :param dcm_dir: String path to directory containing DICOM files (can be nested).
        :param crop_ratio: Portion of image to consider when selecting
        most common pixel value as the background color value.
        :param fill: Color setting to use for bounding boxes
        ("contrast" or "background").
        :param padding_width: Pixel width of padding (uniform).
        :param use_metadata: Whether to redact text in the image that
        are present in the metadata.
        :param overwrite: Only set to True if you are providing
        the duplicated DICOM dir in dcm_dir.
        :param dst_parent_dir: String path to parent directory of where to store copies.
        :param save_bboxes: True if we want to save boundings boxes.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.

        Return:
            dst_dir (str): Path to the output DICOM directory.
        """
        # Ensure we are working on a directory (can have sub-directories)
        if Path(dcm_dir).is_file():
            raise FileNotFoundError("Please ensure dcm_path is a directory")
        elif Path(dcm_dir).is_dir() is False:
            raise FileNotFoundError(f"{dcm_dir} does not exist")

        # List of files to process directly
        if overwrite is False:
            dst_dir = self._copy_files_for_processing(dcm_dir, dst_parent_dir)
        else:
            dst_dir = dcm_dir

        # Process each DICOM file directly
        all_dcm_files = self._get_all_dcm_files(Path(dst_dir))
        for dst_path in all_dcm_files:
            self._redact_single_dicom_image(
                dst_path,
                crop_ratio,
                fill,
                padding_width,
                use_metadata,
                overwrite,
                dst_parent_dir,
                save_bboxes,
                ocr_kwargs=ocr_kwargs,
                ad_hoc_recognizers=ad_hoc_recognizers,
                **text_analyzer_kwargs,
            )

        return dst_dir

augment_word(word, case_sensitive=False) staticmethod

Apply multiple types of casing to the provided string.

Parameters:

Name Type Description Default
words

String containing the word or term of interest.

required
case_sensitive bool

True if we want to preserve casing.

False

Returns:

Type Description
list

List of the same string with different casings and spacing.

Source code in presidio_image_redactor/dicom_image_redactor_engine.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
@staticmethod
def augment_word(word: str, case_sensitive: bool = False) -> list:
    """Apply multiple types of casing to the provided string.

    :param words: String containing the word or term of interest.
    :param case_sensitive: True if we want to preserve casing.

    :return: List of the same string with different casings and spacing.
    """
    word_list = []
    if word != "":
        # Replacing separator character with space, if any
        text_no_separator = word.replace("^", " ")
        text_no_separator = text_no_separator.replace("-", " ")
        text_no_separator = " ".join(text_no_separator.split())

        if case_sensitive:
            word_list.append(text_no_separator)
            word_list.extend(
                [
                    text_no_separator.split(" "),
                ]
            )
        else:
            # Capitalize all characters in string
            text_upper = text_no_separator.upper()

            # Lowercase all characters in string
            text_lower = text_no_separator.lower()

            # Capitalize first letter in each part of string
            text_title = text_no_separator.title()

            # Append iterations
            word_list.extend(
                [text_no_separator, text_upper, text_lower, text_title]
            )

            # Adding each term as a separate item in the list
            word_list.extend(
                [
                    text_no_separator.split(" "),
                    text_upper.split(" "),
                    text_lower.split(" "),
                    text_title.split(" "),
                ]
            )

        # Flatten list
        flat_list = []
        for item in word_list:
            if isinstance(item, list):
                flat_list.extend(item)
            else:
                flat_list.append(item)

        # Remove any duplicates and empty strings
        word_list = list(set(flat_list))
        word_list = list(filter(None, word_list))

    return word_list

redact(image, fill='contrast', padding_width=25, crop_ratio=0.75, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Redact method to redact the given DICOM image.

Please note, this method duplicates the image, creates a new instance and manipulates it.

Parameters:

Name Type Description Default
image FileDataset

Loaded DICOM instance including pixel data and metadata.

required
fill str

Fill setting to use for redaction box ("contrast" or "background").

'contrast'
padding_width int

Padding width to use when running OCR.

25
crop_ratio float

Portion of image to consider when selecting most common pixel value as the background color value.

0.75
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in AnalyzerEngine.

{}

Returns:

Type Description
FileDataset

DICOM instance with redacted pixel data.

Source code in presidio_image_redactor/dicom_image_redactor_engine.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def redact(
    self,
    image: pydicom.dataset.FileDataset,
    fill: str = "contrast",
    padding_width: int = 25,
    crop_ratio: float = 0.75,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> pydicom.dataset.FileDataset:
    """Redact method to redact the given DICOM image.

    Please note, this method duplicates the image, creates a
    new instance and manipulates it.

    :param image: Loaded DICOM instance including pixel data and metadata.
    :param fill: Fill setting to use for redaction box ("contrast" or "background").
    :param padding_width: Padding width to use when running OCR.
    :param crop_ratio: Portion of image to consider when selecting
    most common pixel value as the background color value.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in AnalyzerEngine.

    :return: DICOM instance with redacted pixel data.
    """
    redacted_image, _ = self.redact_and_return_bbox(
        image=image,
        fill=fill,
        padding_width=padding_width,
        crop_ratio=crop_ratio,
        ocr_kwargs=ocr_kwargs,
        ad_hoc_recognizers=ad_hoc_recognizers,
        **text_analyzer_kwargs,
    )

    return redacted_image

redact_and_return_bbox(image, fill='contrast', padding_width=25, crop_ratio=0.75, use_metadata=True, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Redact method to redact the given DICOM image and return redacted bboxes.

Please note, this method duplicates the image, creates a new instance and manipulates it.

Parameters:

Name Type Description Default
image FileDataset

Loaded DICOM instance including pixel data and metadata.

required
fill str

Fill setting to use for redaction box ("contrast" or "background").

'contrast'
padding_width int

Padding width to use when running OCR.

25
crop_ratio float

Portion of image to consider when selecting most common pixel value as the background color value.

0.75
use_metadata bool

Whether to redact text in the image that are present in the metadata.

True
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in AnalyzerEngine.

{}

Returns:

Type Description
Tuple[FileDataset, List[Dict[str, int]]]

DICOM instance with redacted pixel data.

Source code in presidio_image_redactor/dicom_image_redactor_engine.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def redact_and_return_bbox(
    self,
    image: pydicom.dataset.FileDataset,
    fill: str = "contrast",
    padding_width: int = 25,
    crop_ratio: float = 0.75,
    use_metadata: bool = True,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> Tuple[pydicom.dataset.FileDataset, List[Dict[str, int]]]:
    """Redact method to redact the given DICOM image and return redacted bboxes.

    Please note, this method duplicates the image, creates a
    new instance and manipulates it.

    :param image: Loaded DICOM instance including pixel data and metadata.
    :param fill: Fill setting to use for redaction box ("contrast" or "background").
    :param padding_width: Padding width to use when running OCR.
    :param crop_ratio: Portion of image to consider when selecting
    most common pixel value as the background color value.
    :param use_metadata: Whether to redact text in the image that
    are present in the metadata.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in AnalyzerEngine.

    :return: DICOM instance with redacted pixel data.
    """
    # Check input
    if type(image) not in [pydicom.dataset.FileDataset, pydicom.dataset.Dataset]:
        raise TypeError("The provided image must be a loaded DICOM instance.")
    try:
        image.PixelData
    except AttributeError as e:
        raise AttributeError(f"Provided DICOM instance lacks pixel data: {e}")
    except PermissionError as e:
        raise PermissionError(f"Unable to access pixel data (may not exist): {e}")
    except IsADirectoryError as e:
        raise IsADirectoryError(f"DICOM instance is a directory: {e}")

    instance = deepcopy(image)

    # Load image for processing
    with tempfile.TemporaryDirectory() as tmpdirname:
        # Convert DICOM to PNG and add padding for OCR (during analysis)
        is_greyscale = self._check_if_greyscale(instance)
        image = self._rescale_dcm_pixel_array(instance, is_greyscale)
        image_name = str(uuid.uuid4())
        self._save_pixel_array_as_png(image, is_greyscale, image_name, tmpdirname)

        png_filepath = f"{tmpdirname}/{image_name}.png"
        loaded_image = Image.open(png_filepath)
        image = self._add_padding(loaded_image, is_greyscale, padding_width)

    # Detect PII
    analyzer_results = self._get_analyzer_results(
        image,
        instance,
        use_metadata,
        ocr_kwargs,
        ad_hoc_recognizers,
        **text_analyzer_kwargs,
    )

    # Redact all bounding boxes from DICOM file
    analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
        analyzer_results
    )
    bboxes = self.bbox_processor.remove_bbox_padding(analyzer_bboxes, padding_width)
    redacted_image = self._add_redact_box(instance, bboxes, crop_ratio, fill)

    return redacted_image, bboxes

redact_from_directory(input_dicom_path, output_dir, padding_width=25, crop_ratio=0.75, fill='contrast', use_metadata=True, save_bboxes=False, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Redact method to redact from a directory of files.

Please notice, this method duplicates the files, creates new instances and manipulate them.

Parameters:

Name Type Description Default
input_dicom_path str

String path to directory of DICOM images.

required
output_dir str

String path to parent output directory.

required
padding_width

Padding width to use when running OCR.

required
crop_ratio float

Portion of image to consider when selecting most common pixel value as the background color value.

0.75
fill str

Color setting to use for redaction box ("contrast" or "background").

'contrast'
use_metadata bool

Whether to redact text in the image that are present in the metadata.

True
save_bboxes bool

True if we want to save boundings boxes.

False
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in AnalyzerEngine.

{}
Source code in presidio_image_redactor/dicom_image_redactor_engine.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def redact_from_directory(
    self,
    input_dicom_path: str,
    output_dir: str,
    padding_width: int = 25,
    crop_ratio: float = 0.75,
    fill: str = "contrast",
    use_metadata: bool = True,
    save_bboxes: bool = False,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> None:
    """Redact method to redact from a directory of files.

    Please notice, this method duplicates the files, creates
    new instances and manipulate them.

    :param input_dicom_path: String path to directory of DICOM images.
    :param output_dir: String path to parent output directory.
    :param padding_width : Padding width to use when running OCR.
    :param crop_ratio: Portion of image to consider when selecting
    most common pixel value as the background color value.
    :param fill: Color setting to use for redaction box
    ("contrast" or "background").
    :param use_metadata: Whether to redact text in the image that
    are present in the metadata.
    :param save_bboxes: True if we want to save boundings boxes.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in AnalyzerEngine.
    """
    # Verify the given paths
    if Path(input_dicom_path).is_dir() is False:
        raise TypeError("input_dicom_path must be a valid directory")
    if Path(input_dicom_path).is_file() is True:
        raise TypeError("input_dicom_path must be a directory (not file)")
    if Path(output_dir).is_file() is True:
        raise TypeError(
            "output_dir must be a directory (does not need to exist yet)"
        )

    # Create duplicates
    dst_path = self._copy_files_for_processing(input_dicom_path, output_dir)

    # Process DICOM files
    output_location = self._redact_multiple_dicom_images(
        dcm_dir=dst_path,
        crop_ratio=crop_ratio,
        fill=fill,
        padding_width=padding_width,
        use_metadata=use_metadata,
        ad_hoc_recognizers=ad_hoc_recognizers,
        overwrite=True,
        dst_parent_dir=".",
        save_bboxes=save_bboxes,
        ocr_kwargs=ocr_kwargs,
        **text_analyzer_kwargs,
    )

    print(f"Output written to {output_location}")

    return None

redact_from_file(input_dicom_path, output_dir, padding_width=25, crop_ratio=0.75, fill='contrast', use_metadata=True, save_bboxes=False, verbose=True, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Redact method to redact from a given file.

Please notice, this method duplicates the file, creates new instance and manipulate them.

Parameters:

Name Type Description Default
input_dicom_path str

String path to DICOM image.

required
output_dir str

String path to parent output directory.

required
padding_width

Padding width to use when running OCR.

required
fill str

Color setting to use for redaction box ("contrast" or "background").

'contrast'
use_metadata bool

Whether to redact text in the image that are present in the metadata.

True
save_bboxes bool

True if we want to save boundings boxes.

False
verbose bool

True to print where redacted file was written to.

True
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in AnalyzerEngine.

{}
Source code in presidio_image_redactor/dicom_image_redactor_engine.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def redact_from_file(
    self,
    input_dicom_path: str,
    output_dir: str,
    padding_width: int = 25,
    crop_ratio: float = 0.75,
    fill: str = "contrast",
    use_metadata: bool = True,
    save_bboxes: bool = False,
    verbose: bool = True,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> None:
    """Redact method to redact from a given file.

    Please notice, this method duplicates the file, creates
    new instance and manipulate them.

    :param input_dicom_path: String path to DICOM image.
    :param output_dir: String path to parent output directory.
    :param padding_width : Padding width to use when running OCR.
    :param fill: Color setting to use for redaction box
    ("contrast" or "background").
    :param use_metadata: Whether to redact text in the image that
    are present in the metadata.
    :param save_bboxes: True if we want to save boundings boxes.
    :param verbose: True to print where redacted file was written to.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in AnalyzerEngine.
    """
    # Verify the given paths
    if Path(input_dicom_path).is_dir() is True:
        raise TypeError("input_dicom_path must be file (not dir)")
    if Path(input_dicom_path).is_file() is False:
        raise TypeError("input_dicom_path must be a valid file")
    if Path(output_dir).is_file() is True:
        raise TypeError(
            "output_dir must be a directory (does not need to exist yet)"
        )

    # Create duplicate
    dst_path = self._copy_files_for_processing(input_dicom_path, output_dir)

    # Process DICOM file
    output_location = self._redact_single_dicom_image(
        dcm_path=dst_path,
        crop_ratio=crop_ratio,
        fill=fill,
        padding_width=padding_width,
        use_metadata=use_metadata,
        overwrite=True,
        dst_parent_dir=".",
        save_bboxes=save_bboxes,
        ocr_kwargs=ocr_kwargs,
        ad_hoc_recognizers=ad_hoc_recognizers,
        **text_analyzer_kwargs,
    )

    if verbose:
        print(f"Output written to {output_location}")

    return None

DocumentIntelligenceOCR

Bases: OCR

OCR class that uses Azure AI Document Intelligence OCR engine.

Parameters:

Name Type Description Default
key Optional[str]

The API key

None
endpoint Optional[str]

The API endpoint

None
model_id Optional[str]

Which model to use For details, see https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/

'prebuilt-document'
Source code in presidio_image_redactor/document_intelligence_ocr.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
class DocumentIntelligenceOCR(OCR):
    """OCR class that uses Azure AI Document Intelligence OCR engine.

    :param key: The API key
    :param endpoint: The API endpoint
    :param model_id: Which model to use

    For details, see
    https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/
    """

    SUPPORTED_MODELS = [
        "prebuilt-document",
        "prebuilt-read",
        "prebuilt-layout",
        "prebuilt-contract",
        "prebuilt-healthInsuranceCard.us",
        "prebuilt-invoice",
        "prebuilt-receipt",
        "prebuilt-idDocument",
        "prebuilt-businessCard"
    ]

    def __init__(self,
                 endpoint: Optional[str] = None,
                 key: Optional[str] = None,
                 model_id: Optional[str] = "prebuilt-document"):
        if model_id not in DocumentIntelligenceOCR.SUPPORTED_MODELS:
            raise ValueError("Unsupported model id: %s" % model_id)

        # If endpoint and/or key are not passed, attempt to get from environment
        # variables
        if not endpoint:
            endpoint = os.getenv("DOCUMENT_INTELLIGENCE_ENDPOINT")

        if not key:
            key = os.getenv("DOCUMENT_INTELLIGENCE_KEY")

        if not key or not endpoint:
            raise ValueError("Endpoint and key must be specified")

        self.client = DocumentAnalysisClient(
            endpoint=endpoint,
            credential=AzureKeyCredential(key)
        )
        self.model_id = model_id

    @staticmethod
    def _polygon_to_bbox(polygon : Sequence[Point]) -> tuple:
        """Convert polygon to a tuple of left/top/width/height.

        The returned bounding box should entirely cover the passed polygon.

        :param polygon: A sequence of points

        :return a tuple of left/top/width/height in pixel dimensions

        """
        # We need at least two points for a valid bounding box.
        if len(polygon) < 2:
            return (0, 0, 0, 0)

        left = min([int(p.x) for p in polygon])
        top = min([int(p.y) for p in polygon])
        right = max([int(p.x) for p in polygon])
        bottom = max([int(p.y) for p in polygon])
        width = right - left
        height = bottom - top
        return (left, top, width, height)

    @staticmethod
    def _page_to_bboxes(page: DocumentPage) -> dict:
        """Convert bounding boxes to uniform format.

        Presidio supports tesseract format of output only, so we format in the same
        way.
        Expected format looks like:
        {
            "left": [123, 345],
            "top": [0, 15],
            "width": [100, 75],
            "height": [25, 30],
            "conf": ["1", "0.87"],
            "text": ["JOHN", "DOE"],
        }

        :param page: The documentpage object from the DI client library

        :return dictionary in the expected format for presidio
        """
        bounds = [DocumentIntelligenceOCR._polygon_to_bbox(word.polygon)
                  for word in page.words]

        return {
            "left": [box[0] for box in bounds],
            "top": [box[1] for box in bounds],
            "width": [box[2] for box in bounds],
            "height": [box[3] for box in bounds],
            "conf": [w.confidence for w in page.words],
            "text": [w.content for w in page.words]
        }

    def get_imgbytes(self, image: Union[bytes, np.ndarray, Image.Image]) -> bytes:
        """Retrieve the image bytes from the image object.

        :param image:  Any of bytes/numpy array /PIL image object

        :return raw image bytes
        """
        if isinstance(image, bytes):
            return image
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)
            # Fallthrough to process PIL image
        if isinstance(image, Image.Image):
            # Image is a PIL image, write to bytes stream
            ostream = BytesIO()
            image.save(ostream, 'PNG')
            imgbytes = ostream.getvalue()
        elif isinstance(image, str):
            # image is a filename
            imgbytes = open(image, "rb")
        else:
            raise ValueError("Unsupported image type: %s" % type(image))
        return imgbytes

    def analyze_document(self, imgbytes : bytes, **kwargs) -> AnalyzedDocument:
        """Analyze the document and return the result.

        :param imgbytes: The bytes to send to the API endpoint
        :param kwargs: additional arguments for begin_analyze_document

        :return the result of the poller, an AnalyzedDocument object.
        """
        poller = self.client.begin_analyze_document(self.model_id, imgbytes, **kwargs)
        return poller.result()

    def perform_ocr(self, image: object, **kwargs) -> dict:
        """Perform OCR on the image.

        :param image: PIL Image/numpy array or file path(str) to be processed
        :param kwargs: Additional values for begin_analyze_document

        :return: results dictionary containing bboxes and text for each detected word
        """
        imgbytes = self.get_imgbytes(image)
        result = self.analyze_document(imgbytes, **kwargs)

        # Currently cannot handle more than one page.
        if not (len(result.pages) == 1):
            raise ValueError("DocumentIntelligenceOCR only supports 1 page documents")

        return DocumentIntelligenceOCR._page_to_bboxes(result.pages[0])

analyze_document(imgbytes, **kwargs)

Analyze the document and return the result.

Parameters:

Name Type Description Default
imgbytes bytes

The bytes to send to the API endpoint

required
kwargs

additional arguments for begin_analyze_document

{}
Source code in presidio_image_redactor/document_intelligence_ocr.py
144
145
146
147
148
149
150
151
152
153
def analyze_document(self, imgbytes : bytes, **kwargs) -> AnalyzedDocument:
    """Analyze the document and return the result.

    :param imgbytes: The bytes to send to the API endpoint
    :param kwargs: additional arguments for begin_analyze_document

    :return the result of the poller, an AnalyzedDocument object.
    """
    poller = self.client.begin_analyze_document(self.model_id, imgbytes, **kwargs)
    return poller.result()

get_imgbytes(image)

Retrieve the image bytes from the image object.

Parameters:

Name Type Description Default
image Union[bytes, ndarray, Image]

Any of bytes/numpy array /PIL image object

required
Source code in presidio_image_redactor/document_intelligence_ocr.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def get_imgbytes(self, image: Union[bytes, np.ndarray, Image.Image]) -> bytes:
    """Retrieve the image bytes from the image object.

    :param image:  Any of bytes/numpy array /PIL image object

    :return raw image bytes
    """
    if isinstance(image, bytes):
        return image
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)
        # Fallthrough to process PIL image
    if isinstance(image, Image.Image):
        # Image is a PIL image, write to bytes stream
        ostream = BytesIO()
        image.save(ostream, 'PNG')
        imgbytes = ostream.getvalue()
    elif isinstance(image, str):
        # image is a filename
        imgbytes = open(image, "rb")
    else:
        raise ValueError("Unsupported image type: %s" % type(image))
    return imgbytes

perform_ocr(image, **kwargs)

Perform OCR on the image.

Parameters:

Name Type Description Default
image object

PIL Image/numpy array or file path(str) to be processed

required
kwargs

Additional values for begin_analyze_document

{}

Returns:

Type Description
dict

results dictionary containing bboxes and text for each detected word

Source code in presidio_image_redactor/document_intelligence_ocr.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def perform_ocr(self, image: object, **kwargs) -> dict:
    """Perform OCR on the image.

    :param image: PIL Image/numpy array or file path(str) to be processed
    :param kwargs: Additional values for begin_analyze_document

    :return: results dictionary containing bboxes and text for each detected word
    """
    imgbytes = self.get_imgbytes(image)
    result = self.analyze_document(imgbytes, **kwargs)

    # Currently cannot handle more than one page.
    if not (len(result.pages) == 1):
        raise ValueError("DocumentIntelligenceOCR only supports 1 page documents")

    return DocumentIntelligenceOCR._page_to_bboxes(result.pages[0])

ImageAnalyzerEngine

ImageAnalyzerEngine class.

Parameters:

Name Type Description Default
analyzer_engine Optional[AnalyzerEngine]

The Presidio AnalyzerEngine instance to be used to detect PII in text

None
ocr Optional[OCR]

the OCR object to be used to detect text in images.

None
image_preprocessor Optional[ImagePreprocessor]

The ImagePreprocessor object to be used to preprocess the image

None
Source code in presidio_image_redactor/image_analyzer_engine.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
class ImageAnalyzerEngine:
    """ImageAnalyzerEngine class.

    :param analyzer_engine: The Presidio AnalyzerEngine instance
        to be used to detect PII in text
    :param ocr: the OCR object to be used to detect text in images.
    :param image_preprocessor: The ImagePreprocessor object to be
        used to preprocess the image
    """

    def __init__(
        self,
        analyzer_engine: Optional[AnalyzerEngine] = None,
        ocr: Optional[OCR] = None,
        image_preprocessor: Optional[ImagePreprocessor] = None,
    ):
        if not analyzer_engine:
            analyzer_engine = AnalyzerEngine()
        self.analyzer_engine = analyzer_engine

        if not ocr:
            ocr = TesseractOCR()
        self.ocr = ocr

        if not image_preprocessor:
            image_preprocessor = ImagePreprocessor()
        self.image_preprocessor = image_preprocessor

    def analyze(
        self, image: object, ocr_kwargs: Optional[dict] = None, **text_analyzer_kwargs
    ) -> List[ImageRecognizerResult]:
        """Analyse method to analyse the given image.

        :param image: PIL Image/numpy array or file path(str) to be processed.
        :param ocr_kwargs: Additional params for OCR methods.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.

        :return: List of the extract entities with image bounding boxes.
        """
        # Perform OCR
        perform_ocr_kwargs, ocr_threshold = self._parse_ocr_kwargs(ocr_kwargs)
        image, preprocessing_metadata = self.image_preprocessor.preprocess_image(image)
        ocr_result = self.ocr.perform_ocr(image, **perform_ocr_kwargs)
        ocr_result = self.remove_space_boxes(ocr_result)

        if preprocessing_metadata and ("scale_factor" in preprocessing_metadata):
            ocr_result = self._scale_bbox_results(
                ocr_result, preprocessing_metadata["scale_factor"]
            )

        # Apply OCR confidence threshold if it is passed in
        if ocr_threshold:
            ocr_result = self.threshold_ocr_result(ocr_result, ocr_threshold)

        # Analyze text
        text = self.ocr.get_text_from_ocr_dict(ocr_result)

        # Difines English as default language, if not specified
        if "language" not in text_analyzer_kwargs:
            text_analyzer_kwargs["language"] = "en"
        analyzer_result = self.analyzer_engine.analyze(
            text=text, **text_analyzer_kwargs
        )
        allow_list = self._check_for_allow_list(text_analyzer_kwargs)
        bboxes = self.map_analyzer_results_to_bounding_boxes(
            analyzer_result, ocr_result, text, allow_list
        )

        return bboxes

    @staticmethod
    def threshold_ocr_result(ocr_result: dict, ocr_threshold: float) -> dict:
        """Filter out OCR results below confidence threshold.

        :param ocr_result: OCR results (raw).
        :param ocr_threshold: Threshold value between -1 and 100.

        :return: OCR results with low confidence items removed.
        """
        if ocr_threshold < -1 or ocr_threshold > 100:
            raise ValueError("ocr_threshold must be between -1 and 100")

        # Get indices of items above threshold
        idx = list()
        for i, val in enumerate(ocr_result["conf"]):
            if float(val) >= ocr_threshold:
                idx.append(i)

        # Only retain high confidence items
        filtered_ocr_result = {}
        for key in list(ocr_result.keys()):
            filtered_ocr_result[key] = [ocr_result[key][i] for i in idx]

        return filtered_ocr_result

    @staticmethod
    def remove_space_boxes(ocr_result: dict) -> dict:
        """Remove OCR bboxes that are for spaces.

        :param ocr_result: OCR results (raw or thresholded).
        :return: OCR results with empty words removed.
        """
        # Get indices of items with no text
        idx = list()
        for i, text in enumerate(ocr_result["text"]):
            is_not_space = text.isspace() is False
            if text != "" and is_not_space:
                idx.append(i)

        # Only retain items with text
        filtered_ocr_result = {}
        for key in list(ocr_result.keys()):
            filtered_ocr_result[key] = [ocr_result[key][i] for i in idx]

        return filtered_ocr_result

    @staticmethod
    def map_analyzer_results_to_bounding_boxes(
        text_analyzer_results: List[RecognizerResult],
        ocr_result: dict,
        text: str,
        allow_list: List[str],
    ) -> List[ImageRecognizerResult]:
        """Map extracted PII entities to image bounding boxes.

        Matching is based on the position of the recognized entity from analyzer
        and word (in ocr dict) in the text.

        :param text_analyzer_results: PII entities recognized by presidio analyzer
        :param ocr_result: dict results with words and bboxes from OCR
        :param text: text the results are based on
        :param allow_list: List of words to not redact

        return: list of extracted entities with image bounding boxes
        """
        if (not ocr_result) or (not text_analyzer_results):
            return []

        bboxes = []
        proc_indexes = 0
        indexes = len(text_analyzer_results)

        pos = 0
        iter_ocr = enumerate(ocr_result["text"])
        for index, word in iter_ocr:
            if not word:
                pos += 1
            else:
                for element in text_analyzer_results:
                    text_element = text[element.start : element.end]
                    # check position and text of ocr word matches recognized entity
                    if (
                        max(pos, element.start) < min(element.end, pos + len(word))
                    ) and ((text_element in word) or (word in text_element)):
                        yes_make_bbox_for_word = (
                            (word is not None)
                            and (word != "")
                            and (word.isspace() is False)
                            and (word not in allow_list)
                        )
                        # Do not add bbox for standalone spaces / empty strings
                        if yes_make_bbox_for_word:
                            bboxes.append(
                                ImageRecognizerResult(
                                    element.entity_type,
                                    element.start,
                                    element.end,
                                    element.score,
                                    ocr_result["left"][index],
                                    ocr_result["top"][index],
                                    ocr_result["width"][index],
                                    ocr_result["height"][index],
                                )
                            )

                            # add bounding boxes for all words in ocr dict
                            # contained within the text of recognized entity
                            # based on relative position in the full text
                            while pos + len(word) < element.end:
                                prev_word = word
                                index, word = next(iter_ocr)
                                yes_make_bbox_for_word = (
                                    (word is not None)
                                    and (word != "")
                                    and (word.isspace() is False)
                                    and (word not in allow_list)
                                )
                                if yes_make_bbox_for_word:
                                    bboxes.append(
                                        ImageRecognizerResult(
                                            element.entity_type,
                                            element.start,
                                            element.end,
                                            element.score,
                                            ocr_result["left"][index],
                                            ocr_result["top"][index],
                                            ocr_result["width"][index],
                                            ocr_result["height"][index],
                                        )
                                    )
                                pos += len(prev_word) + 1
                            proc_indexes += 1

                if proc_indexes == indexes:
                    break
                pos += len(word) + 1

        return bboxes

    @staticmethod
    def _scale_bbox_results(
        ocr_result: Dict[str, List[Union[int, str]]], scale_factor: float
    ) -> Dict[str, float]:
        """Scale down the bounding box results based on a scale percentage.

        :param ocr_result: OCR results (raw).
        :param scale_percent: Scale percentage for resizing the bounding box.

        :return: OCR results (scaled).
        """
        scaled_results = deepcopy(ocr_result)
        coordinate_keys = ["left", "top"]
        dimension_keys = ["width", "height"]

        for coord_key in coordinate_keys:
            scaled_results[coord_key] = [
                int(np.ceil((x) / (scale_factor))) for x in scaled_results[coord_key]
            ]

        for dim_key in dimension_keys:
            scaled_results[dim_key] = [
                max(1, int(np.ceil(x / (scale_factor))))
                for x in scaled_results[dim_key]
            ]
        return scaled_results

    @staticmethod
    def _remove_bbox_padding(
        analyzer_bboxes: List[Dict[str, Union[str, float, int]]],
        padding_width: int,
    ) -> List[Dict[str, int]]:
        """Remove added padding in bounding box coordinates.

        :param analyzer_bboxes: The bounding boxes from analyzer results.
        :param padding_width: Pixel width used for padding (0 if no padding).

        :return: Bounding box information per word.
        """

        unpadded_results = deepcopy(analyzer_bboxes)
        if padding_width < 0:
            raise ValueError("Padding width must be a non-negative integer.")

        coordinate_keys = ["left", "top"]
        for coord_key in coordinate_keys:
            unpadded_results[coord_key] = [
                max(0, x - padding_width) for x in unpadded_results[coord_key]
            ]

        return unpadded_results

    @staticmethod
    def _parse_ocr_kwargs(ocr_kwargs: dict) -> Tuple[dict, float]:
        """Parse the OCR-related kwargs.

        :param ocr_kwargs: Parameters for OCR operations.

        :return: Params for ocr.perform_ocr and ocr_threshold
        """
        ocr_threshold = None
        if ocr_kwargs is not None:
            if "ocr_threshold" in ocr_kwargs:
                ocr_threshold = ocr_kwargs["ocr_threshold"]
                ocr_kwargs = {
                    key: value
                    for key, value in ocr_kwargs.items()
                    if key != "ocr_threshold"
                }
        else:
            ocr_kwargs = {}

        return ocr_kwargs, ocr_threshold

    @staticmethod
    def _check_for_allow_list(text_analyzer_kwargs: dict) -> List[str]:
        """Check the text_analyzer_kwargs for an allow_list.

        :param text_analyzer_kwargs: Text analyzer kwargs.
        :return: The allow list if it exists.
        """
        allow_list = []
        if text_analyzer_kwargs is not None:
            if "allow_list" in text_analyzer_kwargs:
                allow_list = text_analyzer_kwargs["allow_list"]

        return allow_list

    @staticmethod
    def fig2img(fig: matplotlib.figure.Figure) -> Image:
        """Convert a Matplotlib figure to a PIL Image and return it.

        :param fig: Matplotlib figure.

        :return: Image of figure.
        """
        buf = io.BytesIO()
        fig.savefig(buf)
        buf.seek(0)
        img = Image.open(buf)

        return img

    @staticmethod
    def get_pii_bboxes(
        ocr_bboxes: List[dict],
        analyzer_bboxes: List[dict]
    ) -> List[dict]:
        """Get a list of bboxes with is_PII property.

        :param ocr_bboxes: Bboxes from OCR results.
        :param analyzer_bboxes: Bboxes from analyzer results.

        :return: All bboxes with appropriate label for whether it is PHI or not.
        """
        bboxes = []
        for ocr_bbox in ocr_bboxes:
            has_match = False

            # Check if we have the same bbox in analyzer results
            for analyzer_bbox in analyzer_bboxes:
                has_same_position = (ocr_bbox["left"] == analyzer_bbox["left"] and ocr_bbox["top"] == analyzer_bbox["top"])  # noqa: E501
                has_same_dimension = (ocr_bbox["width"] == analyzer_bbox["width"] and ocr_bbox["height"] == analyzer_bbox["height"])  # noqa: E501
                is_same = (has_same_position is True and has_same_dimension is True)

                if is_same is True:
                    current_bbox = analyzer_bbox
                    current_bbox["is_PII"] = True
                    has_match = True
                    break

            if has_match is False:
                current_bbox = ocr_bbox
                current_bbox["is_PII"] = False

            bboxes.append(current_bbox)

        return bboxes

    @classmethod
    def add_custom_bboxes(
        cls,
        image: Image,
        bboxes: List[dict],
        show_text_annotation: bool = True,
        use_greyscale_cmap: bool = False
    ) -> Image:
        """Add custom bounding boxes to image.

        :param image: Standard image of DICOM pixels.
        :param bboxes: List of bounding boxes to display (with is_PII field).
        :param gt_bboxes: Ground truth bboxes (list of dictionaries).
        :param show_text_annotation: True if you want text annotation for
        PHI status to display.
        :param use_greyscale_cmap: Use greyscale color map.
        :return: Image with bounding boxes drawn on.
        """
        image_custom = ImageChops.duplicate(image)
        image_x, image_y = image_custom.size

        fig, ax = plt.subplots()
        image_r = 70
        fig.set_size_inches(image_x / image_r, image_y / image_r)

        if len(bboxes) == 0:
            ax.imshow(image_custom)
            return image_custom
        else:
            for box in bboxes:
                try:
                    entity_type = box["entity_type"]
                except KeyError:
                    entity_type = "UNKNOWN"

                try:
                    if box["is_PII"]:
                        bbox_color = "r"
                    else:
                        bbox_color = "b"
                except KeyError:
                    bbox_color = "b"

                # Get coordinates and dimensions
                x0 = box["left"]
                y0 = box["top"]
                x1 = x0 + box["width"]
                y1 = y0 + box["height"]
                rect = matplotlib.patches.Rectangle(
                    (x0, y0),
                    x1 - x0, y1 - y0,
                    edgecolor=bbox_color,
                    facecolor="none"
                )
                ax.add_patch(rect)
                if show_text_annotation:
                    ax.annotate(
                        entity_type,
                        xy=(x0 - 3, y0 - 3),
                        xycoords="data",
                        bbox=dict(boxstyle="round4,pad=.5", fc="0.9"),
                    )
            if use_greyscale_cmap:
                ax.imshow(image_custom, cmap="gray")
            else:
                ax.imshow(image_custom)
            im_from_fig = cls.fig2img(fig)
            im_resized = im_from_fig.resize((image_x, image_y))

        return im_resized

add_custom_bboxes(image, bboxes, show_text_annotation=True, use_greyscale_cmap=False) classmethod

Add custom bounding boxes to image.

Parameters:

Name Type Description Default
image Image

Standard image of DICOM pixels.

required
bboxes List[dict]

List of bounding boxes to display (with is_PII field).

required
gt_bboxes

Ground truth bboxes (list of dictionaries).

required
show_text_annotation bool

True if you want text annotation for PHI status to display.

True
use_greyscale_cmap bool

Use greyscale color map.

False

Returns:

Type Description
Image

Image with bounding boxes drawn on.

Source code in presidio_image_redactor/image_analyzer_engine.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@classmethod
def add_custom_bboxes(
    cls,
    image: Image,
    bboxes: List[dict],
    show_text_annotation: bool = True,
    use_greyscale_cmap: bool = False
) -> Image:
    """Add custom bounding boxes to image.

    :param image: Standard image of DICOM pixels.
    :param bboxes: List of bounding boxes to display (with is_PII field).
    :param gt_bboxes: Ground truth bboxes (list of dictionaries).
    :param show_text_annotation: True if you want text annotation for
    PHI status to display.
    :param use_greyscale_cmap: Use greyscale color map.
    :return: Image with bounding boxes drawn on.
    """
    image_custom = ImageChops.duplicate(image)
    image_x, image_y = image_custom.size

    fig, ax = plt.subplots()
    image_r = 70
    fig.set_size_inches(image_x / image_r, image_y / image_r)

    if len(bboxes) == 0:
        ax.imshow(image_custom)
        return image_custom
    else:
        for box in bboxes:
            try:
                entity_type = box["entity_type"]
            except KeyError:
                entity_type = "UNKNOWN"

            try:
                if box["is_PII"]:
                    bbox_color = "r"
                else:
                    bbox_color = "b"
            except KeyError:
                bbox_color = "b"

            # Get coordinates and dimensions
            x0 = box["left"]
            y0 = box["top"]
            x1 = x0 + box["width"]
            y1 = y0 + box["height"]
            rect = matplotlib.patches.Rectangle(
                (x0, y0),
                x1 - x0, y1 - y0,
                edgecolor=bbox_color,
                facecolor="none"
            )
            ax.add_patch(rect)
            if show_text_annotation:
                ax.annotate(
                    entity_type,
                    xy=(x0 - 3, y0 - 3),
                    xycoords="data",
                    bbox=dict(boxstyle="round4,pad=.5", fc="0.9"),
                )
        if use_greyscale_cmap:
            ax.imshow(image_custom, cmap="gray")
        else:
            ax.imshow(image_custom)
        im_from_fig = cls.fig2img(fig)
        im_resized = im_from_fig.resize((image_x, image_y))

    return im_resized

analyze(image, ocr_kwargs=None, **text_analyzer_kwargs)

Analyse method to analyse the given image.

Parameters:

Name Type Description Default
image object

PIL Image/numpy array or file path(str) to be processed.

required
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
text_analyzer_kwargs

Additional values for the analyze method in AnalyzerEngine.

{}

Returns:

Type Description
List[ImageRecognizerResult]

List of the extract entities with image bounding boxes.

Source code in presidio_image_redactor/image_analyzer_engine.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def analyze(
    self, image: object, ocr_kwargs: Optional[dict] = None, **text_analyzer_kwargs
) -> List[ImageRecognizerResult]:
    """Analyse method to analyse the given image.

    :param image: PIL Image/numpy array or file path(str) to be processed.
    :param ocr_kwargs: Additional params for OCR methods.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in AnalyzerEngine.

    :return: List of the extract entities with image bounding boxes.
    """
    # Perform OCR
    perform_ocr_kwargs, ocr_threshold = self._parse_ocr_kwargs(ocr_kwargs)
    image, preprocessing_metadata = self.image_preprocessor.preprocess_image(image)
    ocr_result = self.ocr.perform_ocr(image, **perform_ocr_kwargs)
    ocr_result = self.remove_space_boxes(ocr_result)

    if preprocessing_metadata and ("scale_factor" in preprocessing_metadata):
        ocr_result = self._scale_bbox_results(
            ocr_result, preprocessing_metadata["scale_factor"]
        )

    # Apply OCR confidence threshold if it is passed in
    if ocr_threshold:
        ocr_result = self.threshold_ocr_result(ocr_result, ocr_threshold)

    # Analyze text
    text = self.ocr.get_text_from_ocr_dict(ocr_result)

    # Difines English as default language, if not specified
    if "language" not in text_analyzer_kwargs:
        text_analyzer_kwargs["language"] = "en"
    analyzer_result = self.analyzer_engine.analyze(
        text=text, **text_analyzer_kwargs
    )
    allow_list = self._check_for_allow_list(text_analyzer_kwargs)
    bboxes = self.map_analyzer_results_to_bounding_boxes(
        analyzer_result, ocr_result, text, allow_list
    )

    return bboxes

fig2img(fig) staticmethod

Convert a Matplotlib figure to a PIL Image and return it.

Parameters:

Name Type Description Default
fig Figure

Matplotlib figure.

required

Returns:

Type Description
Image

Image of figure.

Source code in presidio_image_redactor/image_analyzer_engine.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@staticmethod
def fig2img(fig: matplotlib.figure.Figure) -> Image:
    """Convert a Matplotlib figure to a PIL Image and return it.

    :param fig: Matplotlib figure.

    :return: Image of figure.
    """
    buf = io.BytesIO()
    fig.savefig(buf)
    buf.seek(0)
    img = Image.open(buf)

    return img

get_pii_bboxes(ocr_bboxes, analyzer_bboxes) staticmethod

Get a list of bboxes with is_PII property.

Parameters:

Name Type Description Default
ocr_bboxes List[dict]

Bboxes from OCR results.

required
analyzer_bboxes List[dict]

Bboxes from analyzer results.

required

Returns:

Type Description
List[dict]

All bboxes with appropriate label for whether it is PHI or not.

Source code in presidio_image_redactor/image_analyzer_engine.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
@staticmethod
def get_pii_bboxes(
    ocr_bboxes: List[dict],
    analyzer_bboxes: List[dict]
) -> List[dict]:
    """Get a list of bboxes with is_PII property.

    :param ocr_bboxes: Bboxes from OCR results.
    :param analyzer_bboxes: Bboxes from analyzer results.

    :return: All bboxes with appropriate label for whether it is PHI or not.
    """
    bboxes = []
    for ocr_bbox in ocr_bboxes:
        has_match = False

        # Check if we have the same bbox in analyzer results
        for analyzer_bbox in analyzer_bboxes:
            has_same_position = (ocr_bbox["left"] == analyzer_bbox["left"] and ocr_bbox["top"] == analyzer_bbox["top"])  # noqa: E501
            has_same_dimension = (ocr_bbox["width"] == analyzer_bbox["width"] and ocr_bbox["height"] == analyzer_bbox["height"])  # noqa: E501
            is_same = (has_same_position is True and has_same_dimension is True)

            if is_same is True:
                current_bbox = analyzer_bbox
                current_bbox["is_PII"] = True
                has_match = True
                break

        if has_match is False:
            current_bbox = ocr_bbox
            current_bbox["is_PII"] = False

        bboxes.append(current_bbox)

    return bboxes

map_analyzer_results_to_bounding_boxes(text_analyzer_results, ocr_result, text, allow_list) staticmethod

Map extracted PII entities to image bounding boxes.

Matching is based on the position of the recognized entity from analyzer and word (in ocr dict) in the text.

Parameters:

Name Type Description Default
text_analyzer_results List[RecognizerResult]

PII entities recognized by presidio analyzer

required
ocr_result dict

dict results with words and bboxes from OCR

required
text str

text the results are based on

required
allow_list List[str]

List of words to not redact return: list of extracted entities with image bounding boxes

required
Source code in presidio_image_redactor/image_analyzer_engine.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@staticmethod
def map_analyzer_results_to_bounding_boxes(
    text_analyzer_results: List[RecognizerResult],
    ocr_result: dict,
    text: str,
    allow_list: List[str],
) -> List[ImageRecognizerResult]:
    """Map extracted PII entities to image bounding boxes.

    Matching is based on the position of the recognized entity from analyzer
    and word (in ocr dict) in the text.

    :param text_analyzer_results: PII entities recognized by presidio analyzer
    :param ocr_result: dict results with words and bboxes from OCR
    :param text: text the results are based on
    :param allow_list: List of words to not redact

    return: list of extracted entities with image bounding boxes
    """
    if (not ocr_result) or (not text_analyzer_results):
        return []

    bboxes = []
    proc_indexes = 0
    indexes = len(text_analyzer_results)

    pos = 0
    iter_ocr = enumerate(ocr_result["text"])
    for index, word in iter_ocr:
        if not word:
            pos += 1
        else:
            for element in text_analyzer_results:
                text_element = text[element.start : element.end]
                # check position and text of ocr word matches recognized entity
                if (
                    max(pos, element.start) < min(element.end, pos + len(word))
                ) and ((text_element in word) or (word in text_element)):
                    yes_make_bbox_for_word = (
                        (word is not None)
                        and (word != "")
                        and (word.isspace() is False)
                        and (word not in allow_list)
                    )
                    # Do not add bbox for standalone spaces / empty strings
                    if yes_make_bbox_for_word:
                        bboxes.append(
                            ImageRecognizerResult(
                                element.entity_type,
                                element.start,
                                element.end,
                                element.score,
                                ocr_result["left"][index],
                                ocr_result["top"][index],
                                ocr_result["width"][index],
                                ocr_result["height"][index],
                            )
                        )

                        # add bounding boxes for all words in ocr dict
                        # contained within the text of recognized entity
                        # based on relative position in the full text
                        while pos + len(word) < element.end:
                            prev_word = word
                            index, word = next(iter_ocr)
                            yes_make_bbox_for_word = (
                                (word is not None)
                                and (word != "")
                                and (word.isspace() is False)
                                and (word not in allow_list)
                            )
                            if yes_make_bbox_for_word:
                                bboxes.append(
                                    ImageRecognizerResult(
                                        element.entity_type,
                                        element.start,
                                        element.end,
                                        element.score,
                                        ocr_result["left"][index],
                                        ocr_result["top"][index],
                                        ocr_result["width"][index],
                                        ocr_result["height"][index],
                                    )
                                )
                            pos += len(prev_word) + 1
                        proc_indexes += 1

            if proc_indexes == indexes:
                break
            pos += len(word) + 1

    return bboxes

remove_space_boxes(ocr_result) staticmethod

Remove OCR bboxes that are for spaces.

Parameters:

Name Type Description Default
ocr_result dict

OCR results (raw or thresholded).

required

Returns:

Type Description
dict

OCR results with empty words removed.

Source code in presidio_image_redactor/image_analyzer_engine.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
@staticmethod
def remove_space_boxes(ocr_result: dict) -> dict:
    """Remove OCR bboxes that are for spaces.

    :param ocr_result: OCR results (raw or thresholded).
    :return: OCR results with empty words removed.
    """
    # Get indices of items with no text
    idx = list()
    for i, text in enumerate(ocr_result["text"]):
        is_not_space = text.isspace() is False
        if text != "" and is_not_space:
            idx.append(i)

    # Only retain items with text
    filtered_ocr_result = {}
    for key in list(ocr_result.keys()):
        filtered_ocr_result[key] = [ocr_result[key][i] for i in idx]

    return filtered_ocr_result

threshold_ocr_result(ocr_result, ocr_threshold) staticmethod

Filter out OCR results below confidence threshold.

Parameters:

Name Type Description Default
ocr_result dict

OCR results (raw).

required
ocr_threshold float

Threshold value between -1 and 100.

required

Returns:

Type Description
dict

OCR results with low confidence items removed.

Source code in presidio_image_redactor/image_analyzer_engine.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@staticmethod
def threshold_ocr_result(ocr_result: dict, ocr_threshold: float) -> dict:
    """Filter out OCR results below confidence threshold.

    :param ocr_result: OCR results (raw).
    :param ocr_threshold: Threshold value between -1 and 100.

    :return: OCR results with low confidence items removed.
    """
    if ocr_threshold < -1 or ocr_threshold > 100:
        raise ValueError("ocr_threshold must be between -1 and 100")

    # Get indices of items above threshold
    idx = list()
    for i, val in enumerate(ocr_result["conf"]):
        if float(val) >= ocr_threshold:
            idx.append(i)

    # Only retain high confidence items
    filtered_ocr_result = {}
    for key in list(ocr_result.keys()):
        filtered_ocr_result[key] = [ocr_result[key][i] for i in idx]

    return filtered_ocr_result

ImagePiiVerifyEngine

Bases: ImageRedactorEngine

ImagePiiVerifyEngine class only supporting Pii verification currently.

Source code in presidio_image_redactor/image_pii_verify_engine.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
class ImagePiiVerifyEngine(ImageRedactorEngine):
    """ImagePiiVerifyEngine class only supporting Pii verification currently."""

    def verify(
        self,
        image: Image,
        is_greyscale: bool = False,
        display_image: bool = True,
        show_text_annotation: bool = True,
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs
    ) -> Image:
        """Annotate image with the detect PII entity.

        Please notice, this method duplicates the image, creates a
        new instance and manipulate it.

        :param image: PIL Image to be processed.
        :param is_greyscale: Whether the image is greyscale or not.
        :param display_image: If the verificationimage is displayed and returned.
        :param show_text_annotation: True to display entity type when displaying
        image with bounding boxes.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in ImageAnalyzerEngine.

        :return: the annotated image
        """
        image = ImageChops.duplicate(image)

        # Check the ad-hoc recognizers list
        self._check_ad_hoc_recognizer_list(ad_hoc_recognizers)

        # Detect text
        perform_ocr_kwargs, ocr_threshold = self.image_analyzer_engine._parse_ocr_kwargs(ocr_kwargs)  # noqa: E501
        ocr_results = self.image_analyzer_engine.ocr.perform_ocr(
            image,
            **perform_ocr_kwargs
        )
        if ocr_threshold:
            ocr_results = self.image_analyzer_engine.threshold_ocr_result(
                ocr_results,
                ocr_threshold
            )
        ocr_bboxes = self.bbox_processor.get_bboxes_from_ocr_results(ocr_results)

        # Detect PII
        if ad_hoc_recognizers is None:
            analyzer_results = self.image_analyzer_engine.analyze(
                image,
                ocr_kwargs=ocr_kwargs,
                **text_analyzer_kwargs,
            )
        else:
            analyzer_results = self.image_analyzer_engine.analyze(
                image,
                ocr_kwargs=ocr_kwargs,
                ad_hoc_recognizers=ad_hoc_recognizers,
                **text_analyzer_kwargs,
            )
        analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
            analyzer_results
        )

        # Prepare for plotting
        pii_bboxes = self.image_analyzer_engine.get_pii_bboxes(
            ocr_bboxes,
            analyzer_bboxes
        )
        if is_greyscale:
            use_greyscale_cmap = True
        else:
            use_greyscale_cmap = False

        # Get image with verification boxes
        verify_image = (
            self.image_analyzer_engine.add_custom_bboxes(
                image, pii_bboxes, show_text_annotation, use_greyscale_cmap
            )
            if display_image
            else None
        )

        return verify_image

verify(image, is_greyscale=False, display_image=True, show_text_annotation=True, ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Annotate image with the detect PII entity.

Please notice, this method duplicates the image, creates a new instance and manipulate it.

Parameters:

Name Type Description Default
image Image

PIL Image to be processed.

required
is_greyscale bool

Whether the image is greyscale or not.

False
display_image bool

If the verificationimage is displayed and returned.

True
show_text_annotation bool

True to display entity type when displaying image with bounding boxes.

True
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in ImageAnalyzerEngine.

{}

Returns:

Type Description
Image

the annotated image

Source code in presidio_image_redactor/image_pii_verify_engine.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def verify(
    self,
    image: Image,
    is_greyscale: bool = False,
    display_image: bool = True,
    show_text_annotation: bool = True,
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs
) -> Image:
    """Annotate image with the detect PII entity.

    Please notice, this method duplicates the image, creates a
    new instance and manipulate it.

    :param image: PIL Image to be processed.
    :param is_greyscale: Whether the image is greyscale or not.
    :param display_image: If the verificationimage is displayed and returned.
    :param show_text_annotation: True to display entity type when displaying
    image with bounding boxes.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in ImageAnalyzerEngine.

    :return: the annotated image
    """
    image = ImageChops.duplicate(image)

    # Check the ad-hoc recognizers list
    self._check_ad_hoc_recognizer_list(ad_hoc_recognizers)

    # Detect text
    perform_ocr_kwargs, ocr_threshold = self.image_analyzer_engine._parse_ocr_kwargs(ocr_kwargs)  # noqa: E501
    ocr_results = self.image_analyzer_engine.ocr.perform_ocr(
        image,
        **perform_ocr_kwargs
    )
    if ocr_threshold:
        ocr_results = self.image_analyzer_engine.threshold_ocr_result(
            ocr_results,
            ocr_threshold
        )
    ocr_bboxes = self.bbox_processor.get_bboxes_from_ocr_results(ocr_results)

    # Detect PII
    if ad_hoc_recognizers is None:
        analyzer_results = self.image_analyzer_engine.analyze(
            image,
            ocr_kwargs=ocr_kwargs,
            **text_analyzer_kwargs,
        )
    else:
        analyzer_results = self.image_analyzer_engine.analyze(
            image,
            ocr_kwargs=ocr_kwargs,
            ad_hoc_recognizers=ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )
    analyzer_bboxes = self.bbox_processor.get_bboxes_from_analyzer_results(
        analyzer_results
    )

    # Prepare for plotting
    pii_bboxes = self.image_analyzer_engine.get_pii_bboxes(
        ocr_bboxes,
        analyzer_bboxes
    )
    if is_greyscale:
        use_greyscale_cmap = True
    else:
        use_greyscale_cmap = False

    # Get image with verification boxes
    verify_image = (
        self.image_analyzer_engine.add_custom_bboxes(
            image, pii_bboxes, show_text_annotation, use_greyscale_cmap
        )
        if display_image
        else None
    )

    return verify_image

ImagePreprocessor

ImagePreprocessor class.

Parent class for image preprocessing objects.

Source code in presidio_image_redactor/image_processing_engine.py
 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class ImagePreprocessor:
    """ImagePreprocessor class.

    Parent class for image preprocessing objects.
    """

    def __init__(self, use_greyscale: bool = True) -> None:
        """Initialize the ImagePreprocessor class.

        :param use_greyscale: Whether to convert the image to greyscale.
        """
        self.use_greyscale = use_greyscale

    def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
        """Preprocess the image to be analyzed.

        :param image: Loaded PIL image.

        :return: The processed image and any metadata regarding the
             preprocessing approach.
        """
        return image, {}

    def convert_image_to_array(self, image: Image.Image) -> np.ndarray:
        """Convert PIL image to numpy array.

        :param image: Loaded PIL image.
        :param convert_to_greyscale: Whether to convert the image to greyscale.

        :return: image pixels as a numpy array.

        """

        if isinstance(image, np.ndarray):
            img = image
        else:
            if self.use_greyscale:
                image = image.convert("L")
            img = np.asarray(image)
        return img

    @staticmethod
    def _get_bg_color(
        image: Image.Image, is_greyscale: bool, invert: bool = False
    ) -> Union[int, Tuple[int, int, int]]:
        """Select most common color as background color.

        :param image: Loaded PIL image.
        :param is_greyscale: Whether the image is greyscale.
        :param invert: TRUE if you want to get the inverse of the bg color.

        :return: Background color.
        """
        # Invert colors if invert flag is True
        if invert:
            if image.mode == "RGBA":
                # Handle transparency as needed
                r, g, b, a = image.split()
                rgb_image = Image.merge("RGB", (r, g, b))
                inverted_image = PIL.ImageOps.invert(rgb_image)
                r2, g2, b2 = inverted_image.split()

                image = Image.merge("RGBA", (r2, g2, b2, a))

            else:
                image = PIL.ImageOps.invert(image)

        # Get background color
        if is_greyscale:
            # Select most common color as color
            bg_color = int(np.bincount(image.flatten()).argmax())
        else:
            # Reduce size of image to 1 pixel to get dominant color
            tmp_image = image.copy()
            tmp_image = tmp_image.resize((1, 1), resample=0)
            bg_color = tmp_image.getpixel((0, 0))

        return bg_color

    @staticmethod
    def _get_image_contrast(image: np.ndarray) -> Tuple[float, float]:
        """Compute the contrast level and mean intensity of an image.

        :param image: Input image pixels (as a numpy array).

        :return: A tuple containing the contrast level and mean intensity of the image.
        """
        contrast = np.std(image)
        mean_intensity = np.mean(image)
        return contrast, mean_intensity

__init__(use_greyscale=True)

Initialize the ImagePreprocessor class.

Parameters:

Name Type Description Default
use_greyscale bool

Whether to convert the image to greyscale.

True
Source code in presidio_image_redactor/image_processing_engine.py
15
16
17
18
19
20
def __init__(self, use_greyscale: bool = True) -> None:
    """Initialize the ImagePreprocessor class.

    :param use_greyscale: Whether to convert the image to greyscale.
    """
    self.use_greyscale = use_greyscale

convert_image_to_array(image)

Convert PIL image to numpy array.

Parameters:

Name Type Description Default
image Image

Loaded PIL image.

required
convert_to_greyscale

Whether to convert the image to greyscale.

required

Returns:

Type Description
ndarray

image pixels as a numpy array.

Source code in presidio_image_redactor/image_processing_engine.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def convert_image_to_array(self, image: Image.Image) -> np.ndarray:
    """Convert PIL image to numpy array.

    :param image: Loaded PIL image.
    :param convert_to_greyscale: Whether to convert the image to greyscale.

    :return: image pixels as a numpy array.

    """

    if isinstance(image, np.ndarray):
        img = image
    else:
        if self.use_greyscale:
            image = image.convert("L")
        img = np.asarray(image)
    return img

preprocess_image(image)

Preprocess the image to be analyzed.

Parameters:

Name Type Description Default
image Image

Loaded PIL image.

required

Returns:

Type Description
Tuple[Image, dict]

The processed image and any metadata regarding the preprocessing approach.

Source code in presidio_image_redactor/image_processing_engine.py
22
23
24
25
26
27
28
29
30
def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
    """Preprocess the image to be analyzed.

    :param image: Loaded PIL image.

    :return: The processed image and any metadata regarding the
         preprocessing approach.
    """
    return image, {}

ImageRedactorEngine

ImageRedactorEngine performs OCR + PII detection + bounding box redaction.

Parameters:

Name Type Description Default
image_analyzer_engine ImageAnalyzerEngine

Engine which performs OCR + PII detection.

None
Source code in presidio_image_redactor/image_redactor_engine.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
class ImageRedactorEngine:
    """ImageRedactorEngine performs OCR + PII detection + bounding box redaction.

    :param image_analyzer_engine: Engine which performs OCR + PII detection.
    """

    def __init__(
        self,
        image_analyzer_engine: ImageAnalyzerEngine = None,
    ):
        if not image_analyzer_engine:
            self.image_analyzer_engine = ImageAnalyzerEngine()
        else:
            self.image_analyzer_engine = image_analyzer_engine

        self.bbox_processor = BboxProcessor()

    def redact(
        self,
        image: Image,
        fill: Union[int, Tuple[int, int, int]] = (0, 0, 0),
        ocr_kwargs: Optional[dict] = None,
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
        **text_analyzer_kwargs,
    ) -> Image:
        """Redact method to redact the given image.

        Please notice, this method duplicates the image, creates a new instance and
        manipulate it.
        :param image: PIL Image to be processed.
        :param fill: colour to fill the shape - int (0-255) for
        grayscale or Tuple(R, G, B) for RGB.
        :param ocr_kwargs: Additional params for OCR methods.
        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        :param text_analyzer_kwargs: Additional values for the analyze method
        in AnalyzerEngine.

        :return: the redacted image
        """

        image = ImageChops.duplicate(image)

        # Check the ad-hoc recognizers list
        self._check_ad_hoc_recognizer_list(ad_hoc_recognizers)

        # Detect PII
        if ad_hoc_recognizers is None:
            bboxes = self.image_analyzer_engine.analyze(
                image,
                ocr_kwargs=ocr_kwargs,
                **text_analyzer_kwargs,
            )
        else:
            bboxes = self.image_analyzer_engine.analyze(
                image,
                ocr_kwargs=ocr_kwargs,
                ad_hoc_recognizers=ad_hoc_recognizers,
                **text_analyzer_kwargs,
            )

        draw = ImageDraw.Draw(image)

        for box in bboxes:
            x0 = box.left
            y0 = box.top
            x1 = x0 + box.width
            y1 = y0 + box.height
            draw.rectangle([x0, y0, x1, y1], fill=fill)

        return image

    @staticmethod
    def _check_ad_hoc_recognizer_list(
        ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    ):
        """Check if the provided ad-hoc recognizer list is valid.

        :param ad_hoc_recognizers: List of PatternRecognizer objects to use
        for ad-hoc recognizer.
        """
        if isinstance(ad_hoc_recognizers, (list, type(None))):
            if isinstance(ad_hoc_recognizers, list):
                if len(ad_hoc_recognizers) >= 1:
                    are_recognizers = all(
                        isinstance(
                            x, presidio_analyzer.pattern_recognizer.PatternRecognizer
                        )
                        for x in ad_hoc_recognizers
                    )
                    if are_recognizers is False:
                        raise TypeError(
                            """All items in ad_hoc_recognizers list must be
                            PatternRecognizer objects"""
                        )
                else:
                    raise TypeError(
                        "ad_hoc_recognizers must be None or list of PatternRecognizer"
                    )
        else:
            raise TypeError(
                "ad_hoc_recognizers must be None or list of PatternRecognizer"
            )

redact(image, fill=(0, 0, 0), ocr_kwargs=None, ad_hoc_recognizers=None, **text_analyzer_kwargs)

Redact method to redact the given image.

Please notice, this method duplicates the image, creates a new instance and manipulate it.

Parameters:

Name Type Description Default
image Image

PIL Image to be processed.

required
fill Union[int, Tuple[int, int, int]]

colour to fill the shape - int (0-255) for grayscale or Tuple(R, G, B) for RGB.

(0, 0, 0)
ocr_kwargs Optional[dict]

Additional params for OCR methods.

None
ad_hoc_recognizers Optional[List[PatternRecognizer]]

List of PatternRecognizer objects to use for ad-hoc recognizer.

None
text_analyzer_kwargs

Additional values for the analyze method in AnalyzerEngine.

{}

Returns:

Type Description
Image

the redacted image

Source code in presidio_image_redactor/image_redactor_engine.py
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def redact(
    self,
    image: Image,
    fill: Union[int, Tuple[int, int, int]] = (0, 0, 0),
    ocr_kwargs: Optional[dict] = None,
    ad_hoc_recognizers: Optional[List[PatternRecognizer]] = None,
    **text_analyzer_kwargs,
) -> Image:
    """Redact method to redact the given image.

    Please notice, this method duplicates the image, creates a new instance and
    manipulate it.
    :param image: PIL Image to be processed.
    :param fill: colour to fill the shape - int (0-255) for
    grayscale or Tuple(R, G, B) for RGB.
    :param ocr_kwargs: Additional params for OCR methods.
    :param ad_hoc_recognizers: List of PatternRecognizer objects to use
    for ad-hoc recognizer.
    :param text_analyzer_kwargs: Additional values for the analyze method
    in AnalyzerEngine.

    :return: the redacted image
    """

    image = ImageChops.duplicate(image)

    # Check the ad-hoc recognizers list
    self._check_ad_hoc_recognizer_list(ad_hoc_recognizers)

    # Detect PII
    if ad_hoc_recognizers is None:
        bboxes = self.image_analyzer_engine.analyze(
            image,
            ocr_kwargs=ocr_kwargs,
            **text_analyzer_kwargs,
        )
    else:
        bboxes = self.image_analyzer_engine.analyze(
            image,
            ocr_kwargs=ocr_kwargs,
            ad_hoc_recognizers=ad_hoc_recognizers,
            **text_analyzer_kwargs,
        )

    draw = ImageDraw.Draw(image)

    for box in bboxes:
        x0 = box.left
        y0 = box.top
        x1 = x0 + box.width
        y1 = y0 + box.height
        draw.rectangle([x0, y0, x1, y1], fill=fill)

    return image

ImageRescaling

Bases: ImagePreprocessor

ImageRescaling class. Rescales images based on their size.

Source code in presidio_image_redactor/image_processing_engine.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
class ImageRescaling(ImagePreprocessor):
    """ImageRescaling class. Rescales images based on their size."""

    def __init__(
        self,
        small_size: int = 1048576,
        large_size: int = 4000000,
        factor: int = 2,
        interpolation: int = cv2.INTER_AREA,
    ) -> None:
        """Initialize the ImageRescaling class.

        :param small_size: Threshold for small image size.
        :param large_size: Threshold for large image size.
        :param factor: Scaling factor for resizing.
        :param interpolation: Interpolation method for resizing.
        """
        super().__init__(use_greyscale=True)

        self.small_size = small_size
        self.large_size = large_size
        self.factor = factor
        self.interpolation = interpolation

    def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
        """Preprocess the image to be analyzed.

        :param image: Loaded PIL image.

        :return: The processed image and metadata (scale_factor).
        """

        scale_factor = 1
        if image.size < self.small_size:
            scale_factor = self.factor
        elif image.size > self.large_size:
            scale_factor = 1 / self.factor

        width = int(image.shape[1] * scale_factor)
        height = int(image.shape[0] * scale_factor)
        dimensions = (width, height)

        # resize image
        rescaled_image = cv2.resize(image, dimensions, interpolation=self.interpolation)
        metadata = {"scale_factor": scale_factor}
        return Image.fromarray(rescaled_image), metadata

__init__(small_size=1048576, large_size=4000000, factor=2, interpolation=cv2.INTER_AREA)

Initialize the ImageRescaling class.

Parameters:

Name Type Description Default
small_size int

Threshold for small image size.

1048576
large_size int

Threshold for large image size.

4000000
factor int

Scaling factor for resizing.

2
interpolation int

Interpolation method for resizing.

INTER_AREA
Source code in presidio_image_redactor/image_processing_engine.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def __init__(
    self,
    small_size: int = 1048576,
    large_size: int = 4000000,
    factor: int = 2,
    interpolation: int = cv2.INTER_AREA,
) -> None:
    """Initialize the ImageRescaling class.

    :param small_size: Threshold for small image size.
    :param large_size: Threshold for large image size.
    :param factor: Scaling factor for resizing.
    :param interpolation: Interpolation method for resizing.
    """
    super().__init__(use_greyscale=True)

    self.small_size = small_size
    self.large_size = large_size
    self.factor = factor
    self.interpolation = interpolation

preprocess_image(image)

Preprocess the image to be analyzed.

Parameters:

Name Type Description Default
image Image

Loaded PIL image.

required

Returns:

Type Description
Tuple[Image, dict]

The processed image and metadata (scale_factor).

Source code in presidio_image_redactor/image_processing_engine.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def preprocess_image(self, image: Image.Image) -> Tuple[Image.Image, dict]:
    """Preprocess the image to be analyzed.

    :param image: Loaded PIL image.

    :return: The processed image and metadata (scale_factor).
    """

    scale_factor = 1
    if image.size < self.small_size:
        scale_factor = self.factor
    elif image.size > self.large_size:
        scale_factor = 1 / self.factor

    width = int(image.shape[1] * scale_factor)
    height = int(image.shape[0] * scale_factor)
    dimensions = (width, height)

    # resize image
    rescaled_image = cv2.resize(image, dimensions, interpolation=self.interpolation)
    metadata = {"scale_factor": scale_factor}
    return Image.fromarray(rescaled_image), metadata

OCR

Bases: ABC

OCR class that performs OCR on a given image.

Source code in presidio_image_redactor/ocr.py
 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
class OCR(ABC):
    """OCR class that performs OCR on a given image."""

    @abstractmethod
    def perform_ocr(self, image: object, **kwargs) -> dict:
        """Perform OCR on a given image.

        :param image: PIL Image/numpy array or file path(str) to be processed
        :param kwargs: Additional values for perform OCR method

        :return: results dictionary containing bboxes and text for each detected word
        """
        pass

    @staticmethod
    def get_text_from_ocr_dict(ocr_result: dict, separator: str = " ") -> str:
        """Combine the text from the OCR dict to full text.

        :param ocr_result: dictionary containing the ocr results per word
        :param separator: separator to use when joining the words

        return: str containing the full extracted text as string
        """
        if not ocr_result:
            return ""
        else:
            return separator.join(ocr_result["text"])

get_text_from_ocr_dict(ocr_result, separator=' ') staticmethod

Combine the text from the OCR dict to full text.

Parameters:

Name Type Description Default
ocr_result dict

dictionary containing the ocr results per word

required
separator str

separator to use when joining the words return: str containing the full extracted text as string

' '
Source code in presidio_image_redactor/ocr.py
18
19
20
21
22
23
24
25
26
27
28
29
30
@staticmethod
def get_text_from_ocr_dict(ocr_result: dict, separator: str = " ") -> str:
    """Combine the text from the OCR dict to full text.

    :param ocr_result: dictionary containing the ocr results per word
    :param separator: separator to use when joining the words

    return: str containing the full extracted text as string
    """
    if not ocr_result:
        return ""
    else:
        return separator.join(ocr_result["text"])

perform_ocr(image, **kwargs) abstractmethod

Perform OCR on a given image.

Parameters:

Name Type Description Default
image object

PIL Image/numpy array or file path(str) to be processed

required
kwargs

Additional values for perform OCR method

{}

Returns:

Type Description
dict

results dictionary containing bboxes and text for each detected word

Source code in presidio_image_redactor/ocr.py
 7
 8
 9
10
11
12
13
14
15
16
@abstractmethod
def perform_ocr(self, image: object, **kwargs) -> dict:
    """Perform OCR on a given image.

    :param image: PIL Image/numpy array or file path(str) to be processed
    :param kwargs: Additional values for perform OCR method

    :return: results dictionary containing bboxes and text for each detected word
    """
    pass

SegmentedAdaptiveThreshold

Bases: ImagePreprocessor

SegmentedAdaptiveThreshold class.

The class applies adaptive thresholding to an image and returns the thresholded image and metadata. The parameters used to run the adaptivethresholding are selected based on the contrast level of the image.

Source code in presidio_image_redactor/image_processing_engine.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
class SegmentedAdaptiveThreshold(ImagePreprocessor):
    """SegmentedAdaptiveThreshold class.

    The class applies adaptive thresholding to an image
    and returns the thresholded image and metadata.
    The parameters used to run the adaptivethresholding are selected based on
    the contrast level of the image.
    """

    def __init__(
        self,
        block_size: int = 5,
        contrast_threshold: int = 40,
        c_low_contrast: int = 10,
        c_high_contrast: int = 40,
        bg_threshold: int = 122,
    ) -> None:
        """Initialize the SegmentedAdaptiveThreshold class.

        :param block_size: Size of the neighborhood area for threshold calculation.
        :param contrast_threshold: Threshold for low contrast images.
        :param C_low_contrast: Constant added to the mean for low contrast images.
        :param C_high_contrast: Constant added to the mean for high contrast images.
        :param bg_threshold: Threshold for background color.
        """

        super().__init__(use_greyscale=True)
        self.block_size = block_size
        self.c_low_contrast = c_low_contrast
        self.c_high_contrast = c_high_contrast
        self.bg_threshold = bg_threshold
        self.contrast_threshold = contrast_threshold

    def preprocess_image(
        self, image: Union[Image.Image, np.ndarray]
    ) -> Tuple[Image.Image, dict]:
        """Preprocess the image.

        :param image: Loaded PIL image.

        :return: The processed image and metadata (C, background_color, contrast).
        """
        if isinstance(image, np.ndarray):
            image = self.convert_image_to_array(image)

        # Determine background color
        background_color = self._get_bg_color(image, True)
        contrast, _ = self._get_image_contrast(image)

        c = (
            self.c_low_contrast
            if contrast <= self.contrast_threshold
            else self.c_high_contrast
        )

        if background_color < self.bg_threshold:
            adaptive_threshold_image = cv2.adaptiveThreshold(
                image,
                255,
                cv2.ADAPTIVE_THRESH_MEAN_C,
                cv2.THRESH_BINARY_INV,
                self.block_size,
                -c,
            )
        else:
            adaptive_threshold_image = cv2.adaptiveThreshold(
                image,
                255,
                cv2.ADAPTIVE_THRESH_MEAN_C,
                cv2.THRESH_BINARY,
                self.block_size,
                c,
            )

        metadata = {"C": c, "background_color": background_color, "contrast": contrast}
        return Image.fromarray(adaptive_threshold_image), metadata

__init__(block_size=5, contrast_threshold=40, c_low_contrast=10, c_high_contrast=40, bg_threshold=122)

Initialize the SegmentedAdaptiveThreshold class.

Parameters:

Name Type Description Default
block_size int

Size of the neighborhood area for threshold calculation.

5
contrast_threshold int

Threshold for low contrast images.

40
C_low_contrast

Constant added to the mean for low contrast images.

required
C_high_contrast

Constant added to the mean for high contrast images.

required
bg_threshold int

Threshold for background color.

122
Source code in presidio_image_redactor/image_processing_engine.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def __init__(
    self,
    block_size: int = 5,
    contrast_threshold: int = 40,
    c_low_contrast: int = 10,
    c_high_contrast: int = 40,
    bg_threshold: int = 122,
) -> None:
    """Initialize the SegmentedAdaptiveThreshold class.

    :param block_size: Size of the neighborhood area for threshold calculation.
    :param contrast_threshold: Threshold for low contrast images.
    :param C_low_contrast: Constant added to the mean for low contrast images.
    :param C_high_contrast: Constant added to the mean for high contrast images.
    :param bg_threshold: Threshold for background color.
    """

    super().__init__(use_greyscale=True)
    self.block_size = block_size
    self.c_low_contrast = c_low_contrast
    self.c_high_contrast = c_high_contrast
    self.bg_threshold = bg_threshold
    self.contrast_threshold = contrast_threshold

preprocess_image(image)

Preprocess the image.

Parameters:

Name Type Description Default
image Union[Image, ndarray]

Loaded PIL image.

required

Returns:

Type Description
Tuple[Image, dict]

The processed image and metadata (C, background_color, contrast).

Source code in presidio_image_redactor/image_processing_engine.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def preprocess_image(
    self, image: Union[Image.Image, np.ndarray]
) -> Tuple[Image.Image, dict]:
    """Preprocess the image.

    :param image: Loaded PIL image.

    :return: The processed image and metadata (C, background_color, contrast).
    """
    if isinstance(image, np.ndarray):
        image = self.convert_image_to_array(image)

    # Determine background color
    background_color = self._get_bg_color(image, True)
    contrast, _ = self._get_image_contrast(image)

    c = (
        self.c_low_contrast
        if contrast <= self.contrast_threshold
        else self.c_high_contrast
    )

    if background_color < self.bg_threshold:
        adaptive_threshold_image = cv2.adaptiveThreshold(
            image,
            255,
            cv2.ADAPTIVE_THRESH_MEAN_C,
            cv2.THRESH_BINARY_INV,
            self.block_size,
            -c,
        )
    else:
        adaptive_threshold_image = cv2.adaptiveThreshold(
            image,
            255,
            cv2.ADAPTIVE_THRESH_MEAN_C,
            cv2.THRESH_BINARY,
            self.block_size,
            c,
        )

    metadata = {"C": c, "background_color": background_color, "contrast": contrast}
    return Image.fromarray(adaptive_threshold_image), metadata

TesseractOCR

Bases: OCR

OCR class that performs OCR on a given image.

Source code in presidio_image_redactor/tesseract_ocr.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class TesseractOCR(OCR):
    """OCR class that performs OCR on a given image."""

    def perform_ocr(self, image: object, **kwargs) -> dict:
        """Perform OCR on a given image.

        :param image: PIL Image/numpy array or file path(str) to be processed
        :param kwargs: Additional values for OCR image_to_data

        :return: results dictionary containing bboxes and text for each detected word
        """
        output_type = pytesseract.Output.DICT
        return pytesseract.image_to_data(image, output_type=output_type, **kwargs)

perform_ocr(image, **kwargs)

Perform OCR on a given image.

Parameters:

Name Type Description Default
image object

PIL Image/numpy array or file path(str) to be processed

required
kwargs

Additional values for OCR image_to_data

{}

Returns:

Type Description
dict

results dictionary containing bboxes and text for each detected word

Source code in presidio_image_redactor/tesseract_ocr.py
 9
10
11
12
13
14
15
16
17
18
def perform_ocr(self, image: object, **kwargs) -> dict:
    """Perform OCR on a given image.

    :param image: PIL Image/numpy array or file path(str) to be processed
    :param kwargs: Additional values for OCR image_to_data

    :return: results dictionary containing bboxes and text for each detected word
    """
    output_type = pytesseract.Output.DICT
    return pytesseract.image_to_data(image, output_type=output_type, **kwargs)