Skip to content
Advertisement

Error while reading image using cv2.imread() in Django views.py

I am trying to apply image processing on an image which i’m loading through cv2.imread() in Django’s views.py file, but i’m getting an AttributeError everytime.

Following is the hierarchy

Heirarchy


views.py through which i’m trying to read temp321.jpg :

def process_image(request):
    url = "static/images/temp321.jpg"
    a = cv2.imread(url)
    r, c = a.shape


Error which i’m getting:

Error message snapshot

What am i doing wrong?

Advertisement

Answer

This error indicates that a is None. With a being the result of the call to cv2.imread

If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix

This is from the cv2 c documentation. This translates to None in python. So the problem essentially is that your file is not being read.

The solution: If you have setup the PROJECT_ROOT variable properly in your settings.py file

os.path.join(PROJECT_ROOT, "static/images/temp321.jpg")

If you don’t have PROJECT_ROOT setup, add to settings.py

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

Note that you may still have trouble if you are doing this in production because the webserver may not be allowed to read from that directory. In that case you will need to change file system permissions

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement