def login(): if request.method == 'POST': image = request.files['image'] image.save(os.path.join('./', image.filename)) return ResNet50_predict_breed(os.path.join('./', image.filename)) else: return "Use POST method to use /breed endpoint"
def predict(sess, image_file): """ Runs the graph stored in "sess" to predict boxes for "image_file". Prints and plots the preditions. Arguments: sess -- your tensorflow/Keras session containing the YOLO graph image_file -- name of an image stored in the "images" folder. Returns: out_scores -- tensor of shape (None, ), scores of the predicted boxes out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes out_classes -- tensor of shape (None, ), class index of the predicted boxes Note: "None" actually represents the number of predicted boxes, it varies between 0 and max_boxes. """ # Preprocess your image image, image_data = preprocess_image(image_file, model_image_size=(608, 608)) out_scores, out_boxes, out_classes = sess.run( [scores, boxes, classes], feed_dict={yolo_model.input: image_data}) # Print predictions info print('Found {} boxes for {}'.format(len(out_boxes), image_file)) # Generate colors for drawing bounding boxes. colors = generate_colors(class_names) # Draw bounding boxes on the image file draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors) # Save the predicted bounding box on the image image.save(os.path.join("static/outimage", image_file.filename), quality=90) return image_file
def convert_to_ela_image(path, quality): temp_filename = "temp_file_name.jpg" ela_filename = "temp_ela.png" # s3 se fetch image ko image = "" try: response = requests.get(path) image = Image.open(BytesIO(response.content)).convert("RGB") except: # if you want to locally import the image from path then comment above line # Uncomment the below line image = Image.open(path).convert("RGB") # saving local image.save(temp_filename, "JPEG", quality=quality) temp_image = Image.open(temp_filename) ela_image = ImageChops.difference(image, temp_image) extrema = ela_image.getextrema() max_diff = max([ex[1] for ex in extrema]) if max_diff == 0: max_diff = 1 scale = 255.0 / max_diff ela_image = ImageEnhance.Brightness(ela_image).enhance(scale) return ela_image
def weed(): if request.method == 'POST': temp= request.files['image'] img= Image.open(temp) #w,h=img.size #img.load() #array= np.asarray(img,dtype=np.uint8) #image_np= array.reshape(w,h,3) image_np = load_image_into_numpy_array(img) #image_np_expanded = np.expand_dims(image_np, axis=0) output_dict = run_inference_for_single_image(image_np, detection_graph) # Visualization of the results of a detection. vis_utils.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) w,h= 600,400 plt.imshow(image_np) print('hai') img= Image.fromarray(image_np,'RGB') img.save('img.jpg') image = Image.open('img.jpg') #image.show() image.save('static/img.jpg') #return '<html> <body> hai </body></html>' return flask.render_template("weed.html")
def get_images(flic, tag, page, per_page): urls = [] rgbs = [] if not os.path.exists(str(tag)): os.makedirs(str(tag)) for i in range(page): images = flic.photos.search(text=tag, per_page=per_page, extras='url_n', orientation='square', page=i) for j in range(len(images['photos']['photo'])): try: urls.append(images['photos']['photo'][j]['url_n']) except: pass for i in range(len(urls)): response = requests.get(urls[i]) image = Image.open(BytesIO(response.content)) rgbs.append(get_aveage_rgb(image)) uri = str(tag) + '/' + str(tag) + str(i) + '.jpg' image.save(uri) return urls, rgbs
def make_image_thumbnail(filename): base_filename, file_extension = os.path.splitext(filename) thumbnail_filename = f"{base_filename}_thumbnail{file_extension}" image = Image.open(filename) image.thumbnail(size=(128, 128)) image.save(thumbnail_filename, "JPEG") return thumbnail_filename
def getImage(url): user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' headers = {'User-Agent': user_agent, } request = urllib.request.Request(url, None, headers) response = urllib.request.urlopen(request) image = Image.open(response).convert('RGB') image.save( "/root/py-deploy/api/utils/images/n02799071_986.jpg") return True
def upload(): image = request.files['file'] path = os.path.join(app.config['UPLOAD_FOLDER'], image.filename) image.save(path) # Make prediction text = model_predict(path, IMAGEmodel) return jsonify({'text': text}), 200
def upload_image(): if request.method == "POST": if request.files: image = request.files["image"] filename = secure_filename(image.filename) image.save(os.path.join(app.config["IMAGE_UPLOADS"], filename)) print("image saved") return redirect(request.url) return render_template("upload_image.html")
def upload_file(): image = request.files['image'] filename = os.path.join(app.config['UPLOAD_FOLDER'], "image.jpeg") image.save(filename) #image = cv2.imread('filename',0) description = tell_dog_breed(filename) return jsonify(description=description) return render_template('index.html')
def predict(): image = request.files["image"] image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename)) test_datagen = ImageDataGenerator(rescale=1. / 255) test_generator = test_datagen.flow_from_directory("./pred", target_size=(224, 224), batch_size=5, class_mode='categorical', shuffle=False) pred = my_model.predict_generator(test_generator, steps=len(test_generator), verbose=1) os.remove(os.path.join(app.config["IMAGE_UPLOADS"], image.filename)) """ data = request.files['image'] img = cv2.imread(data) print(img) draw = img[init_Base64:] #Decoding draw_decoded = base64.b64decode(draw) image = np.asarray(bytearray(draw_decoded), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_GRAYSCALE) #Resizing and reshaping to keep the ratio. resized = cv2.resize(image, (28,28), interpolation = cv2.INTER_AREA) vect = np.asarray(resized, dtype="uint8") vect = vect.reshape(1, 1, 28, 28).astype('float32') """ """ npimg = np.fromfile(request.files['image'], np.uint8) # convert numpy array to image img = cv2.imdecode(npimg, cv2.IMREAD_GRAYSCALE) xnew = my_model.predict(img.reshape(1,224,224,1)) """ """#[0][0] #y_proba = my_model.predict(img) #y_classes = keras.np_utils.probas_to_classes(y_proba) y_prob = my_model.predict(img) y_classes = y_prob.argmax(axis=-1) y_label = my_model.predict_classes(img, verbose=1)[0][0] #l.append(y_prob) #l.append(labels[1 if y_prob > 0.5 else 0]) #predictedLabels[y_prob[0][0]] = labels[1 if y_prob > 0.5 else 0] predictedLabels[y_prob[0][0]] = labels[y_label] #print('prediction : ',xnew) #print('class : ',my_model.predict_classes(img, verbose=1)) #print('y_classesmal : ',y_classes) #print('Classifying..') #c=request.form#.get("Weight")""" if pred[0][0] >= pred[0][1]: s = "benign" else: s = "malignant" return render_template('result2.html', result=s) # show result in result.html
def draw(model_body, class_names, anchors, image_data, image_set='val', weights_name='trained_stage_3_best.h5', out_path="output_images", save_all=True): ''' Draw bounding boxes on image data # ''' print("draw") if image_set == 'train': image_data = np.array([np.expand_dims(image, axis=0) for image in image_data[:int(len(image_data)*.9)]]) elif image_set == 'val': image_data = np.array([np.expand_dims(image, axis=0) for image in image_data[int(len(image_data)*.9):]]) elif image_set == 'all': image_data = np.array([np.expand_dims(image, axis=0) for image in image_data]) else: ValueError("draw argument image_set must be 'train', 'val', or 'all'") # # model.load_weights(weights_name) print(image_data.shape) model_body.load_weights(weights_name) # Create output variables for prediction. yolo_outputs = yolo_head(model_body.output, anchors, len(class_names)) input_image_shape = K.placeholder(shape=(2, )) boxes, scores, classes = yolo_eval( yolo_outputs, input_image_shape, score_threshold=0.3, iou_threshold=0.1) # Run prediction on overfit image. sess = K.get_session() # TODO: Remove dependence on Tensorflow session. if not os.path.exists(out_path): os.makedirs(out_path) for i in range(len(image_data)): out_boxes, out_scores, out_classes = sess.run( [boxes, scores, classes], feed_dict={ model_body.input: image_data[i], input_image_shape: [image_data.shape[2], image_data.shape[3]], K.learning_phase(): 0 }) print('Found {} boxes for image.'.format(len(out_boxes))) print(out_classes) # Plot image with predicted boxes. image_with_boxes = draw_boxes(image_data[i][0], out_boxes, out_classes, class_names, out_scores) # Save the image: if save_all or (len(out_boxes) > 0): image = PIL.Image.fromarray(image_with_boxes) image.save(os.path.join(out_path,str(i)+'.png')) # To display (pauses the program): plt.imshow(image_with_boxes, interpolation='nearest') plt.show()
def generate_qr_code(request): email = request.session.get('patient_email', False) obj = SignUpPatientModel.objects.filter(email = email) obj = obj.values() obj = obj[0] name = obj['name'] dob = obj['birth_date'] blood_group = obj['blood_group'] aadhar = obj['aadhar_no'] image = Image.new('RGB', (900,600), (255, 255, 255)) draw = ImageDraw.Draw(image) font = ImageFont.truetype('/Library/Fonts/Arial.ttf',15) import random import os import datetime import qrcode (x, y) = (10, 40) color = 'rgb(255, 0, 0)' # black color font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 30) draw.text((x, y),"Name: "+ name, fill=color, font=font) (x, y) = (10, 90) color = 'rgb(0, 0, 0)' # black color draw.text((x, y), "Date of Birth: "+ str(dob), fill=color, font=font) (x, y) = (10, 140) bloodgroup=blood_group color = 'rgb(0, 0, 0)' # black color draw.text((x, y),"Blood Group: "+ bloodgroup, fill=color, font=font) (x, y) = (10, 190) adhaarno= aadhar color = 'rgb(0, 0, 0)' # black color draw.text((x, y), "Adhaar Number: "+str(adhaarno), fill=color, font=font) image.save('code.png') img = qrcode.make(str(name)+','+str(adhaarno)) # this info. is added in QR code, also add other things img.save('qr.jpeg') til = Image.open('code.png') im = Image.open('qr.jpeg') #25x25 til.paste(im,(500,0)) til.save('static/qr/code.png') url = static('/qr/code.png') return redirect(url)
def upload_file(): global graph with graph.as_default(): if request.method == 'POST': myfile = request.form['snapShot'].split(',') imgdata = base64.b64decode(myfile[1]) image = Image.open(io.BytesIO(imgdata)) # 保存 basename = datetime.now().strftime("%Y%m%d-%H%M%S") image.save(os.path.join(UPLOAD_FOLDER, basename + ".png")) filepath = os.path.join(UPLOAD_FOLDER, basename + ".png") image = image.convert('RGB') image = image.resize((image_size, image_size)) data = np.asarray(image) X = [] X.append(data) X = np.array(X).astype('float32') X /= 256 result = model.predict([X])[0] result_proba = model.predict_proba(X, verbose=1)[0] percentage = (result_proba * 100).astype(float) array_sort = sorted(list(zip(percentage, classes, classes_img)), reverse=True) percentage, array_class, array_img = zip(*array_sort) pred_answer1 = "ラベル:" + \ str(array_class[0]) + ",確率:"+str(percentage[0])+"%" pred_answer2 = "ラベル:" + \ str(array_class[1]) + ",確率:"+str(percentage[1])+"%" pred_answer3 = "ラベル:" + \ str(array_class[2]) + ",確率:"+str(percentage[2])+"%" img_src1 = array_img[0] img_src2 = array_img[1] img_src3 = array_img[2] basename = datetime.now().strftime("%Y%m%d-%H%M%S") filepath3 = UPLOAD_FOLDER + basename + ".png" return render_template("index.html", answer1=pred_answer1, img_data1=img_src1, answer2=pred_answer2, img_data2=img_src2, answer3=pred_answer3, img_data3=img_src3) return render_template("index.html", answer="")
def upload(): if request.method == "POST": if request.files: image = request.files["image"] image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename)) return redirect(request.url) return render_template("upload.html")
def predict(): image = request.files["image"] image_bytes = Image.open(io.BytesIO(image.read())) tensor = path_to_VGG19_feature(image_bytes) global graph with graph.as_default(): predicted_vector = model.predict(tensor) actress_name = actress_names[np.argmax(predicted_vector)] image.save( os.path.join(app.config['UPLOAD_FOLDER'], get_next_name(actress_name))) return jsonify("You look like {}".format(actress_name))
def cancer(): if request.method == "POST": if request.files: image = request.files["image"] image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename)) print("Image Saved") img="static/uploads/"+image.filename output=tellme(img) return render_template("cancer.html",imga=img,output=output) return render_template("cancer.html")
def image_upload(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): image = Image(img=request.FILES['img']) image.save() return render( request, 'diabetes_retinopathy_recognition_app/prediction.html', {'image': image}) else: form = UploadImageForm() return render(request, 'diabetes_retinopathy_recognition_app/prediction.html', {'form': form})
def byImage(): tmp = str(uuid.uuid4()) os.makedirs("images/" + tmp + "/") name = "images/" + tmp + "/image.jpg" image = request.files['image'] image.save(name) img_data = prepare_image(name) feat = get_features(img_data) #TODO:: Add code to remove file count = 8 (ind, dist) = get_similar(feat, count) (i, j, k) = get_data(ind, False) return render_template('imagesearch.html', data=zip(i, k, dist), query_imUrl=name)
def index(): if request.method == 'POST': try: image = request.files['file'] # Get the file. filename = timestr + secure_filename( image.filename ) # Get secured file name and add timestamp to make it unique. image.save(os.path.join('static', filename)) path = os.path.join('static', filename) result = predict( base64file=path) # Send the image to prediction algorithm. return render_template('index.html', res=result) except: return render_template('index.html', res=results) return render_template('index.html', res=results)
def main(): st.title("MEP Object Detection 👁") #Disable warnings st.set_option('deprecation.showfileUploaderEncoding', False) st.write("This application detects Mechanical, Electrical and Plumbing assets in images.") st.write("## How does it work?") st.write("Upload an image of a room and the deep learning learning model will interrogate it to find MEP assets. It currently supports sockets, switches and radiators") st.write("## Upload your own image") st.write("**Note:** The model has been trained on typical classrooms and household rooms and will therefore work best for those use cases.") uploaded_image = st.file_uploader("Choose a png or jpg image", type=["jpg", "png", "jpeg"]) if uploaded_image is not None: image = Image.open(uploaded_image) im = image.save('images/out.png') # Make sure image is RGB # TODO: If image is over certain size resize image to certain size if st.button("Make a prediction"): "Making a prediction and drawing MEP boxes on your image..." with st.spinner("Doing the math..."): st.image(detect(), caption="MEP assets detected.", use_column_width=True) st.image(image, caption="Uploaded Image.", use_column_width=True) st.write("## How is this made?") st.write("A [Faster R-CNN](https://arxiv.org/abs/1506.01497?source=post_page) model is used to perform the detections, \ this front end (what you're reading) is built with [Streamlit](https://www.streamlit.io/) \ and it's all hosted on [Heroku](https://www.heroku.com/).") st.write("See the [code on GitHub](https://github.com/Jam516/MEP-detection-app)")
def make_image(tensor): """ Convert an numpy representation image to Image protobuf. Copied from https://github.com/lanpa/tensorboard-pytorch/ """ from PIL import Image height, width, channel = tensor.shape image = Image.fromarray(tensor) import io output = io.BytesIO() image.save(output, format='PNG') image_string = output.getvalue() output.close() return tf.Summary.Image(height=height, width=width, colorspace=channel, encoded_image_string=image_string)
def upload(): if request.method == "POST": if request.files: output = {} image = request.files["image"] print(request.files) basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', secure_filename(image.filename)) print(image.filename) image.save(file_path) # Make prediction preds = model_predict(file_path, image.filename) return str(preds) return "Error"
def main(): if len(sys.argv) != 2: print('以下のように入力してください') print('python simple_vgg16_usage.py [image file path]') sys.exit(1) file_name = sys.argv[1] model = VGG16(weights='imagenet') model.summary() x = img_to_array(load_img(file_name, target_size=(224, 224))) array_to_img(x) # imagenetの最後の畳み込み層を指定 image = Grad_Cam(model, x, 'block5_pool') image = array_to_img(image) image.save('grad_cam.png')
def success(): d = {} new = "" string = {} if request.method == "POST": image = request.files["image"] if image.filename == "": print("No Filename") return redirect(request.url) if allowed_image(image.filename): print(image.filename) date_string = time.strftime("%Y-%m-%d-%H:%M") image.save( os.path.join(app.config["IMAGE_UPLOADS"] + "\\" + image.filename)) add = os.path.join(app.config["IMAGE_UPLOADS"] + "\\" + image.filename) model = load_model('mod.h5') img = load_img(add, target_size=(224, 224)) img = img_to_array(img) img = np.expand_dims(img, axis=0) pred = model.predict_classes(img) if (pred[0][0] == 0): new = 'Covid' else: new = 'Normal' response1 = json.dumps(new) return new else: print(request.url) return redirect(request.url)
def detect(): if request.method == "GET": return render_template("object.html") if request.method == "POST": image = request.files["x-ray"] image_name = image.filename path = os.path.join(UPLOAD_FOLDER, image_name) image.save(path) # path = request.form["path"]': # accuracies, classes = predict(path) accuracies, classes = predict(path) os.remove(path) return render_template("object.html", preds=accuracies, classes=json.dumps(classes), img=path)
def home(): if request.method == "POST": if request.files: image = request.files["image"] if image.filename == "": return redirect(request.url) if not allowed_image(image.filename): return redirect(request.url) else: filename = secure_filename(image.filename) image.save(os.path.join(app.config["IMAGE_UPLOADS"], filename)) prd = predict(filename) os.remove(os.path.join(app.config["IMAGE_UPLOADS"],filename)) return render_template('index.html',cnv=prd[0], dme=prd[1], drusen=prd[2], normal=prd[3], prediction=True) else: return render_template('index.html')
def PREDICT(): if request.method == 'POST': image = request.files['image'] print(image.filename) print(image) return redirect(request.url) print('savedimage') if image: passed = False try: filename = image.filename filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) print("saved") image.save(filepath) passed = True print(passed) except Exception: passed = False print(passed) resp = processImg('file.filename') print(resp) if resp == 0: return render_template('cardboard.html') if resp == 1: return render_template('glass.html.html') if resp == 2: return render_template('paper.html') if resp == 3: return render_template('metal.html') if resp == 4: return render_template('plastic.html') return None else: print('else')
def predictImage(groupId, sender, img): setPredictReady(groupId, sender, False) predictCount = getData("predictCount") print(predictCount) updateData(predictCount + 1, "predict") dist = "%s%s.jpg" % (predictDist, predictCount) img_content = requests.get(img.url).content image = IMG.open(BytesIO(img_content)) image.save(dist) img_path = dist model = VGG16(weights='imagenet', include_top=True) # Input:要辨識的影像 # img = image.load_img(img_path, target_size=(224, 224)) x = np.array(IMG.open(dist).resize((224, 224))) # x = image.img_to_array(img) #转化为浮点型 x = np.expand_dims(x, axis=0) #转化为张量size为(1, 224, 224, 3) x = preprocess_input(x) # 預測,取得features,維度為 (1,1000) features = model.predict(x) # 取得前五個最可能的類別及機率 pred = decode_predictions(features, top=5)[0] #整理预测结果,value values = [] bar_label = [] for element in pred: values.append(element[2]) bar_label.append(element[1]) print(img_path) for i in range(5): print(bar_label[i], values[i]) record("predict", dist, sender, groupId, True, "img") msg = [At(target=sender), Plain(text="\nPredict Result:")] for i in range(5): msg.append(Plain(text="\n%s:%2.2f%%" % (bar_label[i], values[i] * 100))) record("predict", dist, sender, groupId, True, "img") return msg
def index(): if request.method == 'GET': return render_template("index.html") elif request.method == 'POST' and 'uploaded_image' in request.files: #Clean out images folder try: os.remove(glob(os.path.join("static", "unknown", "*.png"))[0]) except IndexError as err: print("No files to clean up") noise = str(uuid.uuid4()) image_name = "%simage.png" % noise image_path = os.path.join("static", "unknown", image_name) image = request.files.get('uploaded_image', '') image.save(image_path) test_data = get_img(os.path.join("static")) results = model.predict_classes(test_data) return_string = "Hotdog" if results == 0 else "Not Hotdog" return render_template("results.html", return_string=return_string, image_name=image_name)