Ejemplo n.º 1
0
def test_make_correspondence():
    import hasi.align

    # Load meshes
    atlas_mesh = itk.meshread(OUTPUT_DIRECTORY + MESH_DIRECTORY + 'atlas.vtk')

    meshes = list()
    for idx in range(len(IMAGE_FILES)):
        mesh_file = IMAGE_FILES[idx].replace('.nrrd', '.vtk')
        meshes.append(
            itk.meshread(OUTPUT_DIRECTORY + MESH_DIRECTORY + mesh_file, itk.F))

    # Get mesh correspondence
    for idx in range(len(meshes)):
        mesh = meshes[idx]
        registered_atlas = hasi.align.register_template_to_sample(
            template_mesh=atlas_mesh, sample_mesh=mesh, max_iterations=500)
        mesh = hasi.align.resample_template_from_target(
            template_mesh=registered_atlas, target_mesh=mesh)
        meshes[idx] = mesh

    # Write out for shape analysis
    for idx in range(len(IMAGE_FILES)):
        mesh = meshes[idx]
        mesh_file = IMAGE_FILES[idx].replace('.nrrd', '.vtk')
        itk.meshwrite(mesh,
                      OUTPUT_DIRECTORY + CORRESPONDENCE_DIRECTORY + mesh_file)
Ejemplo n.º 2
0
def test_mesh():
    data = Path(__file__).absolute().parent / "input" / "cow.vtk"
    itk_mesh = itk.meshread(data)

    itk_mesh_dict = itk.dict_from_mesh(itk_mesh)
    # Bug, to be fixed by 5.3.0
    itk_mesh_dict.pop('dimension', None)
    itkwasm_mesh = Mesh(**itk_mesh_dict)
    itkwasm_mesh_dict = asdict(itkwasm_mesh)
    itk_mesh_roundtrip = itk.mesh_from_dict(itkwasm_mesh_dict)
    itk_mesh_roundtrip_dict = itk.dict_from_mesh(itk_mesh_roundtrip)

    meshType = itk_mesh_dict["meshType"]
    meshType_roundtrip = itk_mesh_roundtrip_dict["meshType"]
    assert meshType["dimension"] == meshType_roundtrip["dimension"]

    assert meshType["pointComponentType"] == meshType_roundtrip[
        "pointComponentType"]
    assert meshType["pointPixelComponentType"] == meshType_roundtrip[
        "pointPixelComponentType"]
    assert meshType["pointPixelType"] == meshType_roundtrip["pointPixelType"]
    assert meshType["pointPixelComponents"] == meshType_roundtrip[
        "pointPixelComponents"]

    assert meshType["cellComponentType"] == meshType_roundtrip[
        "cellComponentType"]
    assert meshType["cellPixelComponentType"] == meshType_roundtrip[
        "cellPixelComponentType"]
    assert meshType["cellPixelType"] == meshType_roundtrip["cellPixelType"]
    assert meshType["cellPixelComponents"] == meshType_roundtrip[
        "cellPixelComponents"]

    assert itk_mesh_dict["name"] == itk_mesh_roundtrip_dict["name"]

    assert itk_mesh_dict["numberOfPoints"] == itk_mesh_roundtrip_dict[
        "numberOfPoints"]
    assert np.array_equal(itk_mesh_dict["points"],
                          itk_mesh_roundtrip_dict["points"])

    assert itk_mesh_dict["numberOfPointPixels"] == itk_mesh_roundtrip_dict[
        "numberOfPointPixels"]
    assert np.array_equal(itk_mesh_dict["pointData"],
                          itk_mesh_roundtrip_dict["pointData"])

    assert itk_mesh_dict["numberOfCells"] == itk_mesh_roundtrip_dict[
        "numberOfCells"]
    assert np.array_equal(itk_mesh_dict["cells"],
                          itk_mesh_roundtrip_dict["cells"])
    assert itk_mesh_dict["cellBufferSize"] == itk_mesh_roundtrip_dict[
        "cellBufferSize"]

    assert itk_mesh_dict["numberOfCellPixels"] == itk_mesh_roundtrip_dict[
        "numberOfCellPixels"]
    assert np.array_equal(itk_mesh_dict["cellData"],
                          itk_mesh_roundtrip_dict["cellData"])
Ejemplo n.º 3
0
def test_shape_analysis():
    import numpy as np
    import sklearn.model_selection
    from dwd.dwd import DWD
    import hasi.classify

    # Load correspondence meshes
    meshes = list()
    for idx in range(len(IMAGE_FILES)):
        mesh_file = IMAGE_FILES[idx].replace('.nrrd', '.vtk')
        meshes.append(
            itk.meshread(
                OUTPUT_DIRECTORY + CORRESPONDENCE_DIRECTORY + mesh_file,
                itk.F))

    # Prepare data
    STEP_SIZE = 10
    TRAIN_SIZE = 0.6
    features = hasi.classify.make_point_features(meshes, step=STEP_SIZE)

    # For labels we will try to distinguish a given mesh from the others
    # based only on shape features
    labels = np.array([('902' in image_file) for image_file in IMAGE_FILES])

    #X_train, X_test, y_train, y_test = \
    #    sklearn.model_selection.train_test_split(features,labels,TRAIN_SIZE=0.6)

    # Train classifier
    # (For integration test we simply train on the population)
    classifier = DWD(C='auto')
    classifier.fit(features, np.squeeze(labels))

    # Predict labels, expecting 100% correct
    predictions = classifier.predict(features)
    correct = np.squeeze(predictions) == labels
    assert sum(correct) == len(labels)

    # Predict distances
    distances = hasi.classify.get_distances(classifier, features)
    assert all(10 < abs(distance) < 20 for distance in distances)
Ejemplo n.º 4
0
def test_meansquares_registration():
    MESH_OUTPUT = 'test/Output/testMeanSquaresRegisterOutput.vtk'

    # Class is imported
    from hasi.meansquaresregistrar import MeanSquaresRegistrar

    # Class is instantiable
    registrar = MeanSquaresRegistrar()

    # Registration executes
    (transform, mesh3) = registrar.register(mesh1,mesh2,filepath=MESH_OUTPUT)

    # Mesh was generated
    assert(type(mesh3) == type(mesh1))

    # Optimization converged
    assert(registrar.optimizer.GetCurrentMetricValue() <
            MEANSQUARES_METRIC_MAXIMUM_THRESHOLD)
  
    # Optimization did not exceed allowable iterations
    assert(registrar.optimizer.GetCurrentIteration() <= MAX_ITERATIONS)

    # Transform was output
    assert(type(transform) == registrar.TransformType)

    # Mesh was output
    assert(os.path.isfile(MESH_OUTPUT))

    # File output matches mesh
    fileMesh3 = itk.meshread(MESH_OUTPUT)
    assert(fileMesh3.GetNumberOfPoints() == mesh3.GetNumberOfPoints())
    assert(all(mesh3.GetPoint(i) == fileMesh3.GetPoint(i)
                for i in range(0,mesh3.GetNumberOfPoints())))

    # Clean up
    os.remove(MESH_OUTPUT)
Ejemplo n.º 5
0
assert type(image) == itk.Image[itk.F, 2]
image = itk.imread(filename, itk.F, fallback_only=True)
assert type(image) == itk.Image[itk.RGBPixel[itk.UC], 2]
try:
    image = itk.imread(filename, fallback_only=True)
    # Should never reach this point if test passes since an exception
    # is expected.
    raise Exception("`itk.imread()` fallback_only should have failed")
except Exception as e:
    if str(e) == "pixel_type must be set when using the fallback_only option":
        pass
    else:
        raise e

# test mesh read / write
mesh = itk.meshread(mesh_filename)
assert type(mesh) == itk.Mesh[itk.F, 3]
mesh = itk.meshread(mesh_filename, itk.UC)
assert type(mesh) == itk.Mesh[itk.UC, 3]
mesh = itk.meshread(mesh_filename, itk.UC, fallback_only=True)
assert type(mesh) == itk.Mesh[itk.F, 3]

itk.meshwrite(mesh, sys.argv[4])
itk.meshwrite(mesh, sys.argv[4], compression=True)

# test search
res = itk.search("Index")
assert res[0] == "Index"
assert res[1] == "index"
assert "ContinuousIndex" in res
Ejemplo n.º 6
0
    url = 'https://data.kitware.com/api/v1/file/608b006d2fa25629b970f139/download'
    urlretrieve(url, TEMPLATE_MESH_FILE)

if not os.path.exists(TARGET_MESH_FILE):
    url = 'https://data.kitware.com/api/v1/file/5f9daaba50a41e3d1924dae9/download'
    urlretrieve(url, TARGET_MESH_FILE)

if not os.path.exists(TARGET_HEALTHY_IMAGE_FILE):
    url = 'https://data.kitware.com/api/v1/file/5eea20bd9014a6d84ec75df1/download'
    urlretrieve(url, TARGET_HEALTHY_IMAGE_FILE)

if not os.path.exists(TARGET_UNHEALTHY_IMAGE_FILE):
    url = 'https://data.kitware.com/api/v1/file/5eea20bb9014a6d84ec75de5/download'
    urlretrieve(url, TARGET_UNHEALTHY_IMAGE_FILE)

template_mesh = itk.meshread(TEMPLATE_MESH_FILE, itk.F)
target_mesh = itk.meshread(TARGET_MESH_FILE, itk.F)
target_healthy_image = itk.imread(TARGET_HEALTHY_IMAGE_FILE)
target_unhealthy_image = itk.imread(TARGET_UNHEALTHY_IMAGE_FILE)

mesh_pixel_type, dimension = itk.template(template_mesh)[1]


def test_hasi_import():
    # Import succeeds
    from hasi import align


def test_mesh_to_image():
    # Import succeeds
    from hasi.align import mesh_to_image
Ejemplo n.º 7
0
os.makedirs('test', exist_ok=True)
os.makedirs('test/Input', exist_ok=True)
os.makedirs('test/Output', exist_ok=True)

if not os.path.exists(FIXED_MESH_FILE):
    url = 'https://data.kitware.com/api/v1/file/5f9daaae50a41e3d1924dae1/download'
    urlretrieve(url, FIXED_MESH_FILE)
    
if not os.path.exists(MOVING_MESH_FILE):
    url = 'https://data.kitware.com/api/v1/file/5f9daaae50a41e3d1924dae1/download'
    urlretrieve(url, MOVING_MESH_FILE)

os.makedirs('test/Output', exist_ok=True)

mesh1 = itk.meshread(FIXED_MESH_FILE)
mesh2 = itk.meshread(MOVING_MESH_FILE)

# Test base class import and functions
def test_mesh_to_image():
    # Class is imported
    from hasi.meshtomeshregistrar import MeshToMeshRegistrar

    # Class is instantiable
    registrar = MeshToMeshRegistrar()

    # Initialize runs without error
    registrar.initialize()

    # Mesh-to-image executes without error
    img1 = registrar.mesh_to_image(mesh1)