def new_image(): form = ImageForm() if form.validate_on_submit(): # save original images rand_name = urandom(4).hex() + form.image_file.data.filename print("is htis hte name /?",rand_name) real_name = ntpath.basename(image_uploadset.save(form.image_file.data, folder='originals', name=rand_name)) original_path = './images/originals/'+real_name image_cv = cv2.imread(original_path) # Face detection ## need to tell the location of the classifier manually!! #face_cascade = cv2.CascadeClassifier('C:/Users/mihir/PycharmProjects/A1_ECE1779/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml') #face_cascade = cv2.CascadeClassifier('/Users/ragnoletto/Documents/School/UofT/ECE1779/assignments/A1_ECE1779/venv/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml') #face_cascade = cv2.CascadeClassifier('/Users/bibinsebastian/Dropbox/UofT/ECE1779/A2_ECE1779/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml') face_cascade = cv2.CascadeClassifier('/home/ubuntu/Desktop/ece1779/A2_ECE1779/venv/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml') gray = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) face_cv = image_cv.copy() #this is neeeded since it will throw error if there is no image in the picture for (x,y,w,h) in faces: face_cv = cv2.rectangle(image_cv, (x,y) , (x + w,y + h), (0,0,255),8) roi_gray = gray[y:y+h, x:x+w] roi_color = face_cv[y:y+h, x:x+w] picture_path = './images/faces/'+real_name cv2.imwrite(picture_path, face_cv) cv2.waitKey(0) try: image = Image(user_id=current_user.id, file_name=real_name, num_faces = len(faces)) db.session.add(image) db.session.commit() flash('File Uploaded!') s3.upload_file(original_path,webapp.config["S3_BUCKET"],real_name) s3.upload_file(picture_path,webapp.config["S3_BUCKET"],'f_'+real_name) os.remove(original_path) os.remove(picture_path) except Exception as error: db.session.rollback() abort(500, error) return render_template("images/new.html", title="Upload an Image", form=form)
def imagem(): form = ImageForm() if form.validate_on_submit(): file = form.image.data user_image = UserImage(user=current_user, image=file) db.session.add(user_image) db.session.commit() flash('Imagem base salva!') return redirect(url_for('imagem')) images = UserImage.query.filter_by(user=current_user, parent=None) return render_template('imagem.html', title='imagem', form=form, user=current_user, images=images)
def file_form(request): if request.method == 'GET': context = { 'form': ImageForm } return render(request, 'file_form.html', context) else: form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = form.save() image.save() return redirect('home') context = { 'form': form } return render(request, 'file_form.html', context)
def image_veiw(request): form = ImageForm() if request.method == 'POST': form = ImageForm(request.POST) if form.is_valid(): form.save() return HttpResponse('success') return render(request, 'test.html', {'form': form})
def image_veiw(request): form = ImageForm() if request.method=='POST': # form = ImageForm(request.POST) # if form.is_valid(): # form.save() name=request.POST.get('Iname') name=request.POST.get('Ilocation') name=request.POST.get('Iname') return HttpResponse('success')
def add_image(board_slug): print 'add_image: ', board_slug board = Board.query.filter_by(slug=board_slug).first() if not board: abort(404) form = ImageForm() if form.validate_on_submit(): image = Image(filename=form.filename.data) db.session.add(image) board.images.append(image) db.session.commit() return json_success( {'image': { 'filename': image.filename, 'id': image.id }}) return json_error_message('Failed to create image', error_data=form.errors)
def add_image(board_slug): print 'add_image: ', board_slug board = Board.query.filter_by(slug=board_slug).first() if not board: abort(404) form = ImageForm() if form.validate_on_submit(): image = Image(filename=form.filename.data) db.session.add(image) board.images.append(image) db.session.commit() return json_success({ 'image': { 'filename': image.filename, 'id': image.id } }) return json_error_message('Failed to create image', error_data=form.errors)
def index(): form = ImageForm() if form.validate_on_submit(): w = form.w.data h = form.h.data file = form.img.data if allowed_file(file.filename): file_extension = os.path.splitext(file.filename)[1] filename = str(uuid.uuid4()) + file_extension file.save(os.path.join(UPLOAD_FOLDER, filename)) flash('File successfully uploaded') new_record = ImageRequest(w=w, h=h, img_path=filename) db.session.add(new_record) db.session.commit() change_img_size.apply_async(args=[filename, w, h, new_record.id]) flash('Your task id is ' + str(new_record.id)) return render_template('index.html', form=form), 202 else: flash('Allowed file types are png, jpg') return redirect(request.url), 301 return render_template('index.html', form=form), 200
def upload_image(): pid,pnames = [t.pid for t in Patients.query.filter_by(therapist_id=current_user.id).all()], [str(t.first_name) + " " + str(t.last_name) for t in Patients.query.filter_by(therapist_id=current_user.id).all()] imtypes_id,imtype_names = [t.id for t in ImageTypes.query.all()], [t.name for t in ImageTypes.query.all()] form = ImageForm() form.patient_id.choices = list(zip(pid, pnames)) form.im_type.choices = list(zip(imtypes_id, imtype_names)) if form.validate_on_submit(): filename = photos.save(form.photo.data, name=f"{form.patient_id.data}_{form.datetime.data}_{current_user.id}.") file_url = photos.url(filename) img = Images(patient_id=form.patient_id.data, datetime=form.datetime.data, im_type=form.im_type.data, image=filename) db.session.add(img) db.session.commit() flash("New image successfully added") if form.analyze.data: #send POST request to ml module res = requests.post(ML_URL, json={'impath':filename}) if res.status_code == 200: result = json.loads(res.text) diagnosis = 1 if result["tumor_detected"]==False else 2 img_anal = ImageAnalysis(image_id=img.image_id, segment=result["segmentation_img"], tumor=result["classification"], diagnosis=diagnosis, recommendations=None, confidence=result["confidence"], dt=datetime.now(), verified=False) db.session.add(img_anal) db.session.commit() #flash(img_anal) flash("Successfully analyzed new image") else: flash("Error when analyzing") else: file_url = None return render_template("upload_image.html", form=form, file_url=file_url)
def patient_dashboard(): if "email" not in session: flash("You must log in first") return redirect(url_for("login")) form = ImageForm() if form.validate_on_submit(): f_name = save_picture(form.picture.data) covid_prediction = model_predict( os.path.join(app.root_path, 'static\\assets\\img\\xray', f_name), ) if covid_prediction is True: email = session["email"] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute( 'UPDATE DETAILS SET xraystatus = "Threatened", status = "Threatened", disease = "Covid-19" WHERE email = %s', (email, )) mysql.connection.commit() flash('You have high chances of Covid-19, please see a doctor.') else: flash('Congratulations! You have low chances of Covid-19.') return render_template('patient-dashboard.html', form=form, title="Patient Dashboard")
def index(): form = ImageForm() if form.validate_on_submit(): # Remove cached image files file_path = os.path.join('uploads', 'uploaded_image.jpg') if os.path.exists(file_path): os.remove(file_path) filename = photos.save(form.upload.data, name="uploaded_image.jpg") file_url = photos.url(filename) + f"?{time.time()}" caption = get_caption_and_attention_plot('uploads/' + filename) if os.path.exists(os.path.join("uploads", "attention_plot.jpg")): attention_path = photos.url( "attention_plot.jpg") + f"?{time.time()}" else: attention_path = None else: file_url = None caption = None attention_path = None return render_template('index.html', form=form, file_url=file_url, caption=caption, attention=attention_path)
def upload_view(request): if request.method == 'POST': form = ImageForm(request.POST or None, request.FILES or None) if form.is_valid(): if form.cleaned_data['link']: image = ImageModel.objects.create() link_path = urlparse(form.cleaned_data['link']) name = os.path.basename(link_path.path) temp_file = tempfile.NamedTemporaryFile() temp_file.write( requests.get(form.cleaned_data['link'], stream=True).content) image.file.save(name, temp_file) elif form.cleaned_data['file']: form.save() return redirect('index') elif request.method == 'GET': form = ImageForm() return render(request, 'upload.html', {'form': form})
def new_image(): form = ImageForm() if form.validate_on_submit(): # save original images rand_name = urandom(4).hex() + form.image_file.data.filename real_name = ntpath.basename( image_uploadset.save(form.image_file.data, name=rand_name)) original_path = '/tmp/' + real_name watermark_name = '/tmp/' + 'w_' + real_name #Adding watermark . need to store the watermark image in s3 and read from there. with Image(filename=original_path) as background: with Image(filename='cpics.png') as watermark: background.watermark(image=watermark, transparency=0.50, left=randint(1, 100), top=randint(1, 100)) background.save(filename=watermark_name) try: s3.upload_file(original_path, webapp.config["S3_BUCKET"], real_name) s3.upload_file(watermark_name, webapp.config["S3_BUCKET_WATER"], 'w_' + real_name) os.remove(original_path) os.remove(watermark_name) table_user = dynamodb.Table(webapp.config["DDB_USER_TBL_NAME"]) table_attrib = dynamodb.Table(webapp.config["DDB_ATTRIB_TBL_NAME"]) # rekognition on images rekognition = boto3.client('rekognition') response_label = rekognition.detect_labels(Image={ "S3Object": { "Bucket": webapp.config["S3_BUCKET"], "Name": real_name } }, MaxLabels=10, MinConfidence=70) response_faces = rekognition.recognize_celebrities( Image={ "S3Object": { "Bucket": webapp.config["S3_BUCKET"], "Name": real_name } }) #print("rekognition response", response) # labels = [{'Confidence': Decimal(str(round(label_prediction['Confidence'], 1))), # 'Name': label_prediction['Name']} for label_prediction in response['Labels']] labels = [{ 'Confidence': int(label_prediction['Confidence']), 'Name': label_prediction['Name'].lower() } for label_prediction in response_label['Labels']] if response_faces['CelebrityFaces'] != []: labels.extend([{ 'Confidence': int(face_prediction['MatchConfidence']), 'Name': face_prediction['Name'].lower() } for face_prediction in response_faces['CelebrityFaces']]) #print("labels:::::", labels) # update table response_user = table_user.get_item(Key={ 'username': current_user.id, }) #print("response 1 ",response1) response_attrib = table_attrib.scan() records = [] for i in response_attrib['Items']: records.append(i) while 'LastEvaluatedKey' in response_attrib: response_attrib = table.scan( IndexName=indexName, ExclusiveStartKey=response['LastEvaluatedKey']) for i in response_attrib['Items']: records.append(i) #print("response_attrib",response_attrib) attrib_list = {} for item in records: attrib_list[(item['attribute'])] = int(item['attrib_counter']) for label in labels: if label['Name'] in attrib_list.keys(): attrib_list[label['Name']] += int(1) table_attrib.update_item( Key={ 'attribute': label['Name'] #, # 'attrib_counter': attrib_list[label['Name']] }, UpdateExpression= "SET attrib_counter = :val, im_path = list_append(im_path, :val2)", ExpressionAttributeValues={ ':val': attrib_list[label['Name']], # ':val2': [real_name] }, ':val2': [{ 'username': current_user.id, 'email': response_user['Item']['email'], 'path': real_name, 'Confidence': label['Confidence'], }] }, ReturnValues="UPDATED_NEW") else: putItem_Attrib(label['Name'], int(1), [{ 'username': current_user.id, 'email': response_user['Item']['email'], 'path': real_name, 'Confidence': label['Confidence'] }]) # for label in labels: # if label['Name'] in attrib_list: # attrib_list[label['Name']] += int(1) # else: # attrib_list[label['Name']] = int(1) # print("attrib list",attrib_list) table_user.update_item( Key={ 'username': current_user.id, }, UpdateExpression="SET images = list_append(images, :val)", ExpressionAttributeValues={ ':val': [{ 'path': real_name, 'labels': labels, }], }, ReturnValues="UPDATED_NEW") # table.update_item( # Key={ # 'username': current_user.id, # }, # UpdateExpression="SET images = list_append(images, :val), attrib = :val2", # ExpressionAttributeValues={ # ':val': [{ # 'path': real_name, # 'labels': labels, # }], # ':val2': attrib_list, # }, # ReturnValues="UPDATED_NEW" # ) #print("labels",labels) flash('File Uploaded!') except Exception as error: # db.session.rollback() abort(500, error) return render_template("images/new.html", title="Upload an Image", form=form)