shawntan123 commited on
Commit
cdf1c08
·
verified ·
1 Parent(s): db5ca18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -12
app.py CHANGED
@@ -23,8 +23,9 @@ models = {
23
 
24
  def identify_objects(input_img):
25
  global models
26
- if input_img is None: return None, "请上传图片"
27
-
 
28
  try:
29
  if "object_detector" not in models:
30
  from transformers import pipeline
@@ -33,12 +34,14 @@ def identify_objects(input_img):
33
  model="hustvl/yolos-tiny",
34
  device=-1
35
  )
36
-
37
  img_pil = input_img.convert("RGB")
38
  results = models["object_detector"](img_pil)
39
 
40
  draw = ImageDraw.Draw(img_pil)
41
- detection_text = "识别结果如下:\n" # 用于存储输出到文本框的文字
 
 
42
 
43
  count = 0
44
  for res in results:
@@ -48,19 +51,38 @@ def identify_objects(input_img):
48
  label = res["label"]
49
  score = res["score"]
50
 
51
- # 1. 绘制逻辑保持不变
52
  draw.rectangle([box["xmin"], box["ymin"], box["xmax"], box["ymax"]], outline="red", width=4)
53
 
54
- # 2. 拼接文本信息
55
- detection_text += f"{count}. 目标: {label} | 置信度: {score:.2%}\n"
 
 
 
 
 
 
 
 
 
 
56
 
57
- if count == 0:
58
- detection_text = "未识别到显著目标(置信度 > 50%)"
59
-
60
- return img_pil, detection_text # 返回两个对象
 
 
 
 
 
61
 
62
  except Exception as e:
63
- return input_img, f"识别失败: {str(e)}"
 
 
 
 
64
 
65
  def process_rembg(input_img):
66
  global models
 
23
 
24
  def identify_objects(input_img):
25
  global models
26
+ if input_img is None:
27
+ return None, json.dumps({"error": "请上传图片"}, ensure_ascii=False)
28
+
29
  try:
30
  if "object_detector" not in models:
31
  from transformers import pipeline
 
34
  model="hustvl/yolos-tiny",
35
  device=-1
36
  )
37
+
38
  img_pil = input_img.convert("RGB")
39
  results = models["object_detector"](img_pil)
40
 
41
  draw = ImageDraw.Draw(img_pil)
42
+
43
+ # 准备一个列表存储结构化数据
44
+ detections = []
45
 
46
  count = 0
47
  for res in results:
 
51
  label = res["label"]
52
  score = res["score"]
53
 
54
+ # 绘制逻辑
55
  draw.rectangle([box["xmin"], box["ymin"], box["xmax"], box["ymax"]], outline="red", width=4)
56
 
57
+ # 信息添加到列表
58
+ detections.append({
59
+ "id": count,
60
+ "label": label,
61
+ "confidence": round(score, 4), # 保留4位小数
62
+ "box": {
63
+ "xmin": int(box["xmin"]),
64
+ "ymin": int(box["ymin"]),
65
+ "xmax": int(box["xmax"]),
66
+ "ymax": int(box["ymax"])
67
+ }
68
+ })
69
 
70
+ # 构造最终的 JSON 响应
71
+ output_json = {
72
+ "status": "success",
73
+ "count": count,
74
+ "detections": detections
75
+ }
76
+
77
+ # 使用 json.dumps 转换为字符串,ensure_ascii=False 保证中文不乱码
78
+ return img_pil, json.dumps(output_json, ensure_ascii=False, indent=4)
79
 
80
  except Exception as e:
81
+ error_json = {
82
+ "status": "error",
83
+ "message": str(e)
84
+ }
85
+ return input_img, json.dumps(error_json, ensure_ascii=False)
86
 
87
  def process_rembg(input_img):
88
  global models