Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an uploaded image be loaded directly by cv2?

I have an uploaded file in memory. I want to manipulate the file with cv2. Currently, I write the file to disk then read it with cv2. How can I skip writing the file and load it directly with cv2?

file = request.files['file']
# if file and allowed_file(file.filename):

# save file            
filename = secure_filename(file.filename)
file_path = os.path.join(dressrank.config['SHOW_IMG_FOLDER'], filename);
file.save(file_path)
img_path = file_path

# COLOR FATURE EXTRACTION
img = read_img(img_path)
img =img_resize(img, 500)
like image 421
erogol Avatar asked Dec 17 '14 03:12

erogol


People also ask

How do I import an image into an OpenCV in Python?

import cv2 #Import openCV import sys #import Sys. Sys will be used for reading from the command line. We give Image name parameter with extension when we will run python script #Read the image. The first Command line argument is the image image = cv2.

What is cv2 in image processing?

It is one of the most widely used tools for computer vision and image processing tasks. It is used in various applications such as face detection, video capturing, tracking moving objects, object disclosure, nowadays in Covid applications such as face mask detection, social distancing, and many more.


2 Answers

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

like image 63
davidism Avatar answered Oct 01 '22 12:10

davidism


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.

like image 45
Catalin Pirvu Avatar answered Oct 01 '22 13:10

Catalin Pirvu