02-Intro-Medical-Image-Computing.ipynb 57 KB
Newer Older
Ben Glocker's avatar
Ben Glocker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial 2: Introduction to Medical Image Computing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running on Colab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install SimpleITK==1.2.2 \n",
    "! wget https://www.doc.ic.ac.uk/~bglocker/teaching/notebooks/mic-data.zip\n",
    "! unzip mic-data.zip\n",
    "\n",
    "# data directory\n",
    "data_dir = \"data/mic/\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running on DoC lab machines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# data directory\n",
    "data_dir = '/vol/lab/course/416/data/mic/'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "print(os.listdir(data_dir))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Loading a 3D medical image\n",
    "\n",
    "We will be using a library called SimpleITK to handle medical image files. It is a simplified interface around the Insight Segmentation and Registration Toolkit (ITK), one of the most popular C++ image processing libraries for medical imaging."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import SimpleITK as sitk"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use it primarily for reading and saving medical volumes encoded in NIfTI format, with the functions `sitk.ReadImage(<file_path>)` and `sitk.WriteImage(<image object>, <file_path>)`, respectively.\n",
    "\n",
    "**Task:** Try loading the image `\"ct-brain.nii.gz\"` in our data directory `data_dir`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = sitk.ReadImage(data_dir + \"ct-brain.nii.gz\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Explore image information\n",
    "\n",
    "Medical image files typically store raw volumetric data as a three-dimensional array. In addition, formats such as NIfTI and DICOM include a header containing a wealth of meta-information, such as:\n",
    "- size: number of voxels in each dimension\n",
    "- resolution/spacing: physical size of a voxel (e.g. 1mm x 1mm x 1mm)\n",
    "- data type: e.g. `int32`, `uint8`, `float64`, vectors (+ number of components)\n",
    "- scanner's origin and direction of coordinate axes\n",
    "- voxel coordinate transformation matrices\n",
    "- ... and [much more](https://brainder.org/2012/09/23/the-nifti-file-format/).\n",
    "\n",
    "**Task:** Print the SimpleITK image object to see a summary of the loaded meta-information:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Print image object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "SimpleITK also allows us to access each field directly.\n",
    "\n",
    "**Task:** Let us have a look at the size and spacing of this image, with the methods `<image>.GetSize()` and `<image>.GetSpacing()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Print image size and spacing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(img.GetSize())\n",
    "print(img.GetSpacing())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Although SimpleITK offers great functionality for manipulating the raw image data, we will often need to convert it to a NumPy array so it plays well with other Python packages, such as Matplotlib, which we will use for visualisation. This is done with the function `sitk.GetArrayFromImage(<image>)` (and vice-versa with `sitk.GetImageFromArray(<array>)`).\n",
    "\n",
    "**Task:** Convert the SimpleITK image to a NumPy array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_array = sitk.GetArrayFromImage(img) # Convert the SimpleITK image to a NumPy array\n",
    "print(img_array.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you are curious about what else SimpleITK Image class offers, [this](http://simpleitk.github.io/SimpleITK-Notebooks/01_Image_Basics.html) is a good place to look. Additionally, you can run Python's `help` command on your image object to see all the available methods."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualisation\n",
    "\n",
    "The NumPy array you obtained from SimpleITK is three-dimensional, meaning we cannot visualise it directly. Fortunately, NumPy allows you to access entire 2D slices at a time, with `img_array[<z index>,:,:]`, `img_array[:,<y index>,:]` or `img_array[:,:,<x index>]`.\n",
    "\n",
    "**Task:** Try printing a slice of your choice:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Print an image slice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(img_array[100])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, we get a large two-dimensional array filled with numbers we cannot directly interpret.\n",
    "\n",
    "To graphically display volume slices, we will use a library called Matplotlib. It is the most widely-used Python plotting library, and offers, beside more advanced functionality, a simple command-based interface, similar to Matlab's."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To display images, Matplotlib offers the function `plt.imshow(<array>)`. It has [many options](https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow),  including which colour map to use to visualise the given data (`cmap`). We will typically want to visualise medical images in greyscale (`cmap='gray'`), but feel free to play with [any of the ones available](http://matplotlib.org/examples/color/colormaps_reference.html).\n",
    "\n",
    "By default, Matplotlib will place the origin of the y-axis at the top, increasing downwards. We can reverse it with the option `origin='lower'`.\n",
    "\n",
    "**Task:** Investigate how to visualise axial (xy), coronal (xz) and sagittal (yz) slices according to the radiological convention."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display image slices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.imshow(img_array[100,:,:], cmap='gray');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you tried coronal (xz) or sagittal (yz) slices, you will have noticed that the aspect ratio was wrong: the image seems 'squashed' in one dimension. This is because the resolution of this scan is *anisotropic*, i.e. the voxels do not have the same length in all directions.\n",
    "\n",
    "`plt.imshow` has an option that lets you rescale the axes: `extent=(<left>, <right>, <bottom>, <top>)`.\n",
    "\n",
    "**Task:** Using the `GetSize` and `GetSpacing` methods discussed earlier (note that SimpleITK's indexing convention is XYZ, whereas NumPy's is ZYX), try to set the display axes to the correct scale, in millimetres."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Obtain the pysical dimensions of the image, in millimetres\n",
    "size = img.GetSize()\n",
    "spacing = img.GetSpacing()\n",
    "\n",
    "width  = size[0] * spacing[0]\n",
    "height = size[1] * spacing[1]\n",
    "depth  = size[2] * spacing[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display axial slice with the correct dimensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.imshow(img_array[100,:,:], cmap='gray', extent=(0, width, height, 0));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display coronal slice with the correct dimensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.imshow(img_array[:,180,:], origin='lower', cmap='gray', extent=(0, width, 0, depth));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display sagittal slice with the correct dimensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.imshow(img_array[:,:,150], origin='lower', cmap='gray', extent=(0, height, 0, depth));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Image statistics\n",
    "\n",
    "Since the image data is numerical, it often makes sense to look at some of its statistics. Many basic statistics are readily available in NumPy, e.g. `np.min`, `np.max`, `np.mean`, `np.std` (standard deviation), `np.percentile` etc.\n",
    "\n",
    "**Task:** Have a look at the minimum, maximum and mean values of your image array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# Print minimum, maximum and mean of image array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(np.min(img_array), np.max(img_array), np.mean(img_array))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a better idea of the distribution of intensities, it is helpful to analyse the image *histogram*. It is a simple bar plot expressing the frequencies of pixel intensity values found in the data array, in regularly-spaced intervals ('bins').\n",
    "\n",
    "**Task:** Use Matplotlib's `plt.hist` function to display the distribution of intensities in your image:\n",
    "```\n",
    "plt.hist(<array>.flatten(), bins=<no. bins>, normed=True)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot the image histogram with values for the number of bins, e.g, 32, 64, 128, 256"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(img_array.flatten(), bins=128, density=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You will notice two main peaks in the histogram with the left corresponding to values between -1000 and -500. This is the \"background\" area of the image corresponding to non-tissue or air. This area often takes a significant part of the image domain.\n",
    "\n",
    "**Task:** Try plotting the histogram again by excluding pixels from the background region, and once more plotting only values close to the second peak (in the range [-500,500]). Hint: use logical operators on the NumPy array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(img_array.flatten()[img_array.flatten() > -500], bins=256, density=True);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(img_array.flatten()[np.logical_and(img_array.flatten() > -500,img_array.flatten() < 500)], bins=256, density=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Window/Level\n",
    "\n",
    "In general, medical images have pixel intensity ranges beyond the typical 256 grayscales (8-bit) that we know from conventional digital images. The loaded CT scan, for example, has a range of about [-1000,2000].\n",
    "\n",
    "By default, `plt.imshow` will display the entire intensity range, mapping the minimum and maximum values in the array to the extremes of the colour scale. However, we can manually specify the display range, setting `clim=(<low>, <high>)` or independently `vmin=<low>` and/or `vmax=<high>`.\n",
    "\n",
    "**Task:** Using the concept of window/level, think about how to calculate parameters `clim=(<low>, <high>)` given a particular set of values for window and level. Also think about formulae for calculating the window and level that capture the full range of image intensities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Calculate parameters low and high from window and level\n",
    "def wl_to_lh(window, level):\n",
    "    low = level - window/2\n",
    "    high = level + window/2\n",
    "    return low,high\n",
    "\n",
    "print(wl_to_lh(160,70))\n",
    "print(wl_to_lh(2000,300))\n",
    "print(wl_to_lh(350,50))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Explore displaying the loaded brain CT scan `\"ct-brain.nii.gz\"` with different window/level settings. For example, using a window = 120 and level = 40 should give a good setting for displaying brain tissue. Other useful settings for CT images are a window = 2000 and level = 300 for good bone contrast, or window = 350 and level = 50 for abdominal organs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display image slices with different window/level settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "low,high = wl_to_lh(120,40)\n",
    "plt.imshow(img_array[100,:,:], cmap='gray', clim=(low, high));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Try also some of the other images provided in the data folder, such as `\"ct-abdomen.nii.gz\"` for an abdominal CT scan showing organs such as the liver or kidneys, or `\"mri-brain.nii.gz\"` for an example of a brain MRI scan. Try to find a good window/level setting for the MRI scan that shows good contrast for gray and white matter tissue (Hint: z-slice 130 shows a good cross-section through the ventricles)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Display other images with different window/level settings\n",
    "print(os.listdir(data_dir))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_mri = sitk.ReadImage(data_dir + 'mri-brain.nii.gz')\n",
    "\n",
    "low,high = wl_to_lh(300,200)\n",
    "plt.imshow(sitk.GetArrayFromImage(img_mri)[130,:,:], cmap='gray', clim=(low, high));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multiplanar Image Viewer\n",
    "\n",
    "**Task:** Now try writing a function to visualise an arbitrary medical volume, based on what you have done so far. It should take as input a SimpleITK image object (`img`), the slice indices (`x,y,z`) and window/level parameters (`window,level`), and display the specified axial (`z`), coronal (`y`) and sagittal (`x`) slices in grayscale and with correct axis dimensions and window/level contrast.\n",
    "\n",
    "Note: If (`x,y,z`) are not specified (`=None`), the function should display the centre slices. If (`window,level`) are not specified, the function should calculate the window/level setting to cover the full intensity range."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def display_image(img, x=None, y=None, z=None, window=None, level=None):\n",
    "    # Convert SimpleITK image to NumPy array\n",
    "    img_array = sitk.GetArrayFromImage(img)\n",
    "    \n",
    "    # Get image dimensions in millimetres\n",
    "    size = img.GetSize()\n",
    "    spacing = img.GetSpacing()\n",
    "    width  = size[0] * spacing[0]\n",
    "    height = size[1] * spacing[1]\n",
    "    depth  = size[2] * spacing[2]\n",
    "    \n",
    "    if x is None:\n",
    "        x = np.floor(size[0]/2).astype(int)\n",
    "    if y is None:\n",
    "        y = np.floor(size[1]/2).astype(int)\n",
    "    if z is None:\n",
    "        z = np.floor(size[2]/2).astype(int)\n",
    "    \n",
    "    if window is None:\n",
    "        window = np.max(img_array) - np.min(img_array)\n",
    "    \n",
    "    if level is None:\n",
    "        level = window / 2 + np.min(img_array)\n",
    "    \n",
    "    low,high = wl_to_lh(window,level)\n",
    "\n",
    "    # Display the orthogonal slices\n",
    "    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 4))\n",
    "\n",
    "    ax1.imshow(img_array[z,:,:], cmap='gray', clim=(low, high), extent=(0, width, height, 0))\n",
    "    ax2.imshow(img_array[:,y,:], origin='lower', cmap='gray', clim=(low, high), extent=(0, width,  0, depth))\n",
    "    ax3.imshow(img_array[:,:,x], origin='lower', cmap='gray', clim=(low, high), extent=(0, height, 0, depth))\n",
    "\n",
    "    # Additionally display crosshairs\n",
    "    ax1.axhline(y * spacing[1], lw=1)\n",
    "    ax1.axvline(x * spacing[0], lw=1)\n",
    "    \n",
    "    ax2.axhline(z * spacing[2], lw=1)\n",
    "    ax2.axvline(x * spacing[0], lw=1)\n",
    "    \n",
    "    ax3.axhline(z * spacing[2], lw=1)\n",
    "    ax3.axvline(y * spacing[1], lw=1)\n",
    "\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The code below should give you an interactive way of displaying 3D medical images based on your `display_image` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "from ipywidgets import interact, fixed\n",
    "from IPython.display import display\n",
    "\n",
    "def interactive_view(img):\n",
    "    size = img.GetSize()\n",
    "    img_array = sitk.GetArrayFromImage(img)\n",
    "    interact(display_image,img=fixed(img),\n",
    "             x=(0, size[0] - 1),\n",
    "             y=(0, size[1] - 1),\n",
    "             z=(0, size[2] - 1),\n",
    "             window=(0,np.max(img_array) - np.min(img_array)),\n",
    "             level=(np.min(img_array),np.max(img_array)));\n",
    "\n",
    "interactive_view(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Accessing voxel values\n",
    "\n",
    "In Python, we can access a single element of a sequence with an integer index (`[index]`), or we can retrieve a contiguous sub-sequence with so-called *slice notation*: `[start:stop]`. Either or both arguments can be left blank: `[start:]` (`stop` defaults to the end), `[:stop]` (`start` defaults to `0`) or `[:]` (entire sequence).\n",
    "\n",
    "A multi-dimensional array (such as our CT volume) can be indexed simultaneously in all dimensions, allowing us to access not only 2D slices, but also lines, rectangles, cuboids or individual voxels. A complete reference for NumPy array indexing can be found [here](https://docs.scipy.org/doc/numpy-1.11.0/reference/arrays.indexing.html).\n",
    "\n",
    "**Task:** Explore the indexing options for extracting 1D, 2D and 3D sub-arrays, and check the resulting shapes, e.g. `img_array[50, :, 100:120].shape`, comparing with the shape of the original array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(img_array.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Print the shape of indexed sub-arrays\n",
    "print(img_array[50, :, 100:120].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indexing is not just useful for reading data in an array, we can also set values in entire regions without having to explicitly write iterative loops.\n",
    "\n",
    "**Task:** Select any 2D slice, try setting a rectangular region to an arbitrary value and visualise the result with `plt.imshow`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Extract a 2D slice\n",
    "# Set a rectangular region to a constant (e.g. 0)\n",
    "# Visualise the result with plt.imshow\n",
    "\n",
    "img = sitk.ReadImage(data_dir + 'mri-brain.nii.gz')\n",
    "slice = sitk.GetArrayFromImage(img)[120,:,:];\n",
    "slice[100:150,50:150] = 400\n",
    "plt.imshow(slice, cmap='gray')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Image arithmetic\n",
    "\n",
    "Beside simply computing statistics, we can also perform arithmetic operations with image intensities, such as multiplication by scalars, contrast adjustment or any pointwise function (e.g. [gamma correction](https://en.wikipedia.org/wiki/Gamma_correction) also known as Power-Law Transform.\n",
    "\n",
    "**Task:** Load the image `\"mri-brain-t1-contrast.nii.gz\"` and visualise slices (`x=105, y=170, z=95`) with window/level (`window=800, level=400`) using your `display_image` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img1 = sitk.ReadImage(data_dir + 'mri-brain-t1-contrast.nii.gz')\n",
    "display_image(img1, 105, 170, 95, 800, 400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Implement a function for performing gamma correction, and apply it to the `\"mri-brain-t1-contrast.nii.gz\"` image (e.g., using (`c=10, gamma=3`)).\n",
    "\n",
    "Note, for gamma correction you should first normalise the image intensity range to [0,1], apply gamma correction, and transform back to the original range. Some operations require the image data type to be floating point (`float`). NumPy arrays can be easily converted using `astype(<dtype>)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gamma_correction(img, c, gamma):\n",
    "    img_array = sitk.GetArrayFromImage(img).astype(float)\n",
    "    min_value = np.min(img_array)\n",
    "    max_value = np.max(img_array)    \n",
    "    img_array = (img_array - min_value) / (max_value - min_value)\n",
    "    img_array = c * np.power(img_array,gamma)\n",
    "    img_array = img_array * (max_value - min_value) + min_value\n",
    "    return sitk.GetImageFromArray(img_array)    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img1_corrected = gamma_correction(img1, 10, 3)\n",
    "display_image(img1_corrected, 105, 170, 95, 800, 400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the image above, an intravenous contrast agent has been used to highlight blood and tumourous tissue. In this case, we also have a corresponding brain scan taken before the contrast agent has been administered.\n",
    "\n",
    "**Task:** Load the image `\"mri-brain-t1.nii.gz\"` and compare the two MRI scans with and without contrast using your `display_image` function. Hint: use the same window/level for both scans so you can better see the differences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img2 = sitk.ReadImage(data_dir + 'mri-brain-t1.nii.gz')\n",
    "\n",
    "display_image(img1, 105, 170, 95, 800, 400)\n",
    "display_image(img2, 105, 170, 95, 800, 400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that these two images of the same patient are registered (i.e. spatially aligned).\n",
    "\n",
    "**Task:** Now try displaying `(img1-img2)` (SimpleITK supports arithmetics with image objects) to see what was highlighted by the contrast agent. Hint: you might need to adjust the window/level for better visibility."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display the difference image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display_image(img1-img2, 105, 170, 95, 200, 100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Try the same with gamma corrected version of the contrast image. Note, you might need to convert the data type of the non-contrast image to be able to subtract it from the gamma corrected image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#  Display the difference image of the gamma corrected images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img2_corrected = gamma_correction(img2, 1, 1)\n",
    "display_image(img1_corrected-img2_corrected, 105, 170, 95, 200, 100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Intensity normalisation\n",
    "\n",
    "When performing statistical analysis or running machine learning methods on images, it is often useful to first *standardise* the intensities, i.e. make them have zero mean and unit variance. This is achieved by subtracting the mean and dividing by the standard deviation of the intensities. In mathematical terms, the standardised image $\\tilde{I}$ is computed as\n",
    "$$\\tilde{I} = \\frac{I - \\mu}{\\sigma}, \\qquad\\qquad \\mu = \\frac{1}{N} \\sum_{n=1}^N I_n, \\quad \\sigma = \\sqrt{\\frac{1}{N} \\sum_{n=1}^N (I_n - \\mu)^2},$$\n",
    "where $I$ is the original image, $N$ is its total number of voxels and $I_n$ is the intensity of voxel $n$.\n",
    "\n",
    "**Task:** Try standardising the intensities of `img1`, using `np.mean` and `np.std`, and plot the resulting histogram:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "img1_array = sitk.GetArrayFromImage(img1)  # Convert img1 to a NumPy array\n",
    "img1_array = img1_array[img1_array > 0]    # Exclude the background voxels, with intensity 0\n",
    "\n",
    "# img1_array is now an unstructured 'flat' array containing only the intensities of the brain voxels\n",
    "\n",
    "# Compute its mean and standard deviation\n",
    "# Standardise the intensity array\n",
    "# Plot the histogram before and after normalisation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(img1_array, bins=100, density=True);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist((img1_array-np.mean(img1_array)) / np.std(img1_array), bins=100, density=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Image enhancement\n",
    "\n",
    "We can also automatically enhance the contrast with [*histogram equalisation*](https://en.wikipedia.org/wiki/Histogram_equalization). It is a transformation applied to the image intensities which makes their distribution roughly uniform, i.e. all values occur approximately equally often in the image. Although it is not ideal for every application, the method is fast, simple to implement and useful for visualisation.\n",
    "\n",
    "Below we define a function, `hist_eq`, which equalises the histogram of a given array, taking as input also the desired number of histogram bins (defaults to the maximum). The resulting array will have its values distributed almost uniformly between the original minimum and maximum values. The helper function `hist_eq_img` does exactly the same but can be called directly on SimpleITK images.\n",
    "\n",
    "**Task:** Try to understand the individual steps of the implementation of `hist_eq`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hist_eq(data, nbins=None):\n",
    "    shape = data.shape\n",
    "    data_min, data_max = data.min(), data.max()\n",
    "    data = data.flatten()\n",
    "\n",
    "    # nbins defaults to the integer range of values\n",
    "    if nbins is None:\n",
    "        nbins = int(data_max - data_min)\n",
    "\n",
    "    # Compute image histogram\n",
    "    counts, bins = np.histogram(data, bins=nbins)\n",
    "    \n",
    "    # Compute cumulative distribution function (CDF)\n",
    "    cdf = counts.cumsum() / counts.sum()\n",
    "    \n",
    "    # Use linear interpolation of CDF to find new intensity values\n",
    "    data_eq = np.interp(data, bins[:-1], (data_max - data_min) * cdf + data_min)\n",
    "                    \n",
    "    return data_eq.reshape(shape)\n",
    "\n",
    "def hist_eq_img(img, nbins=None):\n",
    "    data = sitk.GetArrayFromImage(img)\n",
    "    data_eq = hist_eq(data, nbins)\n",
    "    img_eq = sitk.GetImageFromArray(data_eq)\n",
    "    img_eq.CopyInformation(img)\n",
    "    return img_eq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Now apply `hist_eq_img` to one of the SimpleITK images you have loaded and visualise it next to its original with your `display_image`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Apply histogram equalisation to an image\n",
    "# Display original image\n",
    "# Display equalised image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = sitk.ReadImage(data_dir + 'ct-brain.nii.gz')\n",
    "img_orig = img\n",
    "img_eq = hist_eq_img(img_orig)\n",
    "print(\"Before histogram equalisation:\")\n",
    "display_image(img_orig)\n",
    "print(\"After histogram equalisation:\")\n",
    "display_image(img_eq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following plots compare the intensity distributions before and after histogram equalisation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_orig = sitk.GetArrayFromImage(img_orig).flatten()\n",
    "data_eq = sitk.GetArrayFromImage(img_eq).flatten()\n",
    "\n",
    "plt.figure(figsize=(10, 4))\n",
    "plt.subplot(121)\n",
    "plt.hist(data_orig, bins=128, density=True, histtype='step', cumulative=False)\n",
    "plt.hist(data_eq, bins=128, density=True, histtype='step', cumulative=False)\n",
    "plt.subplot(122)\n",
    "plt.hist(data_orig, bins=128, density=True, histtype='step', cumulative=True)\n",
    "plt.hist(data_eq, bins=128, density=True, histtype='step', cumulative=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Filtering with SimpleITK\n",
    "\n",
    "#### Smoothing\n",
    "\n",
    "Occasionally we will acquire medical scans which include some amount of undesired noise.\n",
    "\n",
    "One such noisy image might look like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# We convert it to `float32` for compatibility with some functions we'll use later\n",
    "img = sitk.Cast(sitk.ReadImage(data_dir + 'mri-brain-noisy.nii.gz'), sitk.sitkFloat32)\n",
    "display_image(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A basic denoising technique is to *convolve* the image with a smoothing filter.\n",
    "\n",
    "We can achieve this with SimpleITK using `sitk.DiscreteGaussian(<img>)` (it has a `variance` option, default `=1.0`).\n",
    "\n",
    "**Task:** Try applying a Gaussian filter to the loaded image. Try out different values for the `variance` parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_gauss = sitk.DiscreteGaussian(img, 1)\n",
    "display_image(img_gauss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Comparing to the original noisy image, we can see that most of the visible noise is gone, but the image edges also lose their sharpness, in particular with larger values for the variance.\n",
    "\n",
    "Interestingly, Gaussian smoothing can be interpreted as *isotropic diffusion*, i.e. image intensities are 'diffused' (think heat conduction) homogeneously in all directions for a length of 'time' proportional to the variance of the Gaussian filter. Extending on this idea, another popular approach for denoising is *anisotropic diffusion*, which adjusts the local 'conductivity' based on the image gradients. In other words, it attempts to smooth out flat regions while preserving the edges.\n",
    "\n",
    "**Task:** Try out the SimpleITK function `sitk.GradientAnisotropicDiffusion(<img>)` (can take a few seconds). Play around with different values for the parameters of this filter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_diffusion = sitk.GradientAnisotropicDiffusion(img)\n",
    "display_image(img_diffusion)\n",
    "#help(sitk.GradientAnisotropicDiffusion)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's visualise all three together. Pay attention to the overall noise level and the sharpness of the edges. You might want to adjust the window/level setting for better contrast:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display_image(img, window=400, level=200)\n",
    "display_image(img_gauss, window=400, level=200)\n",
    "display_image(img_diffusion, window=400, level=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Now try the same two smoothing approaches with `'ct-brain-noisy.nii.gz'`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img2 = sitk.Cast(sitk.ReadImage(data_dir + 'ct-brain-noisy.nii.gz'), sitk.sitkFloat32)\n",
    "display_image(img2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img2_gauss = sitk.DiscreteGaussian(img2)\n",
    "display_image(img2_gauss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img2_diffusion = sitk.GradientAnisotropicDiffusion(img2)\n",
    "display_image(img2_diffusion)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Again, visualise all three (noisy, blurred and diffused) in the CT intensity range for gray/white matter (`window=120, level=40`) and compare noise levels and edge sharpness."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display_image(img2, window=120, level=40)\n",
    "display_image(img2_gauss, window=120, level=40)\n",
    "display_image(img2_diffusion, window=120, level=40)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You will notice that each method gives better results for one image but worse for the other. Why do you think that is the case?\n",
    "\n",
    "*Hint:* Think of the magnitude of the noise compared to the amplitude of the true image variations. If the signal-to-noise ratio if low, the algorithm has no way of knowing what needs to be preserved or smoothed out."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Edge detection\n",
    "\n",
    "Another common application of image filtering is estimating image gradients for edge detection.\n",
    "\n",
    "Let us compute some spatial derivatives with `sitk.Derivative(<img>, direction=<dir>)`, where `<dir>` is 0, 1 or 2 for X, Y or Z, respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_dx = sitk.Derivative(img, direction=0)\n",
    "img_dy = sitk.Derivative(img, direction=1)\n",
    "img_dz = sitk.Derivative(img, direction=2)\n",
    "display_image(img_dx, level=0)\n",
    "display_image(img_dy, level=0)\n",
    "display_image(img_dz, level=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we compute the magnitude of the gradients of an image, we obtain what is called an *edge map*, which is simply a local measure of the 'strength' of an edge.\n",
    "\n",
    "This operation is readily available in SimpleITK with `sitk.SobelEdgeDetection(<img>)`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_sobel = sitk.SobelEdgeDetection(img)\n",
    "display_image(img_sobel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note how the derivatives look quite 'grainy', as we are differentiating the superimposed noise as well.\n",
    "\n",
    "**Task**: How could you improve the edge detection on a noisy image?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We run edge detection on the smoothed image\n",
    "img_sobel2 = sitk.SobelEdgeDetection(img_gauss)\n",
    "display_image(img_sobel2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Edge sharpening\n",
    "\n",
    "**Task:** Here we implement a `sharpen()` function which applies unsharp masking to an image. It uses `sitk.DiscreteGaussian`, as above, and takes the following arguments:\n",
    "- `scale`: the standard deviation of the Gaussian filter\n",
    "- `strength`: the scaling factor for the smoothed image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sharpen(img, scale=1, strength=2):    \n",
    "    # Apply unsharp masking\n",
    "    img_smooth = sitk.DiscreteGaussian(img, scale)\n",
    "    img_sharpened = img + (img - img_smooth) * strength\n",
    "    return img_sharpened\n",
    "\n",
    "img_sharp = sharpen(img_gauss, 1, 2)\n",
    "display_image(img_gauss, window=400, level=200)\n",
    "display_image(img_sharp, window=400, level=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resampling\n",
    "\n",
    "Many image processing or computer vision algorithms adopt a multi-scale approach, for example making a coarse search over the entire image and then refining it at smaller scales. This can be achieved efficiently through the use of so-called *image pyramids*, which are formed by the base image and itself downsampled to lower resolutions, typically by a factor of 2 at each level.\n",
    "\n",
    "**Task:** Implement a naïve downsampling function, by simply taking one every `<factor>` (integer-valued) pixels in each dimension.\n",
    "\n",
    "*Hint:* SimpleITK image objects also support Python's indexing notation: `[start:stop:step]`, potentially omitting any of the arguments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def downsample_naive(img, factor=2):\n",
    "    return img[::factor, ::factor, ::factor]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let us test with the MRI volume from before:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = sitk.ReadImage(data_dir + \"mri-brain-noisy.nii.gz\")\n",
    "display_image(img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_down_naive_1 = downsample_naive(img)\n",
    "img_down_naive_2 = downsample_naive(img_down_naive_1)\n",
    "img_down_naive_3 = downsample_naive(img_down_naive_2)\n",
    "\n",
    "display_image(img)\n",
    "display_image(img_down_naive_1)\n",
    "display_image(img_down_naive_2)\n",
    "display_image(img_down_naive_3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is known that naïve undersampling can produce *aliasing*, i.e. exacerbate high spatial frequencies (edges and noise) in the downsampled image, making it look jagged and 'blocky'. We usually circumvent this issue by first smoothing the image with a low-pass filter (e.g. Gaussian) before resampling the pixel values.\n",
    "\n",
    "**Task:** Now try implementing a `downsample` method which first applies a Gaussian smoothing and then downsamples by an integer factor (no interpolation needed).\n",
    "\n",
    "*Hint:* Recall the `variance` option for `sitk.DiscreteGaussian`. A Gaussian standard deviation of `0.5*factor` works well in practice, but feel free to experiment!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def downsample(img, factor=2):\n",
    "    smoothed = sitk.DiscreteGaussian(img, (.5 * factor) ** 2)   \n",
    "    return smoothed[::factor, ::factor, ::factor]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's have a look at the results for this approach:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_down_1 = downsample(img)\n",
    "img_down_2 = downsample(img_down_1)\n",
    "img_down_3 = downsample(img_down_2)\n",
    "\n",
    "display_image(img)\n",
    "display_image(img_down_1)\n",
    "display_image(img_down_2)\n",
    "display_image(img_down_3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Resampling with SimpleITK"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "SimpleITK offers advanced resampling features that can be useful in many scenarios, e.g. when downsampling by non-integer factors or resampling to a specific resolution (e.g. isotropic).\n",
    "\n",
    "Have a look at the `resample()` function we have implemented below and try to understand the role of each of the arguments to the `sitk.ResampleImageFilter`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def resample(img, new_size=None, new_spacing=None):\n",
    "    old_size = img.GetSize()\n",
    "    old_spacing = img.GetSpacing()\n",
    "    \n",
    "    if new_size is None and new_spacing is None:\n",
    "        return img\n",
    "    \n",
    "    if new_size is None:\n",
    "        # Compute new image dimensions based on the desired rescaling of the voxel spacing\n",
    "        new_size = [int(np.ceil(old_size[d] * old_spacing[d] / new_spacing[d])) for d in range(3)]\n",
    "\n",
    "    if new_spacing is None:\n",
    "        # Compute new voxel spacing based on the desired rescaling of the image dimensions\n",
    "        new_spacing = [old_spacing[d] * old_size[d] / new_size[d] for d in range(3)]\n",
    "\n",
    "    # Smooth the input image with anisotropic Gaussian filter\n",
    "    img_smoothed = img\n",
    "    for d in range(3):\n",
    "        # Note how the blurring strength can be different in each direction,\n",
    "        # if the scaling factors are different.\n",
    "        factor = new_spacing[d] / old_spacing[d]\n",
    "        sigma = 0.2 * factor\n",
    "        img_smoothed = sitk.RecursiveGaussian(img_smoothed, sigma=sigma, direction=d)\n",
    "\n",
    "    # Finally, apply the resampling operation\n",
    "    img_resampled = sitk.ResampleImageFilter().Execute(\n",
    "        img_smoothed,        # Input image\n",
    "        new_size,            # Output image dimensions\n",
    "        sitk.Transform(),    # Coordinate transformation. sitk.Transform() is a dummy identity transform,\n",
    "                             # as we want the brain to be in exactly the same place. When we do image registration,\n",
    "                             # for example, this can be a linear or nonlinear transformation.\n",
    "        sitk.sitkLinear,     # Interpolation method (cf. also sitk.sitkNearestNeighbor and many others)\n",
    "        img.GetOrigin(),     # Output image origin (same)\n",
    "        new_spacing,         # Output voxel spacing\n",
    "        img.GetDirection(),  # Output image orientation (same)\n",
    "        0,                   # Fill value for points outside the input domain\n",
    "        img.GetPixelID())    # Voxel data type (same)\n",
    "\n",
    "    return img_resampled"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's resample the MR image to an element spacing of 2x4x8mm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_resampled = resample(img, new_spacing=[2, 4, 8])\n",
    "\n",
    "print(\"Spacing: {}\".format(img.GetSpacing()))\n",
    "display_image(img, window=400, level=200)\n",
    "\n",
    "print(\"Spacing: {}\".format(img_resampled.GetSpacing()))\n",
    "display_image(img_resampled, window=400, level=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Medical imaging data is often anisotropic. For many image analysis algorithms, however, it is easier to work with isotropic input data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img3 = sitk.ReadImage(data_dir + 'mri-brain-anisotropic.nii.gz')\n",
    "display_image(img3, z=10, window=800, level=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Task:** Try resampling the above image to an isotropic 1mm resolution, and display the result showing approximately the same xy-plane by setting an appropriate value for the `z` parameter in the `display_image` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img3_resampled = resample(img3, new_spacing=[1, 1, 1])\n",
    "\n",
    "print(\"Spacing: {}\".format(img3.GetSpacing()))\n",
    "display_image(img3, z=10, window=800, level=400)\n",
    "\n",
    "print(\"Spacing: {}\".format(img3_resampled.GetSpacing()))\n",
    "display_image(img3_resampled, z=50, window=800, level=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segmentation\n",
    "\n",
    "First let us define some helper functions to overlay an image with a segmentation, for good visualisation. `display_overlay()` takes as input the base image, a segmentation image (binary) and all the usual arguments for `display_image()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def label_overlay(img, seg):\n",
    "    minmax = sitk.MinimumMaximumImageFilter()\n",
    "    minmax.Execute(img)\n",
    "    low, high = minmax.GetMinimum(), minmax.GetMaximum()\n",
    "    img_norm = (img - low) / (high - low)\n",
    "    img_uint8 = sitk.Cast(256 * img_norm, sitk.sitkUInt8)\n",
    "    return sitk.LabelOverlay(img_uint8, seg)\n",
    "\n",
    "def display_overlay(img, seg, *args, **kwargs):\n",
    "    display_image(label_overlay(img, seg), *args, **kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "#### Thresholding\n",
    "\n",
    "The simplest form of segmentation is just based on a single cutoff in the intensities, with a manually specified threshold. Alternatively, we can specify an upper (U) and a lower (L) thresholds.\n",
    "\n",
    "**Task:** Try to find a good UL thresholding to segment the lesion in the noisy CT scan.\n",
    "\n",
    "*Hint 1:* SimpleITK images support comparison (`<`, `>`, `<=`, `>=`, `==`, `!=`) and logical ('and' `&`, 'or' `|`, 'xor' `^`, 'not' `~`) operators to produce binary images.\n",
    "\n",
    "*Hint 2:* Image noise causes major problems for thresholding approaches. Try removing noise before thresholding the image and compare the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = sitk.ReadImage(data_dir + 'ct-brain-noisy.nii.gz')\n",
    "display_image(img, x=70, y=100, z=90, window=120, level=40)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "seg = (img > 50) & (img < 100)\n",
    "display_overlay(img, seg, x=70, y=100, z=90)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_gauss = sitk.DiscreteGaussian(img)\n",
    "seg = (img_gauss > 50) & (img_gauss < 100)\n",
    "display_overlay(img_gauss, seg, x=70, y=100, z=90)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we can observe one of the main shortcomings of purely intensity-based segmentation methods: we have no control over the location or spatial contiguity of the segmented regions. So even if we manage to segment most of the lesion, there are lot of areas included with the same intensity range outside the structure of interest."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Region growing\n",
    "\n",
    "Region growing offers an alternative to simple thresholding that addresses the issue of spatial contiguity: it only labels the voxels which are *reachable* from a set of manually-specified *seed points*. In its simplest form, it is equivalent to thresholding, but limited to regions connected to the seeds.\n",
    "\n",
    "**Task:** Implement region growing with UL thresholding.\n",
    "\n",
    "*Hints:*\n",
    "- To initialise your zero-filled segmentation image, use `sitk.Image(<img>.GetSize(), sitk.sitkUInt8)`. Don't forget to also call `<seg>.CopyInformation(<img>)` to copy the meta-data (spacing, origin, orientation) from the input image.\n",
    "- You can use Python's `collections.deque` (double-ended queue). Use `.append(<elem>)` or `.extend(<list>)` to enqueue elements and `.popleft()` to dequeue an element (`.pop()` would work as a stack instead).\n",
    "- Your algorithm should remember which voxels have already been visited. This can be achieved with a Python set (`set()`), with which you can do `.add(<elem>)` and `if <elem> in <set>:`.\n",
    "- Use tuples to represent the voxel locations (e.g. `point=(x,y,z)`), then you can index directly into the SimpleITK image with them (e.g. `image[point]`).\n",
    "- `neighbours(<point>, <img_size>)` returns the list of immediate neighbours of `<point>`, clipped at the image borders."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def neighbours(x, size):\n",
    "    nbs = []\n",
    "    for d in range(len(x)):\n",
    "        if x[d] > 0:\n",
    "            nb = list(x)\n",
    "            nb[d] -= 1\n",
    "            nbs.append(tuple(nb))\n",
    "        if x[d] < size[d] - 1:\n",
    "            nb = list(x)\n",
    "            nb[d] += 1\n",
    "            nbs.append(tuple(nb))\n",
    "    return nbs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "\n",
    "def region_growing(img, seeds, low, high):\n",
    "    size = img.GetSize()\n",
    "    seg = sitk.Image(size, sitk.sitkUInt8)\n",
    "    queue = deque()\n",
    "    queue.extend(seeds)\n",
    "    visited = set()\n",
    "    while len(queue) > 0:\n",
    "        x = queue.popleft()\n",
    "        if x in visited:\n",
    "            continue\n",
    "        visited.add(x)\n",
    "        if low <= img[x] < high:\n",
    "            seg[x] = 1\n",
    "            queue.extend(neighbours(x, size))\n",
    "    seg.CopyInformation(img)\n",
    "    return seg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display_image(img_gauss, x=70, y=100, z=90, window=120, level=40)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "seed = (70, 100, 90)\n",
    "low, high = 50, 100\n",
    "seg2 = region_growing(img_gauss, [seed], low, high)\n",
    "display_overlay(img_gauss, seg2, *seed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's visually compare the results to a manual reference segmentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ref = sitk.ReadImage(data_dir + 'ct-brain-lesion.nii.gz')\n",
    "\n",
    "print(\"Thresholding\")\n",
    "display_image(label_overlay(img_gauss, seg), *seed)\n",
    "print(\"Region growing\")\n",
    "display_image(label_overlay(img_gauss, seg2), *seed)\n",
    "print(\"Reference segmentation\")\n",
    "display_image(label_overlay(img_gauss, ref), *seed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Segmentation Evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's now quantitatively evaluate the segmentations using different performance measures. SimpleITK has many important measures already implemented.\n",
    "\n",
    "First, we extract the surfaces from the segmentations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "seg_contour = sitk.LabelContour(seg)\n",
    "seg2_contour = sitk.LabelContour(seg2)\n",
    "ref_contour = sitk.LabelContour(ref)\n",
    "\n",
    "print(\"Thresholding - Surface\")\n",
    "display_image(label_overlay(img_gauss, seg_contour), *seed)\n",
    "print(\"Region growing - Surface\")\n",
    "display_image(label_overlay(img_gauss, seg2_contour), *seed)\n",
    "print(\"Reference segmentation - Surface\")\n",
    "display_image(label_overlay(img_gauss, ref_contour), *seed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we can use SimpleITK to compute overlap measures such as Jaccard Index (JI) and Dice Similarity Coefficient (DSC). We can also directly compute the Hausdorff Distance (HD) and Symmetric Average Surface Distance (ASD) from the segmentation contours using SimpleITK's `HausdorffDistanceImageFilter`. (Note, ASD is called AverageHausdorffDistance in SimpleITK)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "overlap_measures_filter = sitk.LabelOverlapMeasuresImageFilter()\n",
    "hausdorff_distance_filter = sitk.HausdorffDistanceImageFilter()\n",
    "\n",
    "overlap_measures_filter.Execute(ref, seg)\n",
    "hausdorff_distance_filter.Execute(ref_contour, seg_contour)\n",
    "print('\\nThresholding')\n",
    "print('JI\\t' + str(overlap_measures_filter.GetJaccardCoefficient()))\n",
    "print('DSC\\t' + str(overlap_measures_filter.GetDiceCoefficient()))\n",
    "print('HD\\t' + str(hausdorff_distance_filter.GetHausdorffDistance()))\n",
    "print('ASD\\t' + str(hausdorff_distance_filter.GetAverageHausdorffDistance()))\n",
    "\n",
    "overlap_measures_filter.Execute(ref, seg2)\n",
    "hausdorff_distance_filter.Execute(ref_contour, seg2_contour)\n",
    "print('\\nRegion growing')\n",
    "print('JI\\t' + str(overlap_measures_filter.GetJaccardCoefficient()))\n",
    "print('DSC\\t' + str(overlap_measures_filter.GetDiceCoefficient()))\n",
    "print('HD\\t' + str(hausdorff_distance_filter.GetHausdorffDistance()))\n",
    "print('ASD\\t' + str(hausdorff_distance_filter.GetAverageHausdorffDistance()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}