def image(): try: image_file = request.files['image'] # get the image # Set an image confidence threshold value to limit returned data threshold = request.form.get('threshold') if threshold is None: threshold = 0.5 else: threshold = float(threshold) # Get the target object class to be detected (alternative: request.headers['target_class']) target_class = request.form.get('target_class') # finally run the image through tensor flow object detection image_object = Image.open(image_file) objects = object_detection_api.get_objects(image_object, target_class, threshold) json_output = json.dumps(objects, indent=4, sort_keys=True, default=str) response = Response(response=json_output, status=200, mimetype="application/json") return response except Exception as e: return Response(response=json.dumps({'error': e}, indent=4, sort_keys=True, default=str), status=500, mimetype="application/json")
def image(): try: image_file = request.files['image'].stream # get the image #dobox=1 if request.args.get('withbox','no')=='yes' else 0 #print('dobox',dobox) # Set an image confidence threshold value to limit returned data threshold = request.form.get('threshold') if threshold is None: threshold = 0.5 else: threshold = float(threshold) # finally run the image through tensor flow object detection` image_object = Image.open(image_file) im = image_object.copy().convert('RGB') objects = object_detection_api.get_objects(im, threshold) #if dobox: # img = object_detection_api.get_objects_image(im) # import base64 # from io import BytesIO # buffered = BytesIO() # img.save(buffered, format="JPEG") # img_str = base64.b64encode(buffered.getvalue()) # imgt="""<img src="data:image/jpeg;base64,{0}"/>""".format(img_str) # return json.dumps(objects)+"<br><br><br>"+imgt return objects except Exception as e: print('POST /image error: %e' % e) return e
def test(): TEST_IMAGE_PATHS = './test_images/image.jpg' image = Image.open(TEST_IMAGE_PATHS) objects = object_detection_api.get_objects(image) return objects
def test(): PATH_TO_TEST_IMAGES_DIR = 'object_detection/test_images' # cwh TEST_IMAGE_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3)] image = Image.open(TEST_IMAGE_PATHS[0]) objects = object_detection_api.get_objects(image) return objects
def getObject(): startTime = time.time() if request.method == 'GET': threshold = request.args.get('threshold', 0.5) file_name = request.args.get('file_name') objects = object_detection_api.get_objects(file_name, threshold) print("-------getObject total time: %f" % (time.time() - startTime)) return objects return 'method error'
def check(): startTime = time.time() if request.method == 'POST': image_file = request.files['file'] base_path = os.path.abspath(os.path.dirname(__file__)) upload_path = os.path.join(base_path, 'static/upload/') file_name = upload_path + image_file.filename image_file.save(file_name) threshold = float(request.form.get('threshold', 0.5)) objects = object_detection_api.get_objects(file_name, threshold) return objects return 'method error'
def test(): threshold = request.form.get('threshold') PATH_TO_TEST_IMAGES_DIR = 'object_detection/test_images' # cwh TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 2) ][0] threshold = 0.7 img = cv2.imread(TEST_IMAGE_PATHS) outputJson = object_detection_api.get_objects(img, threshold) print(outputJson) return outputJson
def image(): startTime = time.time() if request.method == 'POST': image_file = request.files['file'] base_path = os.path.abspath(os.path.dirname(__file__)) upload_path = os.path.join(base_path, 'static/upload/') file_name = upload_path + image_file.filename image_file.save(file_name) threshold = request.form.get('threshold', 0.5) objects = object_detection_api.get_objects(file_name, threshold) print("-------total time: %f" % (time.time() - startTime)) return render_template('index.html', json_data=objects, img=image_file.filename) return 'method error'
def test(): try: CWD_PATH = os.getcwd() PATH_TO_TEST_IMAGES_DIR = CWD_PATH + '/images' TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ] image = Image.open(TEST_IMAGE_PATHS[0]) objects = object_detection_api.get_objects(image) print('objects :', objects) return objects except Exception as e: print('POST /test error: %e', e) return e
def image(): try: image_file = request.files['image'] threshold = request.form.get('threshold') if threshold is None: threshold = 0.5 else: threshold = float(threshold) image_object = Image.open(image_file) objects = object_detection_api.get_objects(image_object, threshold) return objects except Exception as e: print('POST /image error: %e' % e) return e
def image(): try: image_file = request.files['image'].read() # get the image # Set an image confidence threshold value to limit returned data threshold = request.form.get('threshold') if threshold is None: threshold = 0.7 else: threshold = float(threshold) img = np.array(Image.open(io.BytesIO(image_file))) outputJson = object_detection_api.get_objects(img, threshold) return outputJson except Exception as e: print('POST /image error: %e' % e) return e
def image(): try: image_file = request.files['image'] # get the image # Set an image confidence threshold value to limit returned data threshold = request.form.get('threshold') if threshold is None: threshold = 0.5 else: threshold = float(threshold) # finally run the image through tensor flow object detection` image_object = Image.open(image_file) objects = object_detection_api.get_objects(image_object, threshold) return objects except Exception as e: print('POST /image error: %e' % e) return e
def process_image(): """Process image.""" try: # Get the image. image_file = request.files['image'] # Set an image confidence threshold value to limit returned data. threshold = request.form.get('threshold') if threshold is None: threshold = object_detection_api.THRESHOLD else: threshold = float(threshold) # Run the image through Tensorflow object detection. image_object = Image.open(image_file) objects = object_detection_api.get_objects(image_object, threshold) return objects except Exception as e: print('POST /image error: %e' % e) return e
def image(): try: image_file = request.files['image'] # get the image # print(image_file) # Set an image confidence threshold value to limit returned data threshold = request.form.get('threshold') threshold = 0.6 if threshold is None: threshold = 0.5 else: threshold = float(threshold) # finally run the image through tensor flow object detection` image_object = Image.open(image_file) image_object = np.array(image_object) objects = object_detection_api.get_objects(image_object, threshold) return objects except Exception as e: traceback.print_exc() return 'An ERROR raised on image()' return 'OK'
def image(): try: image_file = request.files['image'] # get the image # Set an image confidence threshold value to limit returned data threshold = request.form.get('threshold') if threshold is None: threshold = 0.5 else: threshold = float(threshold) # finally run the image through tensor flow object detection` image_object = Image.open(image_file) objects = object_detection_api.get_objects(image_object, threshold) return Response(response=objects, status=200, mimetype="application/json") except Exception as e: return Response(response=json.dumps({error: e}, indent=4, sort_keys=True, default=str), status=500, mimetype="application/json")
def test(): """Test API.""" image = Image.open(TEST_IMAGE_PATHS[0]) objects = object_detection_api.get_objects(image) return objects
import object_detection_api import os from PIL import Image # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS. PATH_TO_TEST_IMAGES_DIR = 'object_detection/test_images' #cwh TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ] for image_path in TEST_IMAGE_PATHS: image = Image.open(image_path) response = object_detection_api.get_objects(image) print("returned JSON: \n%s" % response)
def detect_object(image_object, threshold): return object_detection_api.get_objects(image_object, threshold)
def index(): base_path = os.path.abspath(os.path.dirname(__file__)) upload_path = os.path.join(base_path, 'static/') file_name = upload_path + 'test.jpg' objects = object_detection_api.get_objects(file_name) return objects
import object_detection_api import os from PIL import Image # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS. PATH_TO_TEST_IMAGES_DIR = 'C:/tensorflow1/models/research/object_detection/test_images' #cwh TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ] # for image_path in TEST_IMAGE_PATHS: # image = Image.open(image_path) # response = object_detection_api.get_objects(image) # print("returned JSON: \n%s" % response) image = Image.open( 'C:/tensorflow1/models/research/object_detection/test_images/image.jpg') response = object_detection_api.get_objects(image) print("returned JSON: \n%s" % response)
def webhook(): data = request.get_json(force=True) app.logger.info(data) update = telegram.update.Update.de_json(request.get_json(force=True), bot) if update.message.text == '/help': bot.sendMessage(chat_id=update.message.chat_id, text=helpers.help_text()) return 'OK' photo_id, status = helpers.get_is_photo(data) app.logger.info(photo_id) if status == 1: bot.sendMessage( chat_id=update.message.chat_id, text= 'Sorry. Unsupported file type. Please use jpg (jpeg) or png file.') return 'OK' if photo_id: photo = helpers.download_file(app, photo_id, 'photos/downloads/') image = cv2.imread(photo) orig_height, orig_width, _ = image.shape objects = object_detection_api.get_objects(image, THRESHOLD) objects = json.loads(objects) if len(objects) > 1: app.logger.info(objects) font = cv2.FONT_HERSHEY_SIMPLEX result_msg = '' for item in objects: if item['name'] != 'Object': continue x = int(orig_width * item['x']) y = int(orig_height * item['y']) width = int(orig_width * item['width']) height = int(orig_height * item['height']) cv2.rectangle(image, (x, y), (width, height), (0, 255, 0), 2) scope = float('{:.2f}'.format(item['score'] * 100)) cv2.putText(image, item['class_name'] + " - " + str(scope) + '%', (x + 5, y + 20), font, 1, (255, 255, 255), 1, cv2.LINE_AA) result_msg += item['class_name'] + " - " + str(scope) + '% \n' new_name = 'photos/detected/photo_detected_' + str( photo_id) + '.jpg' cv2.imwrite(new_name, image) bot.sendPhoto(update.message.chat_id, photo=open(new_name, 'rb'), caption="Result") bot.sendMessage(chat_id=update.message.chat_id, text=result_msg) else: bot.sendMessage( chat_id=update.message.chat_id, text='Sorry! No objects were found. Please try another photo.') return 'OK' bot.sendMessage(chat_id=update.message.chat_id, text='Please send a photo for recognition!') return 'OK'
def processing(app, chat_id, video, object_name, new_object_name, iter_count, threshold): chat_id = str(chat_id) continue_count = 500 root_dir = 'data/' + chat_id + '/' if video: sys.path.append('./object_detection') import object_detection_api helpers.check_or_create_dirs(root_dir, new_object_name) try: cap = cv2.VideoCapture(video) except Exception as e: print(e) sys.exit() x = 0 iteration = 0 while cap.isOpened(): x += 1 if (x % continue_count) != 0: continue ret, frame = cap.read() orig_height, orig_width, _ = frame.shape objects = object_detection_api.get_objects(frame, threshold) objects = json.loads(objects) app.logger.info(objects) if len(objects) > 1: for item in objects: if item['name'] != 'Object': continue if item['class_name'] != object_name: continue iteration += 1 file_name = str(int(time.time())) + '-data' x = int(orig_width * item['x']) y = int(orig_height * item['y']) width = int(orig_width * item['width']) height = int(orig_height * item['height']) cv2.imwrite( root_dir + 'images/' + new_object_name + '/' + file_name + '.jpg', frame) helpers.create_annotation(root_dir, new_object_name, file_name, x, y, width, height, orig_width, orig_height) if iteration == iter_count: break zip_file = 'data/' + str(int(time.time())) + '_' + chat_id + '.zip' zf = zipfile.ZipFile(zip_file, "w") for dirname, subdirs, files in os.walk(root_dir): if dirname == 'data': continue zf.write(dirname) for filename in files: zf.write(os.path.join(dirname, filename)) zf.close() deleteFiles = [] deleteDirs = [] for root, dirs, files in os.walk(root_dir): if root == 'data': continue for f in files: deleteFiles.append(os.path.join(root, f)) for d in dirs: deleteDirs.append(os.path.join(root, d)) for f in deleteFiles: os.remove(f) for d in deleteDirs: if d == 'data': continue os.rmdir(d) return True, zip_file else: return False, ''