@@ -69,12 +69,19 @@ class OpenVINOInferencer(Inferencer):
69
69
metadata is loaded from the ``metadata.json`` file. To make a prediction,
70
70
we can simply call the ``predict`` method:
71
71
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")
76
73
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
78
85
results. For example, to visualize the heatmap, we can do the following:
79
86
80
87
>>> from matplotlib import pyplot as plt
@@ -180,11 +187,26 @@ def predict(
180
187
Returns:
181
188
ImageResult: Prediction results to be visualized.
182
189
"""
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.
183
208
if metadata is None :
184
209
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
-
188
210
metadata ["image_shape" ] = image .shape [:2 ]
189
211
190
212
processed_image = self .pre_process (image )
0 commit comments