Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV imread hanging when called from a web request

This is probably one of the strangest errors that I have ever ran into when using OpenCV. There is a lot going on, so let me try to explain this to the best of my ability.

  1. I am using the Django web framework and OpenCV (cv2) together. I am trying to read a file off my disk from a view in Django.

    imagePath = os.path.dirname(__file__) + "/1.jpg"
    

    Basically, in the same path as views.py file there is a file called "1.jpg". That is all this code is doing. Easy enough. But the next step is where things get crazy.

  2. Now, I want to read the image file located at 'imagePath'. This requires a call to cv2.imread

    image = cv2.imread(imagePath)
    

    But this is where my problems start. Somehow, Apache (or maybe even OpenCV, I can't tell) starts hanging and the file is never loaded. There is no error message, no nothing.

Doing some detective work I decided to try out an older version of OpenCV (import cv). Strangely enough, when I call cv.LoadImage(imagePath) Apache does not hang and my image is loaded just fine. I have absolutely no idea why.

A potential work around for my problem is to use PIL.

from PIL import Image
import numpy as np
image = Image.open(imagePath)
image = np.asarray(image)

One again, using PIL Apache does not hang and I can proceed as normal with my image represented as numpy array and apply any of the cv2 functions to it.

However, I'm not one to settle for workarounds and the fact that cv2.imread is hanging really bothers me.

Has anyone ran into this before?

EDIT: Using cv.imread from a Python shell works fine, it's just from an Apache request that the hang happens.

>>> import cv2
>>> image = cv2.imread("1.jpg")
>>> image.shape
(400, 344, 3)
>>> 
like image 202
Adrian Rosebrock Avatar asked Jul 03 '12 16:07

Adrian Rosebrock


1 Answers

I had a similar issue and found a fix -> just add to your apache configuration:

WSGIScriptAlias application-group=%{GLOBAL}

Apparently it happens when you have an extension module not designed to work in sub interpreter. The above forces it to run in main interpreter.

Sources: django apache mod-wsgi hangs on importing a python module from .so file http://blog.rtwilson.com/how-to-fix-flask-wsgi-webapp-hanging-when-importing-a-module-such-as-numpy-or-matplotlib/

like image 161
Hugo Flick Avatar answered Sep 28 '22 11:09

Hugo Flick