Skip to content
Advertisement

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

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:Usersjoyan.condaenvstensorflow-djangolibsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "C:Usersjoyan.condaenvstensorflow-djangolibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "H:Projects + Programming ProjectsAuto Chloroplantdetectionviews.py", line 50, in uploadImage
    test_img=image.load_img(img,target_size=(48,48))
  File "C:Usersjoyan.condaenvstensorflow-djangolibsite-packageskeras_preprocessingimageutils.py", line 113, in load_img
    with open(path, 'rb') as f:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile```

Advertisement

Answer

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()
Advertisement