def predict(): data = {"success": False} if flask.request.method == "POST": if flask.request.files.get("image"): image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) image = prepare_image( image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) image = image.copy(order="C") k = str(uuid.uuid4()) d = {"id": k, "image": helpers.base64_encode_image(image)} db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) while True: output = db.get(k) if output is not None: output = output.decode("utf-8") data["predictions"] = json.loads(output) db.delete(k) break time.sleep(settings.CLIENT_SLEEP) data["success"] = True return flask.jsonify(data)
def get_tags(): data = {"success": False} if request.method == "POST": if request.files.get("image"): image = request.files["image"].read() image = Image.open(io.BytesIO(image)) image = preprocess_image( image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) image = image.copy(order="C") image_id = str(uuid.uuid4()) image = helpers.base64_encode_image(image) image_dict = {"id": image_id, "image": image} db.rpush(settings.IMAGE_QUEUE, json.dumps(image_dict)) while True: output = db.get(image_id) if output is not None: output = output.decode("utf-8") data["tags"] = json.loads(output) db.delete(image_id) break time.sleep(settings.CLIENT_SLEEP) data["success"] = True return jsonify(data)
def post(self): data = {"success": False} files = request.files.to_dict() if files.get("image"): image = Image.open(io.BytesIO(files['image'].read())) image = prepare_image(image) # get confidence from query or set to 0.7 confidence = float(request.args.get('confidence', 0.7)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it image = image.copy(order="C") # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) image_shape = image.shape image = helpers.base64_encode_image(image) d = { "id": k, "image": image, "shape": image_shape, 'confidence': confidence } db.rpush(settings.SEGMENT_IMAGE_QUEUE, json.dumps(d)) timeDelta = datetime.datetime.now() + datetime.timedelta(minutes=3) # keep looping until our model server returns the output # predictions while True: # attempt to grab the output predictions output = db.get(k) # check to see if our model has classified the input # image if output is not None: # add the output predictions to our data # dictionary so we can return it to the client output = output.decode("utf-8") data["predictions"] = json.loads(output) # delete the result from the database and break # from the polling loop db.delete(k) break # sleep for a small amount to give the model a chance # to classify the input image time.sleep(settings.CLIENT_SLEEP) if datetime.datetime.now() > timeDelta: print('timeout') break # indicate that the request was a success if "predictions" in data: data["success"] = True else: db.delete(k) return "System error", 500 # return the data dictionary as a JSON response return jsonify(data)
def predict(): # initialize the data dictionary that will be returned from the # view data = {"success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get("image"): # read the image in PIL format and prepare it for # detection image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) rfid = flask.request.files["rfid"] tempFileRFIDPath = tempfile.NamedTemporaryFile().name + '.csv' rfid.save(tempFileRFIDPath) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it image = np.array(image) print(image.shape, image.dtype) image = np.expand_dims(image, axis=0) image = image.copy(order='C') # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) image = helpers.base64_encode_image(image) print(len(image)) d = {"id": k, "image": image} db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) # keep looping until our model server returns the output # predictions while True: # attempt to grab the output predictions output = db.get(k) # check to see if our model has classified the input # image if output is not None: # add the output predictions to our data # dictionary so we can return it to the client output = output.decode("utf-8") data["predictions"] = json.loads(output) # delete the result from the database and break # from the polling loop db.delete(k) break # sleep for a small amount to give the model a chance # to classify the input image time.sleep(settings.CLIENT_SLEEP) # indicate that the request was a success data["success"] = True # return the data dictionary as a JSON response return flask.jsonify(data)
def predict(): # initialize the data dictionary that will be returned from the # view app_id = request.args.get('app-id') logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) logging.info('app-id = ' + app_id) data = {"success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get("image"): # read the image in PIL format and prepare it for # classification image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) image = prepare_image( image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it image = image.copy(order="C") # generate an ID for the classification then add the # classification ID + image to the queue k = app_id + '.' + str(uuid.uuid4()) print(k) image = helpers.base64_encode_image(image) d = {"id": k, "image": image} db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) # keep looping until our model server returns the output # predictions while True: # attempt to grab the output predictions output = db.get(k) # check to see if our model has classified the input # image if output is not None: # add the output predictions to our data # dictionary so we can return it to the client output = output.decode("utf-8") data["predictions"] = json.loads(output) # delete the result from the database and break # from the polling loop db.delete(k) break # sleep for a small amount to give the model a chance # to classify the input image time.sleep(settings.CLIENT_SLEEP) # indicate that the request was a success data["success"] = True # return the data dictionary as a JSON response return flask.jsonify(data)
def image_enqueue(image_path): start_time = time.time() with open(image_path, "rb") as imageFile: # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) image = helpers.base64_encode_image(imageFile.read()) d = {"id": k, "path": image_path, "image": image} DB.rpush(settings.IMAGE_QUEUE, json.dumps(d)) print("* Push to redis %d ms" % int(round((time.time() - start_time) * 1000)))
def predict(): # initialize the data dictionary that will be returned from the # view data = {"success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get("image"): # read the image in PIL format and prepare it for # classification image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) image = prepare_image(image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it image = image.copy(order="C") # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) image = helpers.base64_encode_image(image) d = {"id": k, "image": image} db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) # keep looping until our model server returns the output # predictions while True: # attempt to grab the output predictions output = db.get(k) # check to see if our model has classified the input # image if output is not None: # add the output predictions to our data # dictionary so we can return it to the client output = output.decode("utf-8") data["predictions"] = json.loads(output) # delete the result from the database and break # from the polling loop db.delete(k) break # sleep for a small amount to give the model a chance # to classify the input image time.sleep(settings.CLIENT_SLEEP) # indicate that the request was a success data["success"] = True # return the data dictionary as a JSON response return flask.jsonify(data)
def post_detect(image, cnts, width, height): image = image.copy(order="C") image = helpers.base64_encode_image(image) payload = {"image": image, 'cnts': cnts, 'width': width, 'height': height} # submit the request r = requests.post(KERAS_REST_API_URL, json=json.dumps(payload)).json() # print (image.shape) if r["success"]: # loop over the predictions and display them return r["predictions"] else: return []
def ocr_business_license(): # 初始化最终输出数据字典 data = {"success": False} # 通过POST请求获取图像数据 if flask.request.method == "POST": if flask.request.files.get("image"): # 读取图片并做预处理 image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) if image.mode != "RGB": image = image.convert("RGB") image = img_to_array(image) image = np.expand_dims(image, axis=0) # 为图像生成对应的id,并将图像id、图像以及图像尺寸加入到队列中 k = str(uuid.uuid4()) d = { "id": k, "image": helpers.base64_encode_image(image), "shape": image.shape } db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) # 开始循环,直到模型服务器返回结果退出while循环 while True: # 尝试从数据库中获取对应id的图像的ocr结果 output = db.get(k) # 检查返回的结果是否为空,不为空则将结果加入到最终输出的字典中 if output is not None: output = output.decode("utf-8") data["result"] = json.loads(output) # 已获得结果,将该id对应的结果从数据库中删除 db.delete(k) break # 一定的延时,给予模型一定的检测预测时间 time.sleep(settings.CLIENT_SLEEP) data["success"] = True # 将数据字典以json的形式返回 return flask.jsonify(data)
def image_enqueue(image_path): start_time = time.time() with open(image_path, "rb") as imageFile: # generate an ID for the classification then add the # classification ID + image to the queue image = helpers.base64_encode_image(imageFile.read()) read_time = time.time() print("* Read and base64 %d ms" % int(round(read_time - start_time) * 1000)) # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) # Streaming schema d = {"id": str(k), "path": image_path, "image": image} DB.xadd(settings.IMAGE_STREAMING, d) print("* Push to Redis %d ms" % int(round((time.time() - read_time) * 1000))) print("* Total %d ms" % int(round((time.time() - start_time) * 1000)))
def image_enqueue(image_path): # Imaging you already have a image MAT start_time = time.time() # ND array image = cv2.imread(image_path, cv2.IMREAD_COLOR) # Use Png. It is lossless. image = cv2.imencode(".png", image)[1] # PNG compression, 10% reduction in size # image = cv2.imencode(".png", image, [cv2.IMWRITE_PNG_COMPRESSION, 9])[1] # If change to JPEG, the size will be 75% smaller, but ND will be different # image = cv2.imencode(".jpeg", image)[1] # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) image = helpers.base64_encode_image(image) d = {"id": k, "path": image_path, "image": image} DB.rpush(settings.IMAGE_QUEUE, json.dumps(d)) print("* Push to redis %d ms" % int(round((time.time() - start_time) * 1000)))
def age_gender_predict(image_np): data = {"success": False} orig_height, orig_width, _ = image_np.shape ''' # 1. Compose and send the request to db ''' #image_np = preprocess_image_pd(image_np) #image_np = image_np.copy(order="C") image_id = str(uuid.uuid4()) input_data = { 'id': image_id, 'image': helpers.base64_encode_image(image_np) } db.rpush(settings.IMAGE_QUEUE, json.dumps(input_data)) ''' # 2. Loop the db to get the response ''' while True: output_data = db.get(image_id) if output_data is not None: output_data = output_data.decode("utf-8") output_data = json.loads(output_data) output_data['out_boxes'] = np.array( output_data['out_boxes']).astype('float32') output_data['out_ages'] = np.array( output_data['out_ages']).astype('int64') output_data['out_genders'] = np.array(output_data['out_genders']) data["predictions"] = output_data db.delete(image_id) break time.sleep(settings.CLIENT_SLEEP) data["success"] = True return data
def predict(name): data = {"success": False} if flask.request.method == "POST": if flask.request.files.get("image"): response = flask.request.files["image"] data["filename"] = response.filename image = Image.open(io.BytesIO(response.read())) image = prepare_image( image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it image = image.copy(order="C") imageID = str(uuid.uuid4()) image = helpers.base64_encode_image(image) d = {"id": imageID, "image": image} # db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) s3_path = s3.create_folder_with_timestamp(imageID) s3.put(s3_path, json.dumps(d)) # sqs.send(imageID) sns.publish(s3_path, name) while True: output = db.get(imageID) if output is not None: output = output.decode("utf-8") data["predictions"] = json.loads(output) db.delete(imageID) break time.sleep(settings.CLIENT_SLEEP) data["success"] = True return flask.jsonify(data)
def predict(): data = {"success": False} if flask.request.method == "POST": print("Start predict ...") if flask.request.files.get("video"): video = flask.request.files["video"].read() print(len(video)) if flask.request.files.get("image"): image = flask.request.files["image"].read() npimg = np.fromstring(image, np.uint8) image = cv2.imdecode(npimg, 3) height=image.shape[1] print("hape img:",image.shape) k = str(uuid.uuid4()) image = helpers.base64_encode_image(image).decode('utf-8') d = {"id": k, "image": image,"height":height} db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) while True: output = db.get(k) if output is not None: data["predictions"] = json.loads(output) db.delete(k) break # time.sleep(settings.CLIENT_SLEEP) data["success"] = True else: print("err") print(data) return flask.jsonify(data)
def predict(): """ Predicat the image class. Send the image as post request. .. code-block:: bash curl -X POST -F [email protected] 'http://localhost/predict' Return: json of classes from predication .. code-block:: json { "predictions": [ { "label": "beagle", "probability": 0.9461532831192017 }, { "label": "bluetick", "probability": 0.031958963721990585 }, { "label": "redbone", "probability": 0.0066171870566904545 }, { "label": "Walker_hound", "probability": 0.003387963864952326 }, { "label": "Greater_Swiss_Mountain_dog", "probability": 0.0025766845792531967 } ], "success": true } """ # initialize the data dictionary that will be returned from the # view data = {"success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get("image"): # read the image in PIL format and prepare it for # classification image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) image = prepare_image( image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it image = image.copy(order="C") # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) image = helpers.base64_encode_image(image) d = {"id": k, "image": image} db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) # keep looping until our model server returns the output # predictions while True: # attempt to grab the output predictions output = db.get(k) # check to see if our model has classified the input # image if output is not None: # add the output predictions to our data # dictionary so we can return it to the client output = output.decode("utf-8") data["predictions"] = json.loads(output) # delete the result from the database and break # from the polling loop db.delete(k) break # sleep for a small amount to give the model a chance # to classify the input image time.sleep(settings.CLIENT_SLEEP) # indicate that the request was a success data["success"] = True # return the data dictionary as a JSON response return flask.jsonify(data)
def predict(): # initialize the data dictionary that will be returned from the # view data = {"success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get("image") or flask.request.json.get('image'): print('got image') if flask.request.files.get("image"): # read the image in PIL format and prepare it for # classification test_image = flask.request.files["image"].read() test_image = Image.open(io.BytesIO(test_image)) test_image = prepare_image( test_image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it test_image = test_image.copy(order="C") test_image = helpers.base64_encode_image(test_image) print(test_image[:20]) # check format else: print('request.json.get') test_image = request.json.get('image') test_image = test_image[test_image.find('base64,') + 7:] print(test_image[:20]) fh = open("out.jpg", "wb") fh.write(test_image.decode('base64')) fh.close() test_file = 'out.jpg' test_image = Image.open(test_file) test_image = prepare_image( test_image, (settings.IMAGE_WIDTH, settings.IMAGE_HEIGHT)) # ensure our NumPy array is C-contiguous as well, # otherwise we won't be able to serialize it test_image = test_image.copy(order="C") test_image = helpers.base64_encode_image(test_image) print(test_image[:20]) # check format # generate an ID for the classification then add the # classification ID + image to the queue k = str(uuid.uuid4()) d = {"id": k, "image": test_image} redis_db.rpush(settings.IMAGE_QUEUE, json.dumps(d)) # keep looping until our model server returns the output # predictions while True: # attempt to grab the output predictions output = redis_db.get(k) # check to see if our model has classified the input # image if output is not None: # add the output predictions to our data # dictionary so we can return it to the client output = output.decode("utf-8") data["predictions"] = json.loads(output) # delete the result from the database and break # from the polling loop redis_db.delete(k) break # sleep for a small amount to give the model a chance # to classify the input image time.sleep(settings.CLIENT_SLEEP) # indicate that the request was a success data["success"] = True else: print('failed to get image') # return the data dictionary as a JSON response return flask.jsonify(data)
def send_img(self, topic, img): i = process_image(img) i = base64_encode_image(i) self._produce(topic, i)