def post(self): data = Image.parser.parse_args() image = ImageModel(**data) try: image.save_to_db() except: return {'message': "An error occured creating the image."}, 500 return image.json(), 201
def post(self): data = parser.parse_args() image = ImageModel(data['type'], data['url'], data['product_id']) try: image.save() except Exception as e: return { 'message': 'An error occurred inserting into db: {}'.format(e) }, 500 return image.json(), 201
def get(self, _id): image = ImageModel.find_by_id(_id) if not image: return {'message': 'Image not found.'}, 404 return image.json()
def get(self, name): """ API GET """ logging.info('Resource: [Image] >>> Getting file %s', name) images = ImageModel.find_by_name(name) if images: return Image.download_files(images) return {"message": "image not found"}, 404
class ImageService(): m_image = ImageModel() def insert_image(self,image,callback=None): model = yield tornado.gen.Task(m_image.insert,image) callback(model) def exist_image(self,user_name,service_name,callback=None): result = yield tornado.gen.Task(m_image.find_one,{"user_name":user_name,"service_name":service_name}) if result==None or not isinstance(result,dict): callback(False) else: callback(True) def get_image(self,image_id,callback=None): result = yield tornado.gen.Task(m_user.find_one,{"_id":image_id}) if result==None or not isinstance(result,dict): callback(None) else: callback(result) def get_images(self,spec,fileds=None,sorts=None,page_index=0,page_size=20,callback=None): skip = page_index*page_size result_list = yield tornado.gen.Task(m_image.find(spec,fields,sorts,skip,page_size) if not result_list or len(result_list)==0: callback(None) else: callback(result_list)
def post(self, user_id, image_id): #request_data = Image.parser.parse_args() #target_dir = 'E:\\MartinMa\\Intel Cup\\server\\section6\\images' target_dir = os.path.join(APP_ROOT, 'images') print(target_dir) if not os.path.isdir(target_dir): os.mkdir(target_dir) print(request.files.getlist('file')) for uploaded_file in request.files.getlist('file'): print(uploaded_file) filename = user_id + '_' + image_id + '.jpg' new_image = ImageModel(str(datetime.datetime.now()), user_id) new_image.save_to_db() destination = '/'.join([target_dir, filename]) print(destination) uploaded_file.save(destination) return {'url': destination}
def delete(self, _id): image = ImageModel.find_by_id(_id) status = 404 message = 'Image not found' if image: image.delete() status = 200 message = 'Image deleted' return {'message': message}, status
def generator(self): for doc in self.db[self.db_name][self.collection].find(): # Send a data object representing our doc as a dict # This allows for some cool manipulations on-the-fly over the pipeline doc_output = { '_id': doc['_id'], '__data': doc['image'], 'best_candidate': False, 'faces': [] } doc_output['__model'] = ImageModel.from_bytes( doc_output['_id'], doc_output['__data']) yield doc_output
def get(cls): """ Here we get the JWT identity, and then if the user is logged in (we were able to get an identity) we return the entire label list. Otherwise we just return the label names. This could be done with e.g. see orders that have been placed, but not see details about the orders unless the user has logged in. """ # user_id = get_jwt_identity() data = parser.parse_args() label_id = data['label_id'] images = None if label_id: images = [ image.json() for image in ImageModel.find_by_label_id(label_id) ] else: images = [image.json() for image in ImageModel.find_all()] # if user_id: return {"images": images}, 200
def put(cls, image_id: int): image = ImageModel.find_by_id(image_id) req = request.get_json() identity = get_jwt_identity() if identity != image.user_id: return {"message": "you are not allowed to do that"}, 401 if "caption" not in req: return {"message": "caption not in json"}, 400 if image: image.caption = req["caption"] image.save_to_db() return {"msg": "caption has changed"}, 201 return {"message": "image-id dne"}
def get_faces_from_image(self, image: ImageModel): content = image.get_bytes() # IDEs freak out on this, because this is loaded dynamically google_image = types.Image(content=content) results = self.client.face_detection( image=google_image).face_annotations faces = [] for result in results: vertices = result.fd_bounding_poly.vertices # According to the google vision API, the vertices on index 1 is the top right corner face = ExtractedRect(vertices, *vertices) faces.append(face) return faces
def put(cls, label_id: str, image_id: str): image = ImageModel.find_by_id(image_id) print("image.name", image.name) meta_data = json.loads(image.meta_data) bounding_box = meta_data['bounding_box'] print("top_left_y", bounding_box['top_left']['y']) print("top_left_y", round(bounding_box['top_left']['y'])) print("top_left_y", int(round(bounding_box['top_left']['y']))) # image.save_to_db() return image.json(), 200
def delete(cls, name): image = ImageModel.find_by_name(name) if not image: return {"message": "Image not found"}, 404 try: image.delete_from_db() except IntegrityError as e: return {"database_exception": str(e)}, 400 except Exception as e: return { "message": "Internal error occurred during deletion." + str(e) }, 500 return {"message": "Image deleted from database."}, 200
def put(cls, name): image = ImageModel.find_by_name(name) if not image: image = ImageModel(name) else: image.name = name try: image.save_to_db() except IntegrityError as e: return {"database_exception": str(e)}, 400 except: return { "message": "Internal error occurred during the update." }, 500 return image.json(), 201
def put(self, _id): data = parser.parse_args() image = ImageModel.find_by_id(_id) status = 200 if image: image.type = data['type'] image.url = data['url'] else: image = ImageModel(data['type'], data['url'], data['product_id']) status = 201 image.save() return image.json(), status
def get(self, label_id: str, image_id: str): """ This endpoint returns the requested i mage if exists. It will use JWT to retrieve user information and look for the image inside the label's folder. """ image = ImageModel.find_by_id(image_id) filename = image.name # folder = label_name # check if filename is URL secure if not image_helper.is_filename_safe(filename): return {"message": IMAGE_ILLEGAL_FILENAME.format(filename)}, 400 try: # try to send the requested file to the user with status code 200 # abs_path = image_helper.get_path(filename, folder=folder) # abs_path_list = abs_path.split("\\") # abs_path_list.pop() # path = "\\".join(abs_path_list) path = "..\static\images" return send_from_directory(path, filename) except FileNotFoundError: return {"message": IMAGE_NOT_FOUND.format(filename)}, 404
def delete(self, label_id: str, image_id: str): """ This endpoint is used to delete the requested image under the user's folder. It uses the JWT to retrieve user information. """ image = ImageModel.find_by_id(image_id) filename = image.name # check if filename is URL secure if not image_helper.is_filename_safe(filename): return {"message": IMAGE_ILLEGAL_FILENAME.format(filename)}, 400 try: image_path = os.path.abspath(f'static/images/{filename}') image.delete_from_db() os.remove(image_path) return {"message": IMAGE_DELETED.format(filename)}, 200 except FileNotFoundError: return {"message": IMAGE_NOT_FOUND.format(filename)}, 404 except Exception: traceback.print_exc() return {"message": IMAGE_DELETE_FAILED}, 500
def get(self, id: int): dataset = DatasetModel.find_by_id(id) labels = dataset.labels labels = [label for label in labels.all()] with open('annotations.csv', 'w', newline='') as csvfile, \ open('all_train_files_new.txt', 'w') as txtObj, \ open('../sku110k/object_detector_retinanet/keras_retinanet/bin/class_mappings.csv', 'a', newline='') as classMap: for label in labels: classMapWriter = csv.writer(classMap) classMapWriter.writerow([label.id, label.id]) images = ImageModel.find_by_label_id(label.id) for image in images: # shutil.copy(f'static/images/{image.name}', '../sku110k/images') meta_data = json.loads(image.meta_data) dimensions = json.loads(image.dimensions) bounding_box = meta_data['bounding_box'] annotationswriter = csv.writer(csvfile) annotationswriter.writerow([ image.name, round(bounding_box['top_left']['x']), round(bounding_box['top_left']['y']), round(bounding_box['bottom_right']['x']), round(bounding_box['bottom_right']['y']), label.id, dimensions['width'], dimensions['height'] ]) txtObj.write(f'static/images/{image.name}') txtObj.write('\n') annotations.train_val_test_split() os.environ['PYTHONPATH'] = "../sku110k" subprocess.call( f'nohup env PYTHONPATH="../sku110k"; . ../sku110k/env/bin/activate; python -u ../sku110k/object_detector_retinanet/keras_retinanet/bin/train.py --weights ../sku110k/iou_resnet50_csv_06.h5 csv', shell=True) # crop_bounding_boxes() return
def post(cls, name): image = ImageModel.find_by_name(name) if image: return { "message": "An image with name '{}' already exists.".format(name) }, 400 image = ImageModel(name) try: image.save_to_db() except IntegrityError as e: return {"database_exception": str(e)}, 400 except: return { "message": "Internal error occurred during insertion." }, 500 return image.json(), 201
def get(self, place_id): image = ImageModel.find_by_place(place_id) if image: return image.json() return {'message': 'image not found'}, 404
def delete(self, _id): image = ImageModel.find_by_id(_id) if image: image.delete_from_db() return {'message': 'Image has been deleted.'}
def post(self): """ This endpoint is used to upload an image file. It uses the JWT to retrieve user information and save the image in the user's folder. If a file with the same name exists in the user's folder, name conflicts will be automatically resolved by appending a underscore and a smallest unused integer. (eg. filename.png to filename_1.png). """ data = image_schema.load(request.files) label_id = request.form.get("label_id") dim = request.form.get("dimensions") # dimensions = json.loads(dim) angle = request.form.get("angle") metadata = request.form.get("meta_data") # meta_data = json.loads(metadata) # bounding_box = meta_data['bounding_box'] # user_id = get_jwt_identity() label = LabelModel.find_by_id(label_id) try: # create image in db image = ImageModel(angle, dim, metadata, label.id) # save(self, storage, folder=None, name=None) try: image.save_to_db() # static/images/f'{label.id}_{image.id}_{angle}} # image_path = image_helper.save_image( # data["image"], name=image.name) # here we only return the basename of the image and hide the # internal folder structure from our user # basename = image_helper.get_basename(image_path) # with open('annotations.csv', 'a', newline='') as csvfile: # annotationswriter = csv.writer(csvfile) # annotationswriter.writerow( # [ # basename, # round(bounding_box['top_left']['x']), # round(bounding_box['top_left']['y']), # round( # bounding_box['bottom_right']['x'] # ), # round( # bounding_box['bottom_right']['y'] # ), # label.name, # dimensions['width'], # dimensions['height'] # ] # ) # with open('all_train_files.txt', 'a') as txtObj: # txtObj.write(f'static/images/{image_path}') # txtObj.write('\n') except UploadNotAllowed: # forbidden file type extension = image_helper.get_extension(data["image"]) return { "message": IMAGE_ILLEGAL_EXTENSION.format(extension) }, 400 except Exception: print("Exception", Exception) print("Unexpected error:", sys.exc_info()[0]) raise return {"message": ERROR_INSERTING}, 500 return {"message": IMAGE_UPLOADED.format(image.name)}, 201
def post(cls): caption = request.form.to_dict()["caption"] image = request.files["image"] if image: user_id = get_jwt_identity() uploaded_image = upload(image, folder="{}".format(user_id)) image_sizes = ImageModel.find_dimensions(image) width = image_sizes[0] height = image_sizes[1] if width / height > 1.6: url_height = round(700 * image_sizes[1] / image_sizes[0]) url = cloudinary_url( uploaded_image["public_id"], transformation=[ {"width": 700, "height": url_height}, {"crop": "crop", "width": 450, "x": 125, "height": url_height}, { "format": "jpg", "width": 450, "height": url_height, "quality": "auto:good", }, ], )[0] upload_height = round(370 * image_sizes[1] / image_sizes[0]) upload_url = cloudinary_url( uploaded_image["public_id"], transformation=[ {"width": 370, "height": upload_height}, { "crop": "crop", "width": 185, "x": 92, "height": upload_height, }, { "format": "jpg", "width": 185, "height": 185, "quality": "auto:good", }, ], )[0] else: height = round(450 * image_sizes[1] / image_sizes[0]) url = cloudinary_url( uploaded_image["public_id"], format="jpg", width=450, quality="auto:good", )[0] upload_height = round(185 * image_sizes[1] / image_sizes[0]) upload_url = cloudinary_url( uploaded_image["public_id"], transformation=[ {"width": 185, "height": upload_height}, { "crop": "crop", "width": 185, "height": 185, "format": "jpg", "quality": "auto:good", }, ], )[0] full_size_url = cloudinary_url(uploaded_image["public_id"], format="jpg")[0] image_obj = ImageModel( caption=caption, url=url, full_size_url=full_size_url, width=width, height=height, user_id=user_id, upload_url=upload_url, ) try: image_obj.save_to_db() except: return {"message": "error uploading file"}, 500 return image_obj.json(), 201 return {"message": "Please select an image"}, 401
def delete(cls, _id: int): image = ImageModel.find_by_id(_id) if image: image.delete_from_db() return {"message": "image deleted"}, 200 return {"message": "image not found"}, 404
def call(self, parent_id): parent_image = ImageModel.query.get(parent_id) parent_image_file = Image.open(parent_image.url) derivative_images = ImageModel.query.filter(ImageModel.parent_id == parent_id, ImageModel.finished == False)\ .order_by(ImageModel.created_at) images_array = list(derivative_images) print(images_array) images_array = list(map(lambda i: Image.open(i.url), images_array)) print(images_array) images_array.insert(0, parent_image_file) if len(images_array) < 4: blank_image = Image.new('RGB', parent_image_file.size, (255, 255, 255)) while len(images_array) != 4: images_array.append(blank_image) gutter_boundary = 100 total_width = 2 * parent_image_file.width + 3 * gutter_boundary total_height = max(images_array[0].size[1], images_array[1].size[1]) + \ max(images_array[2].size[1], images_array[3].size[1]) + \ 3 * gutter_boundary canvas = Image.new('RGB', (total_width, total_height), (255, 255, 255)) x = y = gutter_boundary if images_array[1].size[1] > images_array[0].size[1]: y = images_array[1].size[1] - images_array[0].size[ 1] + gutter_boundary canvas.paste(images_array[0], (x, y)) x += parent_image_file.width + gutter_boundary if images_array[0].size[1] > images_array[1].size[1]: y = images_array[0].size[1] - images_array[1].size[ 1] + gutter_boundary canvas.paste(images_array[1], (x, y)) x = gutter_boundary y = 2 * gutter_boundary + parent_image_file.height curr_y = y if images_array[2].size[1] < images_array[3].size[1]: y = images_array[3].size[1] - images_array[2].size[1] + curr_y canvas.paste(images_array[2], (x, y)) x += parent_image_file.width + gutter_boundary if images_array[3].size[1] < images_array[2].size[1]: y = images_array[2].size[1] - images_array[3].size[1] + curr_y canvas.paste(images_array[3], (x, y)) canvas.thumbnail((1920, 1080), Image.LANCZOS) logo = self.logo(canvas.size[0]) canvas = ImageManipulator.concat_vertical(canvas, logo) new_id = str(uuid.uuid4()) canvas_image = ImageModel(id=new_id, url=f"uploads/{new_id}.png", parent_id=parent_id, finished=True) canvas.save(f"uploads/{new_id}.png") canvas_image.save() return canvas_image
def get(cls): return { "images": [image.json() for image in ImageModel.find_all()] }, 200
def get(cls, name): image = ImageModel.find_by_name(name) if not image: return {"message": "Image not found."}, 404 return image.json(), 200
sim, sim_errors = user_schema.load({ 'username': '******', 'email': 'sim@google', 'password': '******', 'password_confirmation': 'pass' }) if sim_errors: raise Exception(sim_errors) easy = Difficulty(level='easy', pixelSize=10) medium = Difficulty(level='medium', pixelSize=20) hard = Difficulty(level='hard', pixelSize=30) # Projects: hard teddy = ImageModel(title='teddy', url='https://pixy.org/src/81/thumbs350/811052.jpg', difficulty=hard, user=mia) blue = ImageModel(title='blue', url='https://jpeg.org/images/jpeg2000-home.jpg', difficulty=hard, user=mia) red = ImageModel(title='red', url='https://jpeg.org/images/jpegsystems-home.jpg', difficulty=hard, user=mia) flower = ImageModel(title='flower', url='https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/JPEG_example_flower.jpg/260px-JPEG_example_flower.jpg', difficulty=hard, user=mia) meme = ImageModel(title='meme', url='http://i.imgur.com/nBYOnvl.jpg', difficulty=hard, user=mia) # Projects: medium forest = ImageModel(title='forest', url='https://jpeg.org/images/jpegxs-home.jpg', difficulty=medium, user=mia) emojis = ImageModel(title='emojis', url='https://onlinejpgtools.com/images/examples-onlinejpgtools/smile.jpg', difficulty=medium, user=mia) panda = ImageModel(title='panda', url='https://tinyjpg.com/images/social/website.jpg', difficulty=medium, user=mia) # Projects: easy landscape = ImageModel(title='landscape', url='https://static1.squarespace.com/static/52e57753e4b0f20972c633ab/532b8a93e4b0ccd5fa5463af/5804d81cf5e2319f13781dc2/1476712482113/Brough_-Clearing%2CHelene%27s+view-.jpeg', difficulty=easy, user=mia) lion = ImageModel(title='lion', url='http://www.agm-s.rs/upload/medialib/lion.jpeg', difficulty=easy, user=mia) bouquet = ImageModel(title='bouquet', url='https://static.wixstatic.com/media/ed05e1_5e9b4d30cb79466f93092d9354e7fcc4~mv2.jpeg/v1/fill/w_265,h_255,al_c,q_90/file.jpg', difficulty=easy, user=mia)