文档服务地址:http://47.92.0.57:3000/ 周报索引地址:http://47.92.0.57:3000/s/NruNXRYmV

Commit 67dd991a by convivae

图片后端新增导出文件的api

parent 3de8394f
import traceback
import json
import random
import colorsys
import views.uploadDownload as fileDownload
from flask_mongoengine import MongoEngine
db = MongoEngine()
......@@ -32,6 +36,8 @@ class Point(db.EmbeddedDocument):
class Label(db.EmbeddedDocument):
labelId = db.IntField(required=True)
labelName = db.StringField(required=True)
lineColor = db.ListField(db.IntField())
fillColor = db.ListField(db.IntField())
pointList = db.ListField(db.EmbeddedDocumentField(Point))
def to_json(self):
......@@ -71,10 +77,13 @@ def create_points(point_list):
# 根据json列表创建对象列表
def create_labels(label_list):
res = []
for i in label_list:
colors = ncolors(len(label_list))
for i, c in zip(label_list, colors):
label = Label(
labelId=i['labelId'],
labelName=i['labelName'],
lineColor=list(c),
fillColor=list(c),
pointList=create_points(i['pointList'])
)
res.append(label)
......@@ -97,6 +106,14 @@ def create_images(image_list):
return res
# 根据 relationId 获取图片名称
def get_img_name(relation_id):
img = Image.objects(relationId=relation_id).first()
if img is None:
raise Exception("relation id = {} 的图片不存在".format(relation_id))
return img['imageUrl'].split('/')[-1]
# 根据 relationId 删除图片
def delete_image(relation_id):
obj = Image.objects(relationId=relation_id)
......@@ -104,6 +121,81 @@ def delete_image(relation_id):
obj.delete()
# 获取标注图片的颜色列表
def get_img_colors(relation_id):
obj = Image.objects(relationId=relation_id).first()
line_colors = []
fill_colors = []
labelList = obj['labelList']
if len(labelList[0]['lineColor']) != 0:
for i in labelList:
line_colors.append(i['lineColor'])
fill_colors.append(i['fillColor'])
else:
colors = ncolors(len(labelList))
for i, c in zip(labelList, colors):
i['fillColor'] = c
i['lineColor'] = c
obj.save()
line_colors = colors
fill_colors = colors
return line_colors, fill_colors
# 根据relationId获取原始图片对象
def export_original_img(relation_id):
try:
image_name = get_img_name(relation_id)
return fileDownload.download(image_name)
except Exception as e:
traceback.print_exc()
return Result(0, repr(e), {})
# 根据relationId获取图片json对象
def export_img_json(relation_id):
try:
ret = {'version': '3.10.0', 'flags': {}}
obj = Image.objects(relationId=relation_id).first()
label_list = obj['labelList']
line_colors, fill_colors = get_img_colors(relation_id)
shapes = []
for i, line_color, fill_color in zip(label_list, line_colors, fill_colors):
shape = {}
label_name = i['labelName']
point_list = i['pointList']
points = []
for j in point_list:
points.append([j['X'], j['Y']])
shape['label'] = label_name
shape['line_color'] = line_color
shape['fill_color'] = fill_color
shape['points'] = points
shape['shape_type'] = 'polygon'
shapes.append(shape)
ret['shapes'] = shapes
image_name = get_img_name(relation_id)
ret['imagePath'] = image_name
b64_data = fileDownload.get_image_base64(image_name)
if not isinstance(b64_data, str):
msg = json.loads(str(b64_data.data, encoding='utf-8'))
return Result(0, msg['errmsg'], {})
ret['imageData'] = b64_data
img_width, img_height = fileDownload.get_image_size(image_name)
ret['imageHeight'] = img_height
ret['imageWidth'] = img_width
return json.dumps(ret, ensure_ascii=False, indent=4)
except Exception as e:
traceback.print_exc()
return Result(0, repr(e), {})
# # 图层实体
# class LayerEntity(db.EmbeddedDocument):
# layerId = db.IntField(required=True)
......@@ -282,3 +374,34 @@ def saveLayer(layer_info, landmark_info):
except Exception as e:
traceback.print_exc()
return Result(0, repr(e), {})
# 获得n个高对比度的颜色
def get_n_hls_colors(num):
hls_colors = []
i = 0
step = 360.0 / num
while i < 360:
h = i
s = 90 + random.random() * 10
l = 50 + random.random() * 10
_hlsc = [h / 360.0, l / 100.0, s / 100.0]
hls_colors.append(_hlsc)
i += step
return hls_colors
# 获得n个高对比度的颜色
def ncolors(num):
rgba_colors = []
if num < 1:
return rgba_colors
hls_colors = get_n_hls_colors(num)
for hlsc in hls_colors:
_r, _g, _b = colorsys.hls_to_rgb(hlsc[0], hlsc[1], hlsc[2])
r, g, b = [int(x * 255.0) for x in (_r, _g, _b)]
a = random.randint(220, 255)
rgba_colors.append((r, g, b, a))
return rgba_colors
import json
from flask import Blueprint, jsonify, request
import PIL.Image
from flask import Blueprint, request, Response, make_response
from dao import Image, Relation
......@@ -80,15 +81,46 @@ def save_layer():
return json.dumps(res, ensure_ascii=False)
import views.uploadDownload as upd
@image.route("/image/exportImage/<relationId>", methods=['GET'])
def export_image(relationId):
img = Image.objects(relationId=relationId)
image_url = img['imageUrl'].split('/')[-1]
upd.download('')
return False
# 图像导出为原始图像、json、标注图像
@image.route("/image/export/original/<relationId>", methods=['GET'])
def export_original_img(relationId):
# 原始图像
original_img = Image.export_original_img(relationId)
if not isinstance(original_img, Response):
res = {
'code': original_img.code,
'message': original_img.message,
'data': original_img.data
}
return json.dumps(res, ensure_ascii=False)
return original_img
# 图像导出为原始图像、json、标注图像
@image.route("/image/export/json/<relationId>", methods=['GET'])
def export_json(relationId):
# json
image_name = Image.get_img_name(relationId).split('.')[0]
img_json = Image.export_img_json(relationId)
if isinstance(img_json, Image.Result):
res = {
'code': img_json.code,
'message': img_json.message,
'data': img_json.data
}
return json.dumps(res, ensure_ascii=False)
response = make_response(img_json)
response.headers["Content-Disposition"] = "p_w_upload; filename={}.json".format(image_name)
return response
@image.route("/image/export/label/<relationId>", methods=['GET'])
def export_label(relationId):
# 标注图像
return "False"
# 保存图片标注结果的测试数据
# {
......
......@@ -126,6 +126,33 @@ def get_image_file(imageName):
return jsonify({"code": 0, "errmsg": repr(e)})
# 根据图片名称返回图片的 base64 编码
def get_image_base64(imageName):
try:
file_dir = os.path.join(basedir, UPLOAD_FOLDER, imageName)
if not os.path.exists(file_dir):
return jsonify({"code": 0, "errmsg": u"the image '{}' doesn't exit!".format(imageName)})
with open(file_dir, 'rb') as f:
base64_data = base64.b64encode(f.read())
return str(base64_data, 'utf-8')
except Exception as e:
traceback.print_exc()
return jsonify({"code": 0, "errmsg": repr(e)})
# 根据图片名称返回图片的大小
def get_image_size(imageName):
try:
file_dir = os.path.join(basedir, UPLOAD_FOLDER, imageName)
if not os.path.exists(file_dir):
return jsonify({"code": 0, "errmsg": u"the image '{}' doesn't exit!".format(imageName)})
img = Image.open(file_dir)
return img.width, img.height
except Exception as e:
traceback.print_exc()
return jsonify({"code": 0, "errmsg": repr(e)})
# documentId获取文本内容
@uploadDownload.route('/getFileContent', methods=['POST'])
def getFileContent():
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment