TypeError: expected str, bytes or os.PathLike object, not JpegImageFile (or PngImageFile) in Django

Issue

When I am uploading a picture to check a picture according to tensorflow h5 model, I am loading the image using load_model of tensorflow.keras.models but it is not accepting. For JPG, it is showing TypeError: expected str, bytes or os.PathLike object, not JpegImageFile and for PNG, it is showing as TypeError: expected str, bytes or os.PathLike object, not PngImageFile. What to do now?

I tried the code with raw python but it worked nicely.

Code:

#views.py

import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image

pic = request.FILES['image']
img = Image.open(pic)
detection=load_model(os.path.join(settings.BASE_DIR,'static/auto_chloro_model.h5'))
test_img=image.load_img(img,target_size=(48,48))
test_img=image.img_to_array(test_img)
test_img=np.expand_dims(test_img,axis=0) 
result=detection.predict(test_img)
a=result.argmax()
print(a)

#models.py

class images(models.Model):
   img_main = models.ImageField(upload_to="images_api", default="") 

   def __str__(self):
        return self.product_name

#forms.py

class imageForm(forms.ModelForm):
    image = forms.ImageField()
  
    class Meta:
        model = images
        fields = ['image']

Traceback:

Traceback (most recent call last):
  File "C:\Users\joyan\.conda\envs\tensorflow-django\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\joyan\.conda\envs\tensorflow-django\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "H:\Projects + Programming Projects\Auto Chloro\plant\detection\views.py", line 50, in uploadImage
    test_img=image.load_img(img,target_size=(48,48))
  File "C:\Users\joyan\.conda\envs\tensorflow-django\lib\site-packages\keras_preprocessing\image\utils.py", line 113, in load_img
    with open(path, 'rb') as f:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile```

Solution

This solved my problem.

pic = request.FILES['image']
img_new = images(img_main= pic)
img_new.save()
detection=load_model(os.path.join(settings.BASE_DIR,'staticfiles/auto_chloro_model.h5'))
test_img=image.load_img(img_new.img_main.path,target_size=(48,48))
test_img=image.img_to_array(test_img)
test_img=np.expand_dims(test_img,axis=0) 
result=detection.predict(test_img)
a=result.argmax()

Answered By – Joyanta J. Mondal

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published