draw_multi.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.patches import Polygon
  4. from matplotlib.widgets import LassoSelector
  5. from matplotlib.path import Path
  6. import json
  7. import pydicom
  8. class ROIManager:
  9. def __init__(self, ax, image):
  10. self.ax = ax
  11. self.image = image
  12. self.rois = []
  13. self.current_poly = None
  14. self.history = []
  15. self.colors = plt.cm.get_cmap('tab10')
  16. self.color_index = 0
  17. self.ax.imshow(self.image, cmap='gray')
  18. self.lasso = LassoSelector(ax, onselect=self.on_select)
  19. self.cid = self.ax.figure.canvas.mpl_connect('key_press_event', self.on_key_press)
  20. def on_select(self, verts):
  21. path = Path(verts)
  22. color = self.colors(self.color_index % 10)
  23. self.color_index += 1
  24. patch = Polygon(verts, closed=True, edgecolor=color, facecolor='none', label=f'ROI {len(self.rois) + 1}')
  25. self.rois.append({'path': path, 'patch': patch, 'verts': verts})
  26. self.ax.add_patch(patch)
  27. self.history.append(('add', patch))
  28. self.ax.legend()
  29. self.ax.figure.canvas.draw_idle()
  30. def on_key_press(self, event):
  31. if event.key == 'u': # Undo
  32. if self.history:
  33. action, patch = self.history.pop()
  34. if action == 'add':
  35. patch.remove()
  36. self.rois = [roi for roi in self.rois if roi['patch'] != patch]
  37. elif action == 'remove':
  38. self.ax.add_patch(patch)
  39. self.rois.append({'path': patch.get_path(), 'patch': patch})
  40. self.ax.legend()
  41. self.ax.figure.canvas.draw_idle()
  42. elif event.key == 'd': # Delete selected ROI
  43. if self.current_poly:
  44. confirm = input(f"Do you want to delete {self.current_poly.get_label()}? (y/n): ")
  45. if confirm.lower() == 'y':
  46. self.current_poly.remove()
  47. self.rois = [roi for roi in self.rois if roi['patch'] != self.current_poly]
  48. self.history.append(('remove', self.current_poly))
  49. self.current_poly = None
  50. self.ax.legend()
  51. self.ax.figure.canvas.draw_idle()
  52. elif event.key == 's': # Save ROIs
  53. self.save_rois()
  54. def select_roi(self, event):
  55. for roi in self.rois:
  56. if roi['path'].contains_point((event.xdata, event.ydata)):
  57. self.current_poly = roi['patch']
  58. break
  59. def save_rois(self):
  60. roi_data = [{'label': roi['patch'].get_label(), 'vertices': roi['verts']} for roi in self.rois]
  61. with open('rois.json', 'w') as f:
  62. json.dump(roi_data, f)
  63. print("ROIs saved to rois.json")
  64. def get_rois_data(self):
  65. roi_data = [{'label': roi['patch'].get_label(), 'vertices': roi['verts']} for roi in self.rois]
  66. return roi_data
  67. def main():
  68. image = np.zeros((512, 512)) # Placeholder for MR image
  69. # Load an image (replace this with actual MR image loading)
  70. path = r'C:\Users\user\Desktop\knee_seg\LITVYAK_D.I\LITVYAK_D.I\2025-01-22 181006\IMG-0001-00001.dcm'
  71. file_dcm = pydicom.dcmread(path)
  72. image = file_dcm.pixel_array
  73. fig, ax = plt.subplots()
  74. roi_manager = ROIManager(ax, image)
  75. fig.canvas.mpl_connect('button_press_event', roi_manager.select_roi)
  76. plt.show()
  77. print(roi_manager.get_rois_data())
  78. if __name__ == "__main__":
  79. main()