Can an uploaded image be loaded directly by cv2?
If working with BaseHTTPRequestHandler, one should first create a FieldStorage
form:
fm = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'})
then:
if "file" in fm:
image = cv2.imdecode(np.frombuffer(fm['file'].file.read(), np.uint8), cv2.IMREAD_UNCHANGED)
Also, note that fromstring
is deprecated, and that's why I'm updating davidism's answer with frombuffer
.
Build a numpy array using the uploaded data. Decode this array using cv2.
img = cv2.imdecode(numpy.fromstring(request.files['file'].read(), numpy.uint8), cv2.IMREAD_UNCHANGED)
Prior to OpenCV 3.0, use cv2.CV_LOAD_IMAGE_UNCHANGED
instead.
See also: Python OpenCV load image from byte string