LineGrayscaleMeasurementTool.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. import { Point3, Point2 } from './mathUtils';
  2. import {
  3. utilities as csUtils,
  4. Types as CoreTypes,
  5. getEnabledElement,
  6. cache,
  7. } from '@cornerstonejs/core';
  8. import * as cornerstone from '@cornerstonejs/core';
  9. import {
  10. AnnotationTool,
  11. utilities,
  12. Types,
  13. annotation,
  14. drawing,
  15. } from '@cornerstonejs/tools';
  16. const {
  17. drawHandles,
  18. drawLinkedTextBox,
  19. drawLine: drawLineSvg,
  20. } = drawing;
  21. import {
  22. PublicToolProps,
  23. ToolProps,
  24. EventTypes,
  25. SVGDrawingHelper,
  26. } from '@cornerstonejs/tools/dist/esm/types';
  27. /**
  28. * 直线灰度测量注解接口
  29. */
  30. interface LineGrayscaleAnnotation extends Types.Annotation {
  31. data: {
  32. handles: {
  33. // 控制点(两个端点,世界坐标)
  34. points: CoreTypes.Point3[];
  35. // 当前激活的手柄索引(0或1,null表示未激活)
  36. activeHandleIndex: number | null;
  37. };
  38. label?: string;
  39. // 文本框位置(Canvas坐标)
  40. textBox?: CoreTypes.Point2;
  41. // 缓存的统计结果
  42. cachedStats?: {
  43. [targetId: string]: {
  44. // 平均灰度值
  45. mean: number;
  46. // 最小灰度值
  47. min: number;
  48. // 最大灰度值
  49. max: number;
  50. // 采样点数量
  51. sampleCount: number;
  52. // 直线长度(mm)
  53. lineLength: number;
  54. };
  55. };
  56. };
  57. }
  58. /**
  59. * 像素采样结果
  60. */
  61. interface PixelSampleResult {
  62. values: number[];
  63. coordinates: Array<{ x: number; y: number }>;
  64. count: number;
  65. }
  66. /**
  67. * 直线灰度测量工具
  68. * 功能: 在医学影像上绘制直线,计算并显示直线路径上的灰度值统计信息
  69. */
  70. export default class LineGrayscaleMeasurementTool extends AnnotationTool {
  71. static toolName = 'LineGrayscaleMeasurementTool';
  72. editData: {
  73. annotation: Types.Annotation;
  74. viewportIdsToRender: string[];
  75. handleIndex?: number;
  76. newAnnotation?: boolean;
  77. hasMoved?: boolean;
  78. textBoxBeingMoved?: boolean;
  79. textBoxOffset?: CoreTypes.Point2;
  80. } | null = null;
  81. isDrawing: boolean = false;
  82. /**
  83. * 创建默认注解(工具激活时自动创建)
  84. */
  85. static createDefaultAnnotation(
  86. element: HTMLDivElement,
  87. viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
  88. ): LineGrayscaleAnnotation {
  89. const enabledElement = getEnabledElement(element);
  90. if (!enabledElement) {
  91. throw new Error('Element is not enabled');
  92. }
  93. // 获取viewport的尺寸
  94. const canvas = viewport.canvas;
  95. const { width, height } = canvas;
  96. const centerX = width / 2;
  97. const centerY = height / 2;
  98. // 设置起点和终点(Canvas坐标,水平线,长度100px)
  99. const startCanvas: CoreTypes.Point2 = [centerX - 50, centerY];
  100. const endCanvas: CoreTypes.Point2 = [centerX + 50, centerY];
  101. // 转换为世界坐标
  102. const startWorld = viewport.canvasToWorld(startCanvas);
  103. const endWorld = viewport.canvasToWorld(endCanvas);
  104. const camera = viewport.getCamera();
  105. const { viewPlaneNormal, viewUp } = camera;
  106. if (viewPlaneNormal === undefined || viewUp === undefined) {
  107. throw new Error('Camera parameters are undefined');
  108. }
  109. // 创建注解对象
  110. const annotationData = {
  111. invalidated: true,
  112. highlighted: false,
  113. metadata: {
  114. viewPlaneNormal: [...viewPlaneNormal] as CoreTypes.Point3,
  115. viewUp: [...viewUp] as CoreTypes.Point3,
  116. FrameOfReferenceUID: viewport.getFrameOfReferenceUID(),
  117. referencedImageId: viewport.getCurrentImageId?.() || '',
  118. toolName: LineGrayscaleMeasurementTool.toolName,
  119. },
  120. data: {
  121. label: '',
  122. handles: {
  123. points: [startWorld, endWorld],
  124. activeHandleIndex: null,
  125. },
  126. cachedStats: {},
  127. },
  128. } as LineGrayscaleAnnotation;
  129. return annotationData;
  130. }
  131. constructor(
  132. toolProps: PublicToolProps = {},
  133. defaultToolProps: ToolProps = {
  134. supportedInteractionTypes: ['Mouse', 'Touch'],
  135. configuration: {
  136. shadow: true,
  137. preventHandleOutsideImage: false,
  138. },
  139. }
  140. ) {
  141. super(toolProps, defaultToolProps);
  142. }
  143. /**
  144. * 禁用手动绘制(仅支持预设注解)
  145. */
  146. addNewAnnotation(
  147. evt: EventTypes.InteractionEventType
  148. ): LineGrayscaleAnnotation {
  149. evt.preventDefault();
  150. return {} as LineGrayscaleAnnotation;
  151. }
  152. /**
  153. * 检查点是否靠近工具
  154. */
  155. isPointNearTool(
  156. element: HTMLDivElement,
  157. annotation: LineGrayscaleAnnotation,
  158. canvasCoords: CoreTypes.Point2,
  159. proximity: number
  160. ): boolean {
  161. const enabledElement = getEnabledElement(element);
  162. if (!enabledElement) {
  163. return false;
  164. }
  165. const { viewport } = enabledElement;
  166. const points = annotation.data.handles.points;
  167. // 检查是否靠近任意一个手柄点
  168. for (let i = 0; i < points.length; i++) {
  169. const point = points[i];
  170. const canvasPoint = viewport.worldToCanvas(point);
  171. const distance = Math.sqrt(
  172. Math.pow(canvasPoint[0] - canvasCoords[0], 2) +
  173. Math.pow(canvasPoint[1] - canvasCoords[1], 2)
  174. );
  175. if (distance < proximity) {
  176. return true;
  177. }
  178. }
  179. // 检查是否靠近直线
  180. if (points.length >= 2) {
  181. const p1Canvas = viewport.worldToCanvas(points[0]);
  182. const p2Canvas = viewport.worldToCanvas(points[1]);
  183. const dist = this._distanceToSegment(canvasCoords, p1Canvas, p2Canvas);
  184. if (dist < proximity) {
  185. return true;
  186. }
  187. }
  188. return false;
  189. }
  190. /**
  191. * 计算点到线段的距离
  192. */
  193. private _distanceToSegment(
  194. point: CoreTypes.Point2,
  195. lineStart: CoreTypes.Point2,
  196. lineEnd: CoreTypes.Point2
  197. ): number {
  198. const x = point[0];
  199. const y = point[1];
  200. const x1 = lineStart[0];
  201. const y1 = lineStart[1];
  202. const x2 = lineEnd[0];
  203. const y2 = lineEnd[1];
  204. const A = x - x1;
  205. const B = y - y1;
  206. const C = x2 - x1;
  207. const D = y2 - y1;
  208. const dot = A * C + B * D;
  209. const lenSq = C * C + D * D;
  210. let param = -1;
  211. if (lenSq !== 0) {
  212. param = dot / lenSq;
  213. }
  214. let xx, yy;
  215. if (param < 0) {
  216. xx = x1;
  217. yy = y1;
  218. } else if (param > 1) {
  219. xx = x2;
  220. yy = y2;
  221. } else {
  222. xx = x1 + param * C;
  223. yy = y1 + param * D;
  224. }
  225. const dx = x - xx;
  226. const dy = y - yy;
  227. return Math.sqrt(dx * dx + dy * dy);
  228. }
  229. /**
  230. * 取消操作
  231. */
  232. cancel(element: HTMLDivElement): string {
  233. if (this.isDrawing) {
  234. this.isDrawing = false;
  235. this._deactivateDraw(element);
  236. this._deactivateModify(element);
  237. const enabledElement = getEnabledElement(element);
  238. if (enabledElement) {
  239. const viewportIdsToRender =
  240. utilities.viewportFilters.getViewportIdsWithToolToRender(
  241. element,
  242. this.getToolName()
  243. );
  244. utilities.triggerAnnotationRenderForViewportIds(
  245. viewportIdsToRender
  246. );
  247. }
  248. this.editData = null;
  249. return this.getToolName();
  250. }
  251. return '';
  252. }
  253. _activateDraw(element: HTMLDivElement): void {
  254. element.addEventListener(
  255. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  256. this._dragCallback as EventListener
  257. );
  258. element.addEventListener(
  259. 'CORNERSTONE_TOOLS_MOUSE_UP',
  260. this._endCallback as EventListener
  261. );
  262. }
  263. _deactivateDraw(element: HTMLDivElement): void {
  264. element.removeEventListener(
  265. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  266. this._dragCallback as EventListener
  267. );
  268. element.removeEventListener(
  269. 'CORNERSTONE_TOOLS_MOUSE_UP',
  270. this._endCallback as EventListener
  271. );
  272. }
  273. _activateModify(element: HTMLDivElement): void {
  274. element.addEventListener(
  275. 'CORNERSTONE_TOOLS_MOUSE_DOWN',
  276. this._mouseDownModifyCallback as EventListener
  277. );
  278. element.addEventListener(
  279. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  280. this._mouseDragModifyCallback as EventListener
  281. );
  282. element.addEventListener(
  283. 'CORNERSTONE_TOOLS_MOUSE_UP',
  284. this._mouseUpModifyCallback as EventListener
  285. );
  286. element.addEventListener(
  287. 'CORNERSTONE_TOOLS_MOUSE_MOVE',
  288. this._mouseMoveModifyCallback as EventListener
  289. );
  290. element.addEventListener(
  291. 'keydown',
  292. this._keyDownCallback as EventListener
  293. );
  294. }
  295. _deactivateModify(element: HTMLDivElement): void {
  296. element.removeEventListener(
  297. 'CORNERSTONE_TOOLS_MOUSE_DOWN',
  298. this._mouseDownModifyCallback as EventListener
  299. );
  300. element.removeEventListener(
  301. 'CORNERSTONE_TOOLS_MOUSE_DRAG',
  302. this._mouseDragModifyCallback as EventListener
  303. );
  304. element.removeEventListener(
  305. 'CORNERSTONE_TOOLS_MOUSE_UP',
  306. this._mouseUpModifyCallback as EventListener
  307. );
  308. element.removeEventListener(
  309. 'CORNERSTONE_TOOLS_MOUSE_MOVE',
  310. this._mouseMoveModifyCallback as EventListener
  311. );
  312. element.removeEventListener(
  313. 'keydown',
  314. this._keyDownCallback as EventListener
  315. );
  316. }
  317. _mouseDownModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  318. const eventDetail = evt.detail;
  319. const { element, currentPoints } = eventDetail;
  320. const canvasCoords = currentPoints.canvas;
  321. const enabledElement = getEnabledElement(element);
  322. if (!enabledElement) {
  323. return;
  324. }
  325. const { viewport } = enabledElement;
  326. const annotations = annotation.state.getAnnotations(this.getToolName(), element);
  327. if (!annotations || annotations.length === 0) {
  328. return;
  329. }
  330. // 查找最近的手柄
  331. for (const ann of annotations) {
  332. const customAnn = ann as LineGrayscaleAnnotation;
  333. const handle = this.getHandleNearImagePoint(
  334. element,
  335. customAnn,
  336. canvasCoords,
  337. 6
  338. );
  339. if (handle) {
  340. const viewportIdsToRender =
  341. utilities.viewportFilters.getViewportIdsWithToolToRender(
  342. element,
  343. this.getToolName()
  344. );
  345. this.editData = {
  346. annotation: customAnn,
  347. viewportIdsToRender,
  348. handleIndex: customAnn.data.handles.activeHandleIndex || 0,
  349. hasMoved: false,
  350. };
  351. customAnn.isSelected = true;
  352. customAnn.highlighted = true;
  353. utilities.triggerAnnotationRenderForViewportIds(
  354. viewportIdsToRender
  355. );
  356. evt.preventDefault();
  357. evt.stopPropagation();
  358. return;
  359. }
  360. }
  361. // 如果没有点击在工具上,取消所有选中状态
  362. for (const ann of annotations) {
  363. const customAnn = ann as LineGrayscaleAnnotation;
  364. customAnn.isSelected = false;
  365. }
  366. };
  367. _mouseDragModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  368. if (!this.editData) {
  369. return;
  370. }
  371. const eventDetail = evt.detail;
  372. const { currentPoints } = eventDetail;
  373. const enabledElement = getEnabledElement(eventDetail.element);
  374. if (!enabledElement) {
  375. return;
  376. }
  377. const { annotation: ann, viewportIdsToRender } = this.editData;
  378. const customAnn = ann as LineGrayscaleAnnotation;
  379. const { data } = customAnn;
  380. // 处理手柄拖拽
  381. const worldPos = currentPoints.world;
  382. const activeHandleIndex = data.handles.activeHandleIndex;
  383. if (activeHandleIndex !== null && activeHandleIndex >= 0 && activeHandleIndex < data.handles.points.length) {
  384. data.handles.points[activeHandleIndex] = worldPos;
  385. this._updateCachedStats(customAnn, enabledElement);
  386. this.editData.hasMoved = true;
  387. utilities.triggerAnnotationRenderForViewportIds(
  388. viewportIdsToRender
  389. );
  390. evt.preventDefault();
  391. evt.stopPropagation();
  392. }
  393. };
  394. _mouseUpModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  395. if (!this.editData) {
  396. return;
  397. }
  398. const { annotation: ann } = this.editData;
  399. const customAnn = ann as LineGrayscaleAnnotation;
  400. customAnn.data.handles.activeHandleIndex = null;
  401. customAnn.highlighted = false;
  402. const eventDetail = evt.detail;
  403. const { element } = eventDetail;
  404. const viewportIdsToRender =
  405. utilities.viewportFilters.getViewportIdsWithToolToRender(
  406. element,
  407. this.getToolName()
  408. );
  409. utilities.triggerAnnotationRenderForViewportIds(
  410. viewportIdsToRender
  411. );
  412. this.editData = null;
  413. evt.preventDefault();
  414. evt.stopPropagation();
  415. };
  416. _mouseMoveModifyCallback = (evt: EventTypes.InteractionEventType): void => {
  417. const eventDetail = evt.detail;
  418. const { element, currentPoints } = eventDetail;
  419. if (!currentPoints || !currentPoints.canvas) {
  420. return;
  421. }
  422. const canvasCoords = currentPoints.canvas;
  423. const enabledElement = getEnabledElement(element);
  424. if (!enabledElement) {
  425. return;
  426. }
  427. const { viewport } = enabledElement;
  428. const annotations = annotation.state.getAnnotations(this.getToolName(), element);
  429. if (!annotations || annotations.length === 0) {
  430. element.style.cursor = 'default';
  431. return;
  432. }
  433. let isHovering = false;
  434. // 检查是否悬停在手柄或直线上
  435. for (const ann of annotations) {
  436. const customAnn = ann as LineGrayscaleAnnotation;
  437. // 检查是否靠近手柄
  438. const handle = this.getHandleNearImagePoint(element, customAnn, canvasCoords, 6);
  439. if (handle) {
  440. element.style.cursor = 'crosshair';
  441. customAnn.highlighted = true;
  442. isHovering = true;
  443. break;
  444. }
  445. // 检查是否靠近直线
  446. if (this.isPointNearTool(element, customAnn, canvasCoords, 10)) {
  447. element.style.cursor = 'crosshair';
  448. customAnn.highlighted = true;
  449. isHovering = true;
  450. break;
  451. }
  452. }
  453. // 如果没有悬停,重置高亮和光标
  454. if (!isHovering) {
  455. for (const ann of annotations) {
  456. const customAnn = ann as LineGrayscaleAnnotation;
  457. customAnn.highlighted = false;
  458. }
  459. element.style.cursor = 'default';
  460. }
  461. // 触发渲染以更新高亮状态
  462. const viewportIdsToRender = utilities.viewportFilters.getViewportIdsWithToolToRender(
  463. element,
  464. this.getToolName()
  465. );
  466. utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
  467. };
  468. _keyDownCallback = (evt: KeyboardEvent): void => {
  469. if (evt.key === 'Delete') {
  470. const element = document.activeElement as HTMLDivElement;
  471. if (!element) return;
  472. const annotations = annotation.state.getAnnotations(this.getToolName(), element);
  473. // 查找选中的注解
  474. const selectedAnnotation = annotations.find(ann => ann.isSelected);
  475. if (selectedAnnotation) {
  476. // 删除选中的注解
  477. annotation.state.removeAnnotation(selectedAnnotation.annotationUID || '');
  478. // 触发视图更新
  479. const viewportIdsToRender =
  480. utilities.viewportFilters.getViewportIdsWithToolToRender(
  481. element,
  482. this.getToolName()
  483. );
  484. utilities.triggerAnnotationRenderForViewportIds(viewportIdsToRender);
  485. evt.preventDefault();
  486. evt.stopPropagation();
  487. }
  488. }
  489. };
  490. handleSelectedCallback(
  491. evt: EventTypes.InteractionEventType,
  492. annotation: LineGrayscaleAnnotation
  493. ): void {
  494. const eventDetail = evt.detail;
  495. const { element } = eventDetail;
  496. annotation.highlighted = true;
  497. const viewportIdsToRender =
  498. utilities.viewportFilters.getViewportIdsWithToolToRender(
  499. element,
  500. this.getToolName()
  501. );
  502. utilities.triggerAnnotationRenderForViewportIds(
  503. viewportIdsToRender
  504. );
  505. evt.preventDefault();
  506. }
  507. toolSelectedCallback(
  508. evt: EventTypes.InteractionEventType,
  509. annotation: LineGrayscaleAnnotation
  510. ): void {
  511. // 实现工具选中逻辑
  512. }
  513. _dragCallback = (evt: EventTypes.InteractionEventType): void => {
  514. this.isDrawing = true;
  515. // 实现拖拽逻辑
  516. };
  517. _endCallback = (evt: EventTypes.InteractionEventType): void => {
  518. // 实现结束逻辑
  519. };
  520. getHandleNearImagePoint(
  521. element: HTMLDivElement,
  522. annotation: LineGrayscaleAnnotation,
  523. canvasCoords: CoreTypes.Point2,
  524. proximity: number
  525. ): Types.ToolHandle | undefined {
  526. const enabledElement = getEnabledElement(element);
  527. if (!enabledElement) {
  528. return undefined;
  529. }
  530. const { viewport } = enabledElement;
  531. const points = annotation.data.handles.points;
  532. const handleProximity = Math.max(proximity, 15);
  533. for (let i = 0; i < points.length; i++) {
  534. const point = points[i];
  535. const canvasPoint = viewport.worldToCanvas(point);
  536. const distance = Math.sqrt(
  537. Math.pow(canvasPoint[0] - canvasCoords[0], 2) +
  538. Math.pow(canvasPoint[1] - canvasCoords[1], 2)
  539. );
  540. if (distance < handleProximity) {
  541. annotation.data.handles.activeHandleIndex = i;
  542. return {
  543. worldPosition: point,
  544. } as Types.ToolHandle;
  545. }
  546. }
  547. annotation.data.handles.activeHandleIndex = null;
  548. return undefined;
  549. }
  550. /**
  551. * 更新缓存的统计数据
  552. */
  553. private _updateCachedStats(
  554. annotation: LineGrayscaleAnnotation,
  555. enabledElement: CoreTypes.IEnabledElement
  556. ): void {
  557. const { viewport } = enabledElement;
  558. const { points } = annotation.data.handles;
  559. if (points.length < 2) {
  560. return;
  561. }
  562. // 使用Cornerstone缓存系统获取图像
  563. const imageId = viewport.getCurrentImageId?.();
  564. if (!imageId) {
  565. console.warn('[LineGrayscaleTool] No imageId available');
  566. return;
  567. }
  568. const image = cornerstone.cache.getImage(imageId);
  569. if (!image) {
  570. console.warn('[LineGrayscaleTool] Image not found in cache');
  571. return;
  572. }
  573. // 采样像素
  574. const sampleResult = this._samplePixelsAlongLine(points[0], points[1], image, viewport);
  575. // 计算统计值
  576. const stats = this._calculateGrayscaleStats(sampleResult.values, points[0], points[1]);
  577. // 更新缓存
  578. const targetId = `imageId:${imageId}`;
  579. if (!annotation.data.cachedStats) {
  580. annotation.data.cachedStats = {};
  581. }
  582. annotation.data.cachedStats[targetId] = stats;
  583. }
  584. /**
  585. * 沿直线采样像素(Bresenham算法)
  586. */
  587. private _samplePixelsAlongLine(
  588. startWorld: CoreTypes.Point3,
  589. endWorld: CoreTypes.Point3,
  590. image: any,
  591. viewport: CoreTypes.IStackViewport | CoreTypes.IVolumeViewport
  592. ): PixelSampleResult {
  593. // 使用正确的API获取像素数据
  594. const pixelData = image.getPixelData();
  595. const { width, height } = image;
  596. // 使用viewport坐标转换(世界坐标→Canvas坐标)
  597. const startCanvas = viewport.worldToCanvas(startWorld);
  598. const endCanvas = viewport.worldToCanvas(endWorld);
  599. // Canvas坐标直接对应像素坐标(对于2D视图)
  600. const startPixel = [
  601. Math.floor(startCanvas[0]),
  602. Math.floor(startCanvas[1]),
  603. ];
  604. const endPixel = [
  605. Math.floor(endCanvas[0]),
  606. Math.floor(endCanvas[1]),
  607. ];
  608. // Bresenham直线算法
  609. const pixels = this._bresenhamLine(
  610. startPixel[0],
  611. startPixel[1],
  612. endPixel[0],
  613. endPixel[1]
  614. );
  615. // 采样灰度值
  616. const values: number[] = [];
  617. const coordinates: Array<{ x: number; y: number }> = [];
  618. for (const pixel of pixels) {
  619. const { x, y } = pixel;
  620. // 边界检查
  621. if (x < 0 || x >= width || y < 0 || y >= height) {
  622. continue;
  623. }
  624. // 计算像素索引(行优先)
  625. const index = y * width + x;
  626. const value = pixelData[index];
  627. values.push(value);
  628. coordinates.push({ x, y });
  629. }
  630. return {
  631. values,
  632. coordinates,
  633. count: values.length,
  634. };
  635. }
  636. /**
  637. * Bresenham直线算法实现
  638. */
  639. private _bresenhamLine(
  640. x0: number,
  641. y0: number,
  642. x1: number,
  643. y1: number
  644. ): Array<{ x: number; y: number }> {
  645. const pixels: Array<{ x: number; y: number }> = [];
  646. const dx = Math.abs(x1 - x0);
  647. const dy = Math.abs(y1 - y0);
  648. const sx = x0 < x1 ? 1 : -1;
  649. const sy = y0 < y1 ? 1 : -1;
  650. let err = dx - dy;
  651. let x = x0;
  652. let y = y0;
  653. while (true) {
  654. pixels.push({ x, y });
  655. if (x === x1 && y === y1) break;
  656. const e2 = 2 * err;
  657. if (e2 > -dy) {
  658. err -= dy;
  659. x += sx;
  660. }
  661. if (e2 < dx) {
  662. err += dx;
  663. y += sy;
  664. }
  665. }
  666. return pixels;
  667. }
  668. /**
  669. * 计算灰度统计值
  670. */
  671. private _calculateGrayscaleStats(
  672. values: number[],
  673. startWorld: CoreTypes.Point3,
  674. endWorld: CoreTypes.Point3
  675. ): {
  676. mean: number;
  677. min: number;
  678. max: number;
  679. sampleCount: number;
  680. lineLength: number;
  681. } {
  682. if (values.length === 0) {
  683. return {
  684. mean: 0,
  685. min: 0,
  686. max: 0,
  687. sampleCount: 0,
  688. lineLength: 0,
  689. };
  690. }
  691. // 计算平均值
  692. const sum = values.reduce((acc, val) => acc + val, 0);
  693. const mean = Math.round(sum / values.length);
  694. // 计算最小值和最大值
  695. const min = Math.min(...values);
  696. const max = Math.max(...values);
  697. // 计算物理距离(mm)
  698. const dx = endWorld[0] - startWorld[0];
  699. const dy = endWorld[1] - startWorld[1];
  700. const dz = endWorld[2] - startWorld[2];
  701. const lineLength = Math.sqrt(dx * dx + dy * dy + dz * dz);
  702. return {
  703. mean,
  704. min,
  705. max,
  706. sampleCount: values.length,
  707. lineLength: parseFloat(lineLength.toFixed(2)),
  708. };
  709. }
  710. /**
  711. * 渲染注解
  712. */
  713. renderAnnotation = (
  714. enabledElement: CoreTypes.IEnabledElement,
  715. svgDrawingHelper: SVGDrawingHelper
  716. ): boolean => {
  717. const { viewport } = enabledElement;
  718. const { element } = viewport;
  719. let annotations = annotation.state.getAnnotations(
  720. LineGrayscaleMeasurementTool.toolName,
  721. element
  722. ) as LineGrayscaleAnnotation[];
  723. if (!annotations || annotations.length === 0) {
  724. return false;
  725. }
  726. const targetId = `imageId:${(viewport as any).getCurrentImageId?.() || ''}`;
  727. const styleSpecifier: any = {
  728. toolGroupId: this.toolGroupId,
  729. toolName: this.getToolName(),
  730. viewportId: viewport.id,
  731. };
  732. for (const annotationItem of annotations) {
  733. const { annotationUID, data } = annotationItem;
  734. const { points } = data.handles;
  735. const canvasCoordinates = points.map((p) => viewport.worldToCanvas(p));
  736. if (!annotationUID) {
  737. continue;
  738. }
  739. styleSpecifier.annotationUID = annotationUID;
  740. const lineWidth = this.getStyle('lineWidth', styleSpecifier, annotationItem);
  741. const lineDash = this.getStyle('lineDash', styleSpecifier, annotationItem);
  742. const color = this.getStyle('color', styleSpecifier, annotationItem);
  743. // 绘制直线
  744. const lineUID = `${annotationUID}-line`;
  745. drawLineSvg(
  746. svgDrawingHelper,
  747. annotationUID,
  748. lineUID,
  749. canvasCoordinates[0],
  750. canvasCoordinates[1],
  751. {
  752. color,
  753. width: lineWidth,
  754. lineDash,
  755. }
  756. );
  757. // 绘制手柄
  758. const handleGroupUID = `${annotationUID}-handles`;
  759. drawHandles(
  760. svgDrawingHelper,
  761. annotationUID,
  762. handleGroupUID,
  763. canvasCoordinates,
  764. {
  765. color,
  766. }
  767. );
  768. // 绘制统计文本
  769. const stats = data.cachedStats?.[targetId];
  770. if (stats) {
  771. const textLines = [
  772. `平均: ${stats.mean}`,
  773. `最小: ${stats.min}`,
  774. `最大: ${stats.max}`,
  775. `长度: ${stats.lineLength.toFixed(2)}mm`,
  776. ];
  777. const textBoxPosition = data.textBox || canvasCoordinates[1];
  778. const textBoxUID = `${annotationUID}-text`;
  779. drawLinkedTextBox(
  780. svgDrawingHelper,
  781. annotationUID,
  782. textBoxUID,
  783. textLines,
  784. textBoxPosition,
  785. [canvasCoordinates[1]],
  786. {},
  787. {
  788. color,
  789. }
  790. );
  791. }
  792. }
  793. return true;
  794. };
  795. }