I am evaluating a Tensorflow model on open cv video frames. I need to reshape the incoming PIL image into reshaped numpy array so that i can run inference on it.
But i see that the conversion of the PIL image to numpy array is taking around 900+ milliseconds on my laptop with 16 GiB memory and 2.6 GHz Intel Core i7 processor. I need to get this down to a few milliseconds so that i can process multiple frames per second on my camera.
Can anyone suggest how to make the below method run faster?
def load_image_into_numpy_array(pil_image): (im_width, im_height) = pil_image.size data = pil_image.getdata() data_array = np.array(data) return data_array.reshape((im_height, im_width, 3)).astype(np.uint8)
On further instrumentation i realized that
np.array(data) is taking the bulk of the time… close to 900+ milliseconds. So conversion of the image data to numpy array is the real culprit.
You can just let numpy handle the conversion instead of reshaping yourself.
def pil_image_to_numpy_array(pil_image): return np.asarray(pil_image)
You are converting image into (height, width, channel) format. That is default conversion numpy.asarray function performs on PIL image so explicit reshaping should not be neccesary.
Answered By – unlut