'Opencv with Sanic async causes segmentation fault

I have created a Sanic API in Python where the user sends a request, and I create a task using asyncio to process the request using opencv. I'm using the asyncio.create_task in order to return 200 immediately instead of having the frontend waiting for my endpoint to process the image. The problem is that when the first cv2 function is called, Python crashes with segmentation fault.

Here is the entry-point to my Sanic app:

@process_image_route.route('/startProcessing/', methods=['POST'])
async def processing_endpoint(request):
    content = request.json
    asyncio.create_task(process(content))
    return json({'status': 'Processing started successfully'}, 200)

async def process(content):
    # fetch image
    image = load_image(content['imageUrl']) # function that loads image from URL
    processed_image = process_image(image) # This works fine - no opencv is used here just some basic transforms using PIL. This function is NOT async
    cv_processed_image = cv_process_image(processed_image) # this crashes as it uses opencv. This function is NOT async
    write_image_to_S3(cv_processed_image) # works fine is no opencv used 
    push_to_frontend()  # works fine if no opencv used

def cv_process_image(image):
    areas_num, labels = cv2.connectedComponents(image.astype(np.uint8))
    # here is the crash          ^
    # do stuff 

I know that problem is related with threads but I have no idea how to work around it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source