dangtiendatdat commited on
Commit
f9ed910
·
verified ·
1 Parent(s): ade05f8

Update MeAI_Maincode/Polyb.py

Browse files
Files changed (1) hide show
  1. MeAI_Maincode/Polyb.py +60 -14
MeAI_Maincode/Polyb.py CHANGED
@@ -7,11 +7,11 @@ from lang_sam import LangSAM
7
  model = LangSAM()
8
 
9
  text_prompt = """
10
- A polyp is an anomalous oval-shaped small bump-like structure, a relatively small growth or
11
- mass that develops on the inner lining of the colon or other organs.
12
  Multiple polyps may exist in one image.
13
  """
14
 
 
15
  def highlight_mask_on_image(image, mask_np, color=(0, 200, 0), alpha=0.7):
16
  """Tô màu cho khu vực được xác định bởi mask lên hình ảnh gốc."""
17
  image_np = np.array(image)
@@ -25,24 +25,70 @@ def highlight_mask_on_image(image, mask_np, color=(0, 200, 0), alpha=0.7):
25
  highlighted_image[mask_indices] = (1 - alpha) * image_np[mask_indices] + alpha * np.array(color)
26
 
27
  return Image.fromarray(highlighted_image.astype(np.uint8))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  def main(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- image_pil = image.convert("RGB")
32
- masks, boxes, phrases, logits = model.predict(image_pil, text_prompt)
33
 
34
- if len(masks) == 1:
35
- print(f"No objects of the '{text_prompt}' prompt detected in the image.")
36
- return image_pil # Trả về ảnh gốc nếu không phát hiện ra mask
37
- masks_np = [mask.squeeze().cpu().numpy() for mask in masks]
38
 
39
- if len(masks_np) > 1:
40
- combined_mask = np.sum(masks_np[1:], axis=0) > 0
41
- else:
42
- combined_mask = masks_np[0]
43
- highlighted_image = highlight_mask_on_image(image_pil, combined_mask)
44
 
45
- return highlighted_image
 
 
 
 
46
  def create_polyb():
47
  demo = gr.Interface(
48
  fn=main,
 
7
  model = LangSAM()
8
 
9
  text_prompt = """
10
+ Focus on the inner circular region captured by the endoscopic camera. Identify only small, raised, and rounded growths (polyps) with smooth and well-defined edges. These polyps typically appear brighter or redder than the surrounding tissue and have a soft, protruding texture. Ignore any flat areas, reflections, or irregular shapes that do not match these criteria. Avoid including empty or uniformly colored regions without distinct structures.
 
11
  Multiple polyps may exist in one image.
12
  """
13
 
14
+
15
  def highlight_mask_on_image(image, mask_np, color=(0, 200, 0), alpha=0.7):
16
  """Tô màu cho khu vực được xác định bởi mask lên hình ảnh gốc."""
17
  image_np = np.array(image)
 
25
  highlighted_image[mask_indices] = (1 - alpha) * image_np[mask_indices] + alpha * np.array(color)
26
 
27
  return Image.fromarray(highlighted_image.astype(np.uint8))
28
+ def display_masks_np(masks_np):
29
+ """
30
+ Hiển thị từng mask từ danh sách masks_np.
31
+
32
+ Parameters:
33
+ masks_np (list): Danh sách các mask dưới dạng numpy array.
34
+
35
+ Returns:
36
+ None: Hiển thị từng mask.
37
+ """
38
+ import matplotlib.pyplot as plt
39
+
40
+ print(f"Number of masks to display: {len(masks_np)}")
41
+ for i, mask_np in enumerate(masks_np):
42
+ print(f"Mask {i + 1} statistics: min={np.min(mask_np)}, max={np.max(mask_np)}, sum={np.sum(mask_np)}")
43
+
44
+ if np.sum(mask_np) > 0: # Chỉ hiển thị mask nếu không rỗng
45
+ plt.imshow(mask_np, cmap="gray")
46
+ plt.title(f"Mask {i + 1}")
47
+ plt.axis("off")
48
+ plt.show()
49
+ else:
50
+ print(f"Mask {i + 1} is empty (all zeros).")
51
 
52
  def main(image):
53
+ # Convert image to RGB
54
+ image_pil = image.convert("RGB")
55
+
56
+ # Get prediction results from the model
57
+ res = model.predict([image_pil], [text_prompt])
58
+
59
+ # Check if the result has the expected structure
60
+ if not isinstance(res, list) or len(res) == 0 or not isinstance(res[0], dict):
61
+ raise ValueError("Unexpected result structure from model.predict")
62
+
63
+ # Extract masks, boxes, phrases, and logits from the result
64
+ masks = res[0].get("masks", [])
65
+ boxes = res[0].get("boxes", [])
66
+ phrases = res[0].get("phrases", [])
67
+ logits = res[0].get("scores", [])
68
+
69
+ # Handle the case where no masks are detected
70
+ if len(masks) == 0:
71
+ print(f"No objects of the '{text_prompt}' prompt detected in the image.")
72
+ return image_pil # Return the original image if no masks are detected
73
 
74
+ # Convert masks to numpy arrays (if not already numpy arrays)
75
+ masks_np = [mask.squeeze() if isinstance(mask, np.ndarray) else mask.cpu().numpy() for mask in masks]
76
 
77
+ # Skip the first mask and process only masks from the second one onwards
78
+ if len(masks_np) > 1:
79
+ masks_np = masks_np[1:] # Bỏ mask đầu tiên
 
80
 
81
+ # Combine masks if there are multiple masks
82
+ if len(masks_np) > 1:
83
+ combined_mask = np.sum(masks_np, axis=0) > 0
84
+ else:
85
+ combined_mask = masks_np[0]
86
 
87
+ # Highlight the combined mask on the original image
88
+ highlighted_image = highlight_mask_on_image(image_pil, combined_mask)
89
+ #display_masks_np(masks_np) # Display the remaining masks
90
+ return highlighted_image # Return the highlighted image
91
+
92
  def create_polyb():
93
  demo = gr.Interface(
94
  fn=main,