I wanted to convert the PIL Image object into a numpy array. I tried using the following codes it showing an error
TypeError Traceback (most recent call last) <ipython-input-133-0898103f22f0> in <module>()
1 image_path = 'test/28/image_05230.jpg'
----> 2 image = process_image(image_path)
3 imshow(image)
<ipython-input-129-e036faebfd31> in process_image(image_path)
24 # normalize
25 print(type(image))
---> 26 image_arr = np.array(image) / 255
27 mean = np.array([0.485, 0.456, 0.406])
28 std_dv = np.array( [0.229, 0.224, 0.225])
TypeError: unsupported operand type(s) for /: 'Image' and 'int'
from PIL import Image
image = Image.open(image_path)
image = np.asarray(image) / 255
I also tried with this code image = np.array(image) / 255 it's showing the same error. (code below)
from PIL import Image
image = Image.open(image_path)
image = np.array(image) / 255
This error occurs only when I used the above code in below function
def convert_pil_to_numpy_array(image_path):
# Load Image an open the image
from PIL import Image
image = Image.open(image_path)
width = image.size[0]
height = image.size[1]
if width > height:
image.thumbnail((500, 256))
else:
image.thumbnail((256, 500))
left_margin = (image.width - 224) / 2
lower_margin = (image.height - 224) / 2
upper_margin = lower_margin + 224
right_margin = left_margin + 224
image = image.crop((left_margin, upper_margin, right_margin, lower_margin))
# normalize
print(type(image))
image_arr = np.array(image) / 255
mean = np.array([0.485, 0.456, 0.406])
std_dv = np.array( [0.229, 0.224, 0.225])
image_arr = (image_arr - mean)/std_dv
return image_arr
