5 Star 1 Fork 2

tacom / Segmentation_webback_old

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
app.py 20.36 KB
一键复制 编辑 原始数据 按行查看 历史
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
# from flask import *
# from flask_cors import CORS
# import os
# import cv2
# from model.tools import test,pre_process,tw
# from flask import Flask, render_template, request, jsonify, redirect, url_for, make_response, send_from_directory,send_file
# from werkzeug.utils import secure_filename
# from datetime import timedelta
# import os
# import cv2
# import time
# import shutil
# import pandas as pd
# ###############
# from PIL import Image, ImageDraw, ImageFont
# import qrcode
# import pygame
# import glob
# import fitz
# ##############
# # import DR.matlabarray
# import torch
# from PIL import Image
# import Data_PDF
#
# from vessel_segmentation.imed_models import CS_Net
# import numpy as np
# from DR.fine_tune import BiResNet
# from torchvision import transforms
#
# from enhance.options.test_options import TestOptions
# from enhance.data import create_dataset
# from enhance.models import create_model
#
# import matplotlib
# import matplotlib.pyplot as plt
#
# #import matlab
# import matlab.engine
# import json
#
# from himed_dao import HimedDao,UserInfo,DataInfo,DaoUtils
# from CHenTao.API import interface as SbspAPI
# from DR_project.API import interface as TangwangAPI
#
# # from himed_dao.HimedDao import HimedDao
# # from himed_dao.UserInfo import UserInfo
# # from himed_dao.DataInfo import DataInfo
# # from himed_dao.DaoUtils import HashUtils
#
#
# from enhance.API import interface as EnhanceAPI
# import os
# os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
# matplotlib.use("Qt5Agg") # 声明使用QT5
# # plt.rcParams['font.sans-serif']=['Simhei']#win
# # plt.rcParams['font.sans-serif'] = ['./fonts/simsun.ttc']#ubuuntu
# plt.rcParams['font.sans-serif'] = ['Simhei']
# Arteriovenous_model_path = "model-new.pth" # 动静脉分割的模型
# #Arter_net = torch.load(Arteriovenous_model_path).cuda() # 动静脉分割网络的加载
# Arter_net = torch.load(Arteriovenous_model_path, map_location='cpu').module # 动静脉分割网络的加载
# Arter_net.eval()
# ALLOWED_EXTENSIONS = {'png', 'jpg', 'JPG', 'PNG', 'bmp', 'jpeg','tif','TIF','tiff','TIFF'}# 设置允许的图片格式
# BASE_PATH = os.path.dirname(os.path.abspath(__file__))# 本工程路径
# basepath = os.path.dirname(__file__)
# app = Flask(__name__)
# app.send_file_max_age_default = timedelta(seconds=1)# 设置静态文件缓存过期时间
#
# #分离文件的后缀名来判断是否是允许上传的图像文件格式
# def allowed_file(filename):
# return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
# #糖尿病性视网膜病变的概率诊断
# def dr_grading(upload_path, basepath):
# image = Image.open(upload_path)
# resize_transform = transforms.Compose([
# transforms.Resize((512, 512)),
# transforms.ToTensor(),
# transforms.Normalize(mean=[0.321, 0.224, 0.161], std=[0.262, 0.183, 0.132]),
# ])
# image = resize_transform(image).view([1, 3, 512, 512])
# image = image
#
# net = BiResNet(num_class=5, model_name='resnet34')
# a = os.path.join(basepath, 'DR_grading.pkl')
# abc = torch.load(a, map_location='cpu') # , map_location='cpu'
# net.load_state_dict(abc)
# with torch.no_grad():
# net.eval()
# x1, x2, predictions = net(image)
# probs = torch.softmax(predictions, dim=1)
# probs = probs.data.cpu().numpy()
# probs = probs[0]
# # ff = open('static/download/data.txt', "w")
# # for i in range(5):
# # item = str(round(probs[i], 4))
# # ff.write(str(item))
# # ff.write('\n')
#
# labels = ['正常', '1级糖尿病性视网膜病变概率', '2级糖尿病性视网膜病变概率', '3级糖尿病性视网膜病变概率', '4级糖尿病性视网膜病变概率']
# colors = ['green', 'yellow', 'pink', 'red', 'blue']
# explode = (0.1, 0.1, 0., 0.1, 0.1)
# fig = plt.figure()
# fig.set_facecolor('black')
# plt.axis('equal')
# plt.pie(x=probs, colors=colors, labels=labels, explode=explode, autopct='%1.1f',
# textprops={'color': 'orange'})
# plt.legend(loc="upper right", fontsize=8, bbox_to_anchor=(1.1, 1.05), borderaxespad=0.3)
# plt.savefig('static/download/pie.png')
#
# return 0
# #图片的叠加处理
# def applyImage(imgname, segment,branch):
# """:param
# img: the original RGB image --- numpy array with shape: [w,h,3]
# seg: the segmentation map --- numpy array with shape: [w,h] (1-channel image)
# """
# img = cv2.imread(imgname, flags=1)
# image = Image.fromarray(img).convert("RGB")
# image = image.resize((512, 512))
# image = np.array(image, dtype='uint8')
# seg = Image.fromarray(segment).convert("RGB")
# seg = np.array(seg, dtype='uint8')
# bra = np.array(branch).astype(int)
# bra = np.array(bra,dtype='uint8')
# point = np.where(bra == 1)
#
# # bra = Image.fromarray(bra).convert("RGB")
# # bra = np.array(bra, dtype='uint8')
# image[:, :, 0][seg[:, :, 0] == 255] = 25
# image[:, :, 1][seg[:, :, 1] == 255] = 255
# image[:, :, 2][seg[:, :, 2] == 255] = 13
# for i in range(len(point[0])):
# cv2.circle(seg, (point[1][i],point[0][i]), 3, (67, 6, 255), -1)
#
# return image,seg
# #血管分割
# def vessel_seg(image_name):
# img = Image.open(image_name)
# resize_transform = transforms.Compose([
# transforms.Resize([512, 512]),
# transforms.ToTensor()])
# img = resize_transform(img).view([1, 3, 512, 512])
# model = CS_Net(3, 1)
# b = os.path.join(basepath, 'state-179.pkl')
# bc = torch.load(b, map_location='cpu') # , map_location='cpu'
# model.load_state_dict(bc)
#
# with torch.no_grad():
# model.eval()
# img = img
# output1 = model(img)
# output1 = output1.squeeze().detach().cpu().numpy()
# output1 = np.array(output1 * 255, dtype='uint8')
# threshed_pred, output = cv2.threshold(output1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# image = output
# image = image / 255
#
# cv2.imwrite('aaa.jpg', image)
# image_name = 'aaa.jpg'
#
# engine = matlab.engine.start_matlab()
# feature_out = engine.vessel_feature(image_name)
# out = engine.vessel_branch(image_name)
#
# ff = open('static/download/data.txt', "w")
#
# item = '弯曲度特征为:'+str(round(feature_out[0][0], 3))
# ff.write(str(item))
# ff.write('\n')
# item = 'VAD特征为:' + str(round(feature_out[0][1], 3))
# ff.write(str(item))
# ff.write('\n')
# item = 'VLD特征为:' + str(round(feature_out[0][2], 3))
# ff.write(str(item))
# ff.write('\n')
# item = 'FD特征为:' + str(round(feature_out[0][3], 3))
# ff.write(str(item))
# ff.write('\n')
#
# return output, feature_out, out
# #绘制血管中心线
# def vessel_centerline(img_path):
# engine = matlab.engine.start_matlab()
# out = engine.vessel_centerline(img_path)
# out = np.array(out)
# out = out *255
#
# centerline_path ="./tmp/vessel_centerline.png"
#
# cv2.imwrite(centerline_path, out)
#
# img = cv2.imread('./tmp/vessel_centerline.png', flags=1)
# img = cv2.resize(img,(512,512))
# image = Image.fromarray(img).convert("RGB")
# image = np.array(image, dtype='uint8')
# seg = cv2.imread(centerline_path, flags=1)
# seg = Image.fromarray(seg).convert("RGB")
# seg = np.array(seg, dtype='uint8')
# image[:, :, 0][seg[:, :, 0] == 255] = 25
# image[:, :, 1][seg[:, :, 1] == 255] = 255
# image[:, :, 2][seg[:, :, 2] == 255] = 13
# cv2.imwrite(centerline_path, image)
# #绘制动静脉
# def vessel_Arter(img_path):
# img_dir = img_path
# img = cv2.imread(img_dir)
# img = img[:, :, ::-1]
# img = cv2.resize(img, (512, 512))
# clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
# r, g, b = cv2.split(img)
# r = clahe.apply(r)
# g = clahe.apply(g)
# b = clahe.apply(b)
# img = cv2.merge([r, g, b])
# img = np.array(img).transpose(2, 0, 1) / 255.0
#
# img = [img]
#
# img = torch.Tensor(img)
# img = img
#
# pred = Arter_net(img)
# pred[:, 1, :, :] = 0
# pred = pred.cpu().detach().numpy()
#
# # 从list里取出来
# pred = pred[0].transpose(1, 2, 0)*255
# # 544,544,3 rgb
# cv2.imwrite('./tmp/vessel_Ater.png', pred)
# #眼底图的图像增强
# def vessel_Enhance(img_path):
# opt = TestOptions().parse() # get test options
# # hard-code some parameters for test
# opt.num_threads = 0 # test code only supports num_threads = 0
# opt.batch_size = 1 # test code only supports batch_size = 1
# opt.serial_batches = True # disable data shuffling; comment this line if results on randomly chosen images are needed.
# opt.no_flip = True # no flip; comment this line if results on flipped images are needed.
# opt.display_id = -1 # no visdom display; the test code saves the results to a HTML file.
# dataset = create_dataset(opt) # create a dataset given opt.dataset_mode and other options
# model = create_model(opt) # create a model given opt.model and other options
# model.setup(opt)
# visuals = model.get_current_visuals() # get image results
# img_path = model.get_image_paths()
# if opt.eval:
# model.eval()
# #生成PDF的背景图和文本框的格式配置
# # backMode = {
# # # 背景图属性,我的背景图上需要添加一个二维码和多个文本框
# # "back_url": "./static/CSS/a.png",
# # "size": (3024, 3876),
# # "QR": {
# # # 二维码属性
# # "frame": (500, 500), # 大小
# # "position": (2440, 80), # 位置
# # },
# # "text": [{
# # # 文本框属性
# # "size": 70, # 字号
# # "ttf": "FZXBSJW.TTF", # 字体
# # "color": "", # 颜色
# # "position": (80, 120),
# # "frame": (2400, 20),
# # }, {
# # "size": 70,
# # "ttf": "FZXBSJW.TTF",
# # "color": "",
# # "position": (40, 240),
# # "frame": (2400, 20),
# # }, {
# # "size": 70,
# # "ttf": "FZXBSJW.TTF",
# # "color": "",
# # "position": (40, 360),
# # "frame": (2400, 20),
# # }, {
# # "size": 70,
# # "ttf": "FZXBSJW.TTF",
# # "color": "",
# # "position": (40, 480),
# # "frame": (2400, 20),
# # }, {
# # "size": 70,
# # "ttf": "FZXBSJW.TTF",
# # "color": "",
# # "position": (40, 600),
# # "frame": (2400, 20),
# # }, ],
# # }
# # #生成二维码
# # def make_QR(content, sizeW=0, sizeH=0): # 创建二维码
# # qr = qrcode.QRCode(version=3, box_size=3, border=1, error_correction=qrcode.constants.ERROR_CORRECT_H)
# # qr.add_data(content)
# # qr.make(fit=True)
# # img = qr.make_image()
# # if sizeW == 0 and sizeH == 0:
# # return img
# # w, h = img.size
# # if sizeW < w or sizeH < h:
# # return None
# # img = img.resize((sizeW, sizeH), Image.ANTIALIAS)
# # return img
# # #合并图片 combine picture
# # def com_pic(topimg, backimg, position): # 合并图片
# # nodeA = position
# # w, h = topimg.size
# # nodeB = (position[0] + w, position[1] + h)
# # backimg.paste(topimg, (nodeA[0], nodeA[1], nodeB[0], nodeB[1]))
# # return backimg
# # #给单个文本框填充数据
# # def write_line(backimg, text, tmode): # 给单个文本框填充数据
# # # myfont = ImageFont.truetype(tmode["ttf"], size=tmode["size"])
# # myfont=ImageFont.truetype(os.path.join("fonts", "simsun.ttc"), size=tmode["size"])
# # draw = ImageDraw.Draw(backimg)
# # tend = len(text)
# # while True:
# # text_size = draw.textsize(text[:tend], font=myfont) # 文本图层的尺寸
# # # print(text_size)
# # if text_size[0] <= tmode["frame"][0]:
# # break
# # else:
# # tend -= 1 # 文本太长,调整文本长度
# # draw.text((tmode["position"][0], tmode["position"][1]), text[:tend], font=myfont)
# #
# # return backimg, tend
# # #写文本
# # def write_text(img, text, tmodeList): # 写文本
# # tlist = text.split("\n")
# # mnum = 0
# # draw = ImageDraw.Draw(img)
# # for t in tlist:
# # tbegin = 0
# # tend = len(t)
# # while True:
# # img, tend = write_line(img, t[tbegin:tend], tmodeList[mnum])
# # mnum += 1
# # if tbegin + tend == len(t) or mnum == len(tmodeList):
# # break
# # else:
# # tbegin = tbegin + tend
# # tend = len(t)
# # if mnum == len(tmodeList):
# # break
# # return img
# # #绘制包含二维码和文本的图片
# # def make_pic(mode, text, url):
# # img = Image.open(mode["back_url"])#读取背景图片
# # img = Image.open(r'./static/CSS/a.png') # 读取背景图片
# # QR_res = make_QR(url, mode["QR"]["frame"][0], mode["QR"]["frame"][1]) # 创建二维码
# # img = com_pic(QR_res, img, mode["QR"]["position"]) # 合成1
# # img = write_text(img, text, mode["text"]) # 写文本
# # img.show()
# # img.save(r'./static/download/output.png', quality=100)
# # #将文本文件TXT转为字符串
# # def txt2String(txt_path):
# # String = ""
# # with open(txt_path, 'r')as f:
# # content = f.read().splitlines()
# # my_data =content
# # f.close()
# # for i in range(len(my_data)):
# # temp = my_data[i]
# # temp += ' \n '
# # my_data[i] = temp
# # String += my_data[i]
# #
# # return String
# # #生成PDF
# # def make_pdf():#首先将文本转化为图片,之后将所有图片合并
# #
# # img_path = r"./static/download"
# # pdf_path = r"./static/download"
# # pdf_name = r"1.pdf"
# #
# # a = txt2String('./static/download/data.txt')
# # make_pic(backMode, a, "https://imed.nimte.ac.cn/")
# # doc = fitz.open()
# # imgdoc = fitz.open('./static/download/output.png')
# # pdfbytes = imgdoc.convertToPDF()
# # imgpdf = fitz.open('pdf',pdfbytes)
# # doc.insertPDF(imgpdf)
# # doc.save('./static/download/output.PDF')
# # doc.close()
# #
# # doc = fitz.open()
# #
# # for img in sorted(glob.glob(img_path + "/*.png")):
# # imgdoc = fitz.open(img)
# # pdfbytes = imgdoc.convertToPDF()
# # imgpdf = fitz.open("pdf",pdfbytes)
# # doc.insertPDF(imgpdf)
# # doc.save('./static/download/output1.PDF')
# # doc.close
#
# #图像增强
# def img_enhance(img_path, dst_path):
# # EnhanceAPI.interface(img_path, dst_path)
# return
# #视杯视盘
# def img_sbsp(img_path, dst_path):
# SbspAPI.interface(img_path, dst_path)
# return
# def img_Tangwang(img_path, dst_path):
# tangwang_list, tangwang_num, _ = TangwangAPI.interface(img_path, dst_path)
# res = "糖网级别:" + str(tangwang_num) +",概率:" +str(round(tangwang_list[tangwang_num],2))
# return res
# ################################################################################
# ############################请带好口罩,出示健康码##################################
# #################某某路无人售票公交车,票价一元,持证请出示,下车请走好###################
# ################################################################################
# hash_util = DaoUtils.HashUtils()
# h = HimedDao.HimedDao()
# tmp_user = UserInfo.UserInfo()
# CORS(app=app)
# app.config['UPLOAD_FOLDER']='./uploads'
# @app.route("/upload/<path:file>", methods=['POST','GET'])
# def upload(file):
# if file=='dr':
# ul=[]
# picl=[]
# infol=[]
# print('111100-----------------',request.form['chunk'])
# for i in range(int(request.form['chunk'])):
# fileObj = request.files.get('files'+str(i))
# print(fileObj)
# fileObj.save(os.path.join(app.config['UPLOAD_FOLDER'],pre_process(fileObj.filename)[1]+'.png'))
# fileObj.save(os.path.join('./tmp/ct', pre_process(fileObj.filename)[1]+'.png'))
# ul.append('http://127.0.0.1:5000/tmp/ct/'+pre_process(fileObj.filename)[1]+'.png')
# rimg,info=test(os.path.join(app.config['UPLOAD_FOLDER'], pre_process(fileObj.filename)[1]+'.png'))
# infol.append(info)
# cv2.imwrite('tmp/dr/'+pre_process(fileObj.filename)[1]+'.png',rimg)
# picl.append('http://127.0.0.1:5000/tmp/dr/'+pre_process(fileObj.filename)[1]+'.png')
# return jsonify({'state':1,
# 'imgl':ul,
# 'imgcl':picl,
# 'infol':infol
# })
# elif file=='tw':
# ul = []
# picl = []
# infol = []
# print('111100-----------------', request.form['chunk'])
# for i in range(int(request.form['chunk'])):
# fileObj = request.files.get('files' + str(i))
# print(fileObj)
# fileObj.save(os.path.join(app.config['UPLOAD_FOLDER'], pre_process(fileObj.filename)[1] + '.png'))
# fileObj.save(os.path.join('./tmp/ct', pre_process(fileObj.filename)[1] + '.png'))
# ul.append('http://127.0.0.1:5000/tmp/ct/' + pre_process(fileObj.filename)[1] + '.png')
# rimg, info = tw(os.path.join(app.config['UPLOAD_FOLDER'], pre_process(fileObj.filename)[1] + '.png'))
# infol.append(info)
# cv2.imwrite('tmp/tw/' + pre_process(fileObj.filename)[1] + '.png', rimg)
# picl.append('http://127.0.0.1:5000/tmp/tw/' + pre_process(fileObj.filename)[1] + '.png')
# return jsonify({'state': 1,
# 'imgl': ul,
# 'imgcl': picl,
# 'infol': infol
# })
# @app.route("/uploads",methods=['POST','GET'])
# def uploads():
#
# f = request.files['file']
# basepath = os.path.dirname(__file__)
# upload_path = os.path.join(basepath, 'tmp', 'raw.png')
# upload_filename = secure_filename(f.filename)
# f.save(upload_path)
# img = cv2.imread(upload_path)
# Img_path = os.path.join(basepath, 'tmp', "vessel.png")
# print(Img_path, upload_path)
# cv2.imwrite(Img_path, img)
# cv2.imwrite(upload_path, img)
#
# small_scale = img.shape[0] / 512
# width = img.shape[0] / small_scale
# length = img.shape[1] / small_scale
#
# #width = 512
# #length = 512
# tangwang_res = img_Tangwang(upload_path, os.path.join(basepath, 'tmp', "vessel_tangwang.png"))
#
# img_enhance(upload_path, os.path.join(basepath, 'tmp', "vessel_enhance.png"))
# img_sbsp(upload_path, os.path.join(basepath, 'tmp', "vessel_sbsp.png"))
#
# dr_grading(upload_path, basepath)
#
# Img, feature_out, out = vessel_seg(upload_path)
#
# Img1, Img2 = applyImage(upload_path, Img, out)
#
# vessel_Arter(upload_path)
#
# Img_path = os.path.join(basepath, 'tmp', "vessel_white.png")
#
# cv2.imwrite(Img_path, Img)
# Img_path1 = os.path.join(basepath, 'tmp', "vessel_green.png")
#
# cv2.imwrite(Img_path1, Img1)
# Img_path2 = os.path.join(basepath, 'tmp', "vessel_red.png")
#
# cv2.imwrite(Img_path2, Img2)
#
# vessel_centerline("./tmp/vessel_white.png")
# #vessel_centerline("D:\\flaskProject723\\static\\download\\vessel_white.png")
#
# Tortuosity = str(round(feature_out[0][0], 2))
# VAD = str(round(feature_out[0][1], 2))
# VLD = str(round(feature_out[0][2], 2))
# FD = str(round(feature_out[0][3], 2))
# info = {'Width' : width,
# 'Length' : length,
# 'Feature_out_tor':Tortuosity,
# 'Feature_out_VAD':VAD,#
# 'Feature_out_VLD':VLD,
# 'Feature_out_FD':FD,
# 'tangwang_res':tangwang_res}
# xf_path={}
# xf_path['raw'] = 'raw.png'
# xf_path['vessel'] = 'vessel.png'
# xf_path['vessel_Ater'] = 'vessel_Ater.png'
# xf_path['vessel_white'] = 'vessel_white.png'
# xf_path['vessel_red'] = 'vessel_red.png'
# xf_path['vessel_green'] = 'vessel_green.png'
# xf_path['vessel_sbsp'] = 'vessel_sbsp.png'
# xf_path['vessel_centerline'] = 'vessel_centerline.png'
# xf_path['vessel_tangwang'] = 'vessel_tangwang.png'
# return jsonify({
# 'state': 1,
# 'path':xf_path,
# 'info':info
# })
# @app.route('/tmp/<path:file>', methods=['GET'])
#
# def show_photo(file):
# if request.method == 'GET':
# if not file is None:
# print(1)
# image_data = open(f'tmp/{file}', "rb").read()
# response = make_response(image_data)
# response.headers['Content-Type'] = 'image/png'
# return response
# if __name__ == "__main__":
# app.run()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/aprogrotess/Segmentation_webback_old.git
git@gitee.com:aprogrotess/Segmentation_webback_old.git
aprogrotess
Segmentation_webback_old
Segmentation_webback_old
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891