Search code examples
djangodjango-modelsdjango-rest-frameworkpython-requestshttp-post

How to convert Django uploadedfile.InMemory into numpy array or Image


#Views.py-- I want to convert uploaded image file into numpy array(cv2.imread)

def upload(request):
  if request.method == 'POST' and request.FILES['image_file']:
    f = request.FILES['image_file']
    myfile = str(f.read())
    array_np = cv2.imread(myfile)

Solution

  • You can convert the byte into int and decode it using cv2.imdecode. Then you will get a cv2 image array.

    image = cv2.imdecode(numpy.frombuffer(myfile , numpy.uint8), cv2.IMREAD_UNCHANGED)