def sendToStorage(image): convert(image) storage_client = storage.Client() print "get bucket" bucket = storage_client.get_bucket('enter-project-id-here') print "set blob" blob = bucket.blob('fejs') print "upload blob" blob.upload_from_filename('face.jpg') print "after upload" sendNotification('fejs')
def image_post_request(): x = image.convert(request.json['image']) y = model.predict(x.reshape((1, 28, 28, 1))).reshape((10, )) n = int(np.argmax(y, axis=0)) y = [float(i) for i in y] return jsonify({'result': y, 'digit': n})
def process(ch, method, properties, body): data = json.loads(body) image = convert(data['path'], IMAGE_SIZE) list_predictions = [] if image: image = np.array(image) list_predictions = [] for network in image_networks: list_predictions.append(network.classify(image.copy())) payload = { 'id': data['id'], 'path': data['path'], 'predictions': determine_predictions(list_predictions), 'reject': False } if len(payload['predictions']) == 0: payload['reject'] = True message = json.dumps(payload) channel.basic_publish( exchange='', routing_key='return_queue', body=message, properties=pika.BasicProperties( delivery_mode=2, # make message persistent )) ch.basic_ack(delivery_tag=method.delivery_tag)
def _scan(frame, window, model, roi): lt, rb = roi.bbox(window) #cv2.rectangle(frame, lt, rb, color=(255,255,255), thickness=4) subimage = scale_roi(frame, window, lt, rb) cvt = convert(subimage) position, features = zip(*fast_sliding_window(cvt, window // (2 * SIZE) + 1)) prediction = model.predict(features) return ((*restore_position(xy, window, lt, rb), window) for xy in np.array(position)[np.where(prediction == 1)])
def image_convert(files=None, dest_typ=None): if not dest_typ: dest_typ = best_dest_type() ext_ = ext(dest_typ) image_fmt = dest_typ.split('/', 1)[1] LOG.debug('image_convert dest=%s files=%s', dest_typ, repr(files)[:100]) for stream, mimetype, name in request_files(files): if 'application/pdf' == mimetype: # n = len(pdf.get_pages(stream)) for i, part in enumerate(pdf.split_pdf(stream)): try: yield (image.convert(part, image_fmt, 'application/pdf'), dest_typ, name + ('-page_%02d' % (i + 1)) + ext_) except Exception, exc: LOG.error("error converting %s (%s) to pdf: %s", repr(part)[:100], image_fmt, exc) else: try: yield (image.convert(stream, image_fmt, mimetype), dest_typ, name + ext_) except Exception, exc: LOG.error("error converting %s (%s) to pdf: %s", repr(stream)[:100], image_fmt, exc)
def to_jpeg(self): new_basename_root, old_ext = \ os.path.splitext(os.path.basename(self.filename)) new_basename = new_basename_root + '.jpg' new_filename = tempfile.gettempdir() + os.path.sep + new_basename image = Image.open(self.filename) if image.mode != 'RGB': image = image.convert('RGB') image.save(new_filename, 'JPEG', quality=100) new_file = JPEGFile(new_filename) new_file.item = self.item new_file.index = self.index return new_file
async def convert_local(data: ConvertImage): """ Converts incoming base64 images of any compatible formats to the specified output format. If no format specified, JPEG is assumed. See here for compatible incoming and outgoing formats: https://tinyurl.com/yymmmpwk """ b64_image = data.get('base64_image') if get_b64_size(b64_image) > 20971520: raise HTTPException(status_code=413, detail="Content is too large.") image_format = data.get('image_format') content = BytesIO(base64.b64decode(b64_image)) content.seek(0) image_buffer = convert(content, image_format) content.close() return Response(image_buffer.getvalue(), status_code=200)
async def convert_remote(url: str = 'https://s.gravatar.com/avatar/434d67e1ebc4109956d035077ef5adb8', image_format: str = 'JPEG'): """ Converts image at specified URL to specified format. JPEG is assumed if no format specified. Allowed formats: https://tinyurl.com/yymmmpwk """ response = requests.get(url) if response.status_code != 200: raise HTTPException(status_code=response.status_code, detail=f'Server returned error {response.status_code}.') if len(response.content) > 20971520: raise HTTPException(status_code=413, detail="Content is too large.") content = BytesIO(response.content) content.seek(0) image_buffer = convert(content, image_format) content.close() return Response(image_buffer.getvalue(), status_code=200)
def average_hash(image, hash_size=9): """ Average Hash computation Implementation follows http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html Step by step explanation: https://www.safaribooksonline.com/blog/2013/11/26/image-hashing-with-python/ @image must be a PIL instance. """ if hash_size < 0: raise ValueError("Hash size must be positive") # reduce size and complexity, then covert to grayscale image = image.convert("L").resize((hash_size, hash_size), Image.ANTIALIAS) # find average pixel value; 'pixels' is an array of the pixel values, ranging from 0 (black) to 255 (white) pixels = numpy.asarray(image) avg = pixels.mean() # create string of bits diff = pixels > avg # make a hash return ImageHash(diff)
def test_bmp(self): i = 'images/samoyed.bmp' image = convert(i, self.IMAGE_SIZE) image.show() self.verify_correct(image)
def formatImage(image): if image.mode == 'RGB': return image return image.convert('RGB')
def image_post_request(): x = image.convert(request.json['image']) y, n = classifier.classify(x) return jsonify({'result': y, 'digit': n})
def image2pdf_gm(stream, inp_fmt=None): return image.convert(stream, 'pdf', inp_fmt=inp_fmt)
import engine import image import battle # Image of a bag bag = image.convert('images/bag.txt') # Selected item in inventory selected = 0 # Combination of food and armour and weapons (used for drawing) loot_together = [] # Draw the inventory menu to the screen def draw_inventory(): global loot_together global selected global bag battle.compute_max_health() # Draw the inventory menu engine.draw_text_box(0, 0, 20, 22, fill=True, text=' I N V E N T O R Y \n===================') engine.draw_buf(bag.data, (14, 22))
test = pytesseract.image_to_string(crop) uc_txt.append(test) for l in range(len(lista)): if lista[l] in test: path = os.path.join("./directoies/", lista[l]) if (os.path.isdir(path)): print("{} Already exists".format(lista[l])) else: path = os.path.join("./directoies/", lista[l]) os.mkdir(path, mode=755) print("path of {} is {}".format(lista[l], path)) print("{} found".format(lista[l])) image = Image.open('./images3/{}.jpg'.format(i)) img = image.convert('RGB') img.save("{}/{}.jpg".format(path, i)) ##########Appending the respective pages to the list ############# if (lista[l] == "Closing Cost Worksheet"): CCW.append(i) dic["Closing Cost Worksheet"] = CCW c += 1 break elif (lista[l] == "LOAN ESTIMATE"): LE.append(i) dic["LOAN ESTIMATE"] = LE c += 1 break elif (lista[l] == "Uniform Residential Loan Application"): URLA.append(i)
# Player's HP player_health = constants.START_MAX_HEALTH player_max_health = constants.START_MAX_HEALTH # Food and equipment player_food = Counter() player_equip = set() # Items the player is currently wearing current_head = ('nothing', 'hat', 0) current_body = ('nothing', 'body', 0) current_legs = ('nothing', 'legs', 0) current_weapon = ('nothing', 'weapon', 1) # Crab image (O B A M A I S G O N E !!!) crab = image.convert('images/crab.txt') # Draw healthbar def draw_bar(frac, size, pos): for i in range(size): engine.plot("▰▱"[floor(i / size - frac + 1)], (pos[0], pos[1] + i)) # Battle drawing and stuff def battle(): global cursor_pos # Draw the menu engine.draw_text_box( 0,
from keras import backend as K from pprint import pprint from nets import ImageNetNetwork from determiner import determine_predictions from image import convert from utils.profiler import timer_avg # K.set_session(K.tf.Session(config=K.tf.ConfigProto(intra_op_parallelism_threads=1, # inter_op_parallelism_threads=1))) os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' IMAGE_SIZE = 224 MODE = os.getenv('MODE', 'local2') preload_image = convert('samoyed.jpg', IMAGE_SIZE) preload_image = np.array(preload_image) if MODE == 'production': print('=== Production') NETWORKS = [('seresnet50', IMAGE_SIZE, preload_image), ('densenet169', IMAGE_SIZE, preload_image), ('resnet34', IMAGE_SIZE, preload_image)] HOST = 'rabbitmq-server' elif MODE == 'testing': print('=== Testing') NETWORKS = [('mobilenet', IMAGE_SIZE, preload_image)] HOST = 'rabbitmq-server' elif MODE == 'local1': print('=== Local1') NETWORKS = [('mobilenet', IMAGE_SIZE, preload_image)]
def uploaded(): global assign global fixed global cd global CAN cd.clear() CAN.clear() W2.clear() URLNF.clear() DOT.clear() folder = './static/fnma' i = 0 dele = [] while i < len(fixed): dele = str(fixed[i]) + ".jpg" i = i + 1 for filename in os.listdir(folder): print(filename) file_path = os.path.join(folder, filename) try: if (os.path.isfile(file_path) or os.path.islink(file_path)) and filename not in dele: os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) data = [] doc = [] fnma.clear() paatalo.clear() target = os.path.join('./uploads') ##print(target) if not os.path.isdir(target): os.mkdir(target) for file in request.files.getlist("file"): ##print(file) filename = file.filename destination = "/".join([target, filename]) ##print("Accept incoming file:", filename) ##print(destination) file.save(destination) #i made change here if ".pdf" in filename: import pytesseract from PIL import Image x = './uploads/{}'.format(filename) pages = convert_from_path(x) print("--- %s seconds converted ---" % (time.time() - start_time)) for i, im in enumerate(pages): im.save("./static/images/{}.jpg".format(i + 1)) print("--- %s seconds After Naming images ---" % (time.time() - start_time)) print("images done") pdf = PdfFileReader(request.files['file']) print(pdf.getNumPages()) counter = 0 i = 0 global pp global c global uc CCW.clear() LE.clear() GFE.clear() URLA.clear() F3021.clear() MF.clear() CD.clear() APP.clear() a.clear() unc.clear() dic.clear() uc_txt.clear() pp.clear() dic.clear() unc.clear() for i in range(pdf.getNumPages()): i = i + 1 print(i) result = '' image = cv2.imread('./static/images/{}.jpg'.format(i)) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) crop = gray[1950:2180, 10:1700].copy() test = pytesseract.image_to_string(crop) uc_txt.append(test) for l in range(len(lista)): if lista[l] in test: path = os.path.join("./directoies/", lista[l]) if (os.path.isdir(path)): print("{} Already exists".format(lista[l])) else: path = os.path.join("./directoies/", lista[l]) os.mkdir(path, mode=755) print("path of {} is {}".format(lista[l], path)) print("{} found".format(lista[l])) image = Image.open('./static/images/{}.jpg'.format(i)) img = image.convert('RGB') img.save("{}/{}.jpg".format(path, i)) ##########Appending the respective pages to the list ############# if (lista[l] == "Closing Cost Worksheet"): CCW.append(i) dic["Closing Cost Worksheet"] = CCW c += 1 break elif (lista[l] == "LOAN ESTIMATE"): LE.append(i) dic["LOAN ESTIMATE"] = LE c += 1 break elif (lista[l] == "Uniform Residential Loan Application"): URLA.append(i) dic["Uniform Residential Loan Application"] = URLA c += 1 break elif (lista[l] == "Form 3021"): F3021.append(i) dic["Form 3021"] = F3021 c += 1 break elif (lista[l] == "MULTISTATE FIXED"): MF.append(i) dic["MULTISTATE FIXED"] = MF c += 1 break elif (lista[l] == "CLOSING DISCLOSURE"): CD.append(i) dic["CLOSING DISCLOSURE"] = CD c += 1 break elif (lista[l] == "appraisal software by a la mode"): APP.append(i) dic["appraisal software by a la mode"] = APP c += 1 break else: path = os.path.join("./directoies/", lista[l]) if (os.path.isdir(path)): print("{} Already exists".format(lista[l])) else: path = os.path.join("./directoies/", lista[l]) os.mkdir(path, mode=755) print("path of {} is {}".format(lista[l], path)) print("{} found".format(lista[l])) image = Image.open('./static/images/{}.jpg'.format(i)) img = image.convert('RGB') img.save("{}/{}.jpg".format(path, i)) if (("Closing Cost Worksheet" and "LOAN ESTIMATE" and "Uniform Residential Loan Application" and "Form 3021" and "MULTISTATE FIXED" and "CLOSING DISCLOSURE" and "appraisal software by a la mode") not in uc_txt): uc += 1 unc.append(i) dic["unclassified"] = unc #######Assembling the images and converting to pdf ########### for nam, pag in dic.items(): pp = list(compress_ranges(pag)) counter = 0 for x in pp: counter = counter + 1 pre_path = os.path.join("./directoies/", nam) prefix = ("{}/".format(pre_path)) suffix = ".jpg" out_fname = "./static/pdf/{0} {1}.pdf".format(nam, counter) for z in range(x[0], x[1] + 1): a.append(z) process_images(prefix, suffix, out_fname, a) a.clear() data.append(str(x[0]) + ".jpg") doc.append("pdf/{0} {1}.pdf".format(nam, counter)) print("count of classified is {}".format(c)) print("count uclassfied is {}".format(uc)) print("data {}".format(data)) return render_template('index.html', data=data, doc=doc)
0, 79, 4, text=" ran away successfully!") constants.game_state['mode'] = 'main' # Bag state elif constants.game_state['mode'] == 'bag': inventory.draw_inventory() # Draw the screen to the terminal engine.draw() # Images! title = image.convert('images/title.txt') battlescreen = image.convert('images/battlescreen.txt') levelup = image.convert('images/levelup.txt') player_x = 0 player_y = 0 if __name__ == '__main__': try: run(b' ') while (1): run(getch.getch()) except KeyboardInterrupt: sys.exit()
def test_gif(self): i = 'images/reject.gif' image = convert(i, self.IMAGE_SIZE) self.assertIsNone(image)
def test_broken(self): i = 'images/broken.jpg' image = convert(i, self.IMAGE_SIZE) self.assertIsNone(image)