Forums

Getting error Expected Ptr<cv::UMat> for argument 'src' while resizing the cv2 image. Please asvise how to resolve this issue

.

Traceback (most recent call last):
  File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/clonesangram/django_projects/ocrsite/ocr/views.py", line 187, in image_upload_view
    return render(request, 'ocr/index1.html', {'form': form, 'img_obj': img_obj, 'text': text_detector(image)})
  File "/home/clonesangram/django_projects/ocrsite/ocr/Test_OCR_Img.py", line 15, in text_detector
    image = cv2.resize(np.float32(image), (320, 320), interpolation=cv2.INTER_AREA)

Exception Type: TypeError at /ocr/upload/
Exception Value: Expected Ptr<cv::UMat> for argument 'src'

[edit by admin: formatting]

Does your code work on another machine? Is the version of OpenCV identical there?

I checked from my local pycharm and the current version I am using is 4.3.0. And in here(pythonanywhere) it is 4.5.1. So, there is a version difference.

Did you try running it with the same version as you have on your local machine?

no, let me try this

Let us know if it works.

I have updated the version to 4.3.0 same as my local machine but still getting the same error

Environment:

Request Method: POST
Request URL: http://clonesangram.pythonanywhere.com/ocr/upload/

Django Version: 3.1.5
Python Version: 3.8.0
Installed Applications:
['ocr.apps.OcrConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'crispy_forms',
 'django.contrib.humanize',
 'django_extensions',
 'rest_framework',
 'social_django']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/clonesangram/django_projects/ocrsite/ocr/views.py", line 192, in image_upload_view
    return render(request, 'ocr/index1.html', {'form': form, 'img_obj': img_obj, 'text': text_detector(path)})
  File "/home/clonesangram/django_projects/ocrsite/ocr/Test_OCR_Img.py", line 15, in text_detector
    image = cv2.resize(np.float32(image), (640, 320), interpolation=cv2.INTER_AREA)

Exception Type: TypeError at /ocr/upload/
Exception Value: Expected Ptr<cv::UMat> for argument 'src'

Do you think my images are getting corrupted while uploading them through pythonanywhere web application or is there any other reason.

[edit by admin: formatting]

the ocr python file is running fine separately if I run it from pythonanywehere.com but when I am running or calling it from django3 views the uploaded image file it is not able to recognize. This is my view

def image_upload_view(request):
    """Process images uploaded by users"""
    #profile = get_object_or_404(OcrRegister, user=request.user)
    if request.method == 'POST':
        form = ImageForm(data=request.POST, files=request.FILES)
        if form.is_valid():

            form.save()

            img_obj = form.instance

            pic = Image.objects.filter(id=1).first()

            str_path = pic.image.name
            path = Path(str_path)



            return render(request, 'ocr/index1.html', {'form': form, 'img_obj': img_obj, 'text': text_detector(path)})

[edit by admin: formatting]

How did you install the new version of cv2? That is, which package did you install with pip? If it wasn't opencv-contrib-python-headless, could you try uninstalling it and then installing that package -- it's a version of OpenCV with all of its dependencies included, so it should be more reliable.

I typed this command pip install opencv-python==4.3.0.36

still getting the same error

Is that after having uninstalled opencv-python, and installing opencv-contrib-python-headless instead?

yes, i unstalled opencv-python==4.3.0.36 and installed opencv-contrib-python-headless

Could you show the new traceback?

Environment:

Request Method: POST Request URL: http://clonesangram.pythonanywhere.com/ocr/upload/

Django Version: 3.1.5 Python Version: 3.8.0 Installed Applications: ['ocr.apps.OcrConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'django.contrib.humanize', 'django_extensions', 'rest_framework', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last): File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, callback_args, *callback_kwargs) File "/home/clonesangram/django_projects/ocrsite/ocr/views.py", line 192, in image_upload_view return render(request, 'ocr/index1.html', {'form': form, 'img_obj': img_obj, 'text': text_detector(path)}) File "/home/clonesangram/django_projects/ocrsite/ocr/Test_OCR_Img.py", line 15, in text_detector image = cv2.resize(np.float32(image), (640, 320), interpolation=cv2.INTER_AREA)

Exception Type: TypeError at /ocr/upload/ Exception Value: Expected Ptr<cv::UMat> for argument 'src'

In order to eliminate variables, try running the OCR code on an image that you know works from a console with your virtualenv enabled so that we can see whether the issue is actually with the library or with what you are passing to it.

ocr code is running fine if I run it from the console. error is only coming when I am calling the ocr code from django3 views.

Below is my views code:

def image_upload_view(request): """Process images uploaded by users""" #profile = get_object_or_404(OcrRegister, user=request.user) if request.method == 'POST': form = ImageForm(data=request.POST, files=request.FILES) if form.is_valid():

        #form.save()
        # Get the current instance object to display in the template
        img_obj = form.instance

        user_pr = form.save(commit=False)
        user_pr.image = request.FILES['image']
        file_name = user_pr.image.url.split('/')[-1]

        #pic = Image.objects.filter(id=5).first()
        #url = "https://www.pythonanywhere.com/user/clonesangram/files/home/clonesangram/django_projects/ocrsite/media/images/image4.jpg"

        #resp = urlopen(url)
        #image = np.asarray(bytearray(resp.read()), dtype="uint8")
        #image = cv2.imdecode(image, cv2.IMREAD_COLOR)

        #str_path = pic.image.name
        #path = Path(str_path)


        user_pr.save()

        image = cv2.imread(str(file_name))

        return render(request, 'ocr/index1.html', {'form': form, 'img_obj': img_obj, 'text': text_detector(image)})

else:
    form = ImageForm()
return render(request, 'ocr/index1.html', {'form': form})

Then there are 2 possibilities:

  • you're using a different version of Python/virtualenv in your web app and that explains the difference in behaviour
  • the data that you're passing in to the call in the web app is different to what you're passing in when you run it in the console. Check that and then, if there are differences, follow the variables back to see why they are different and what you might need to do to fix the view code.

Now it worked but only for one image. I am trying for other images but getting the same error. The image size and the dimensions are relatively the same and of the same file type(JPG) as the tested image that worked but I don't know why it is not working for other images.

According to this bug report on GitHub that error can appear if you somehow pass None into opencv (they note that it's not a very helpful error message). Perhaps you could try printing out the file_name and the image object that you're working with and see if that is the case? If you do something like this in your Django code:

print(f"file_name is {file_name}", flush=True)
print(f"image is {image}", flush=True)

...then you'll get the output in the website's server log (not the error log) and perhaps that will help work out what is going on.

Thanks, I will look into this

Yes, you are right. Image is coming None.

2021-03-21 07:20:40 file_name is image0.jpg
2021-03-21 07:20:40 image is None
2021-03-21 07:20:40 Internal Server Error: /ocr/upload/#012Traceback (most recent call last):#012  File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner#012    response = get_response(request)#012  File "/home/clonesangram/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response#012    response = wrapped_callback(request, *callback_args, **callback_kwargs)#012  File "/home/clonesangram/django_projects/ocrsite/ocr/views.py", line 207, in image_upload_view#012    image = cv2.resize(np.float32(image), (640, 320), interpolation=cv2.INTER_AREA)#012TypeError: Expected Ptr<cv::UMat> for argument 'src'
(django3) 07:22 /var/log $

[edit by admin: formatting]

I have seen multiple suggestions on the internet, and most of them are saying that we need to install libjpeg. Can you please install it for me. I can't use sudo in the console. Below is the command:

sudo apt-get install libjpeg-dev libjpeg libjpeg-dbg libjpeg-progs

I think we already have all of that installed.

Looking at the image filename that you're using there, I think that that might be the problem. It's trying to load an image from the file "image0.jpg" in its current working directory -- the one defined on the "Web" page under "Working directory". Perhaps if the file path that you provide to it does not exist, cv2.imread just returns None.

How are you getting the image? I see that you seem to be getting a URL in your form post, and then just stripping all of the URL off apart from the filename at the end.

yes, I stripped the url to get the filename. I have fixed this issue now. I used pillow library to open the image and later converting it to cv2 readable image.

Now I am giving proper path using os library (os.path.dirname(os.path.dirname(os.path.abspath(file)))) .

I think it was a directory issue. When I used the pillow for the first time it was giving me an error like "image not found in this path", then I tried this(os.path) and it worked.

Thanks for helping me

Glad to hear that you made it work!