Skip to content

Commit 2a2d000

Browse files
authored
🔨 Update OpenVINO predict to handle normalization inside the method. (#1875)
* Update OpenVINO docstring * Perform the normalization within the predict in openvino * Update the docstring by adding more examples
1 parent 165702f commit 2a2d000

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

‎src/anomalib/deploy/inferencers/openvino_inferencer.py

+30-8
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,19 @@ class OpenVINOInferencer(Inferencer):
6969
metadata is loaded from the ``metadata.json`` file. To make a prediction,
7070
we can simply call the ``predict`` method:
7171
72-
>>> import cv2
73-
>>> image = cv2.imread("path/to/image.jpg")
74-
>>> image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
75-
>>> result = inferencer.predict(image)
72+
>>> prediction = inferencer.predict(image="path/to/image.jpg")
7673
77-
``result`` will be an ``ImageResult`` object containing the prediction
74+
Alternatively we can also pass the image as a PIL image or numpy array:
75+
76+
>>> from PIL import Image
77+
>>> image = Image.open("path/to/image.jpg")
78+
>>> prediction = inferencer.predict(image=image)
79+
80+
>>> import numpy as np
81+
>>> image = np.random.rand(224, 224, 3)
82+
>>> prediction = inferencer.predict(image=image)
83+
84+
``prediction`` will be an ``ImageResult`` object containing the prediction
7885
results. For example, to visualize the heatmap, we can do the following:
7986
8087
>>> from matplotlib import pyplot as plt
@@ -180,11 +187,26 @@ def predict(
180187
Returns:
181188
ImageResult: Prediction results to be visualized.
182189
"""
190+
# Convert file path or string to image if necessary
191+
if isinstance(image, str | Path):
192+
image = Image.open(image)
193+
194+
# Convert PIL image to numpy array
195+
if isinstance(image, Image.Image):
196+
image = np.array(image, dtype=np.float32)
197+
if not isinstance(image, np.ndarray):
198+
msg = f"Input image must be a numpy array or a path to an image. Got {type(image)}"
199+
raise TypeError(msg)
200+
201+
# Normalize numpy array to range [0, 1]
202+
if image.dtype != np.float32:
203+
image = image.astype(np.float32)
204+
if image.max() > 1.0:
205+
image /= 255.0
206+
207+
# Check if metadata is provided, if not use the default metadata.
183208
if metadata is None:
184209
metadata = self.metadata if hasattr(self, "metadata") else {}
185-
if isinstance(image, str | Path):
186-
image = np.array(Image.open(image)).astype(np.float32) / 255.0
187-
188210
metadata["image_shape"] = image.shape[:2]
189211

190212
processed_image = self.pre_process(image)

0 commit comments

Comments
 (0)