Exemple #1
0
def rois_additional(idx, outdir=os.path.join("scoring","rois","additional")):
    images = [
        ("JHU", 24),
        ("JHU", 25),
        ("JHU", 26),
        ("JHU", 27),
        ("JHU", 28),
        ("JHU", 29),
        ("JHU", 30),
        ("JHU", 31),
        ("JHU", 32),
        ("JHU", 33),
        ("JHU", 34),
    ]
    data_source, acq = images[idx]
    P, xl, zl = load_data(data_source, acq)

    # Define pixel grid limits (assume y == 0)
    wvln = P.c / P.fc
    dx = wvln / 3
    dz = dx  # Use square pixels
    desired_grid = [400, 300]
    xlims = np.array([-0.5, 0.5]) * (desired_grid[1] - 1) * dx + (xl[0] + xl[1]) / 2
    zlims = np.array([-0.5, 0.5]) * (desired_grid[0] - 1) * dz + (zl[0] + zl[1]) / 2
    xlims = [np.maximum(xlims[0], xl[0]), np.minimum(xlims[1], xl[1])]
    zlims = [np.maximum(zlims[0], zl[0]), np.minimum(zlims[1], zl[1])]
    grid = make_pixel_grid(xlims, zlims, dx, dz)
    fnum = 1

    # Normalize input to [-1, 1] range
    maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
    P.idata /= maxval
    P.qdata /= maxval

    # Make data torch tensors
    x = (P.idata, P.qdata)

    # Make 75-angle image
    dasN = DAS_PW(P, grid, rxfnum=fnum)
    idasN, qdasN = dasN(x)
    idasN, qdasN = idasN.detach().cpu().numpy(), qdasN.detach().cpu().numpy()
    iqN = idasN + 1j * qdasN
    ground_truth = np.abs(iqN)
    ground_truth /= np.amax(ground_truth)

    # Normalize to have RMS = 1
    # ground_truth /= np.sqrt(np.mean(ground_truth ** 2))

    # Display images via matplotlib
    xext = (np.array([-0.5, grid.shape[1] - 0.5]) * dx + xlims[0]) * 1e3
    zext = (np.array([-0.5, grid.shape[0] - 0.5]) * dz + zlims[0]) * 1e3
    extent = [xext[0], xext[1], zext[1], zext[0]]
    plt.clf()
    bimgN = 20 * np.log10(ground_truth)  # Log-compress
    bimgN -= np.amax(bimgN)  # Normalize by max value
    plt.imshow(bimgN, vmin=-60, cmap="gray", extent=extent, origin="upper")
    plt.suptitle("%s%03d (c = %d m/s)" % (data_source, acq, np.round(P.c)))
    # Check to make sure save directory exists, if not, create it
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir,"roi%02d.png" % (idx)))

    # Save
    mdict = {
        "grid": grid,
        "data_source": data_source,
        "acq": acq,
        "extent": extent,
        "ground_truth": ground_truth,
    }
    hdf5storage.savemat(os.path.join(outdir,"roi%02d" % (idx)), mdict)
Exemple #2
0
def rois_lesion(idx, outdir=os.path.join("scoring", "rois", "lesion")):
    if idx == 0:
        data_source, acq = "UFL", 1
        xctr, zctr, r0, r1 = -0.8e-3, 30.3e-3, 2.8e-3, 4.5e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 1:
        data_source, acq = "UFL", 5
        xctr, zctr, r0, r1 = 0.2e-3, 16.4e-3, 2.2e-3, 3.5e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 2:
        data_source, acq = "UFL", 5
        xctr, zctr, r0, r1 = -0.5e-3, 45e-3, 2.2e-3, 3.5e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 3:
        data_source, acq = "OSL", 7
        xctr, zctr, r0, r1 = -8.2e-3, 39.1e-3, 2.5e-3, 4.5e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 4:
        data_source, acq = "MYO", 1
        xctr, zctr, r0, r1 = 15.5e-3, 16.5e-3, 1.3e-3, 3e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 5:
        data_source, acq = "MYO", 4
        xctr, zctr, r0, r1 = 12.2e-3, 25.8e-3, 1.3e-3, 3e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 6:
        data_source, acq = "INS", 8
        xctr, zctr, r0, r1 = 11.4e-3, 42.3e-3, 2.8e-3, 4.5e-3
        P, _, _ = load_data(data_source, acq)
    elif idx == 7:
        data_source, acq = "INS", 21
        xctr, zctr, r0, r1 = -7e-3, 41.2e-3, 2.8e-3, 4.5e-3
        P, _, _ = load_data(data_source, acq)
    else:
        raise NotImplementedError

    xlims = [-6e-3 + xctr, 6e-3 + xctr]
    zlims = [-6e-3 + zctr, 6e-3 + zctr]
    r2 = np.sqrt(r0**2 + r1**2)

    # Define pixel grid limits (assume y == 0)
    wvln = P.c / P.fc
    dx = wvln / 3
    dz = dx  # Use square pixels
    grid = make_pixel_grid(xlims, zlims, dx, dz)
    fnum = 1

    # Normalize input to [-1, 1] range
    maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
    P.idata /= maxval
    P.qdata /= maxval

    # Make ROI
    dist = np.sqrt((grid[:, :, 0] - xctr)**2 + (grid[:, :, 2] - zctr)**2)
    roi_i = dist <= r0
    roi_o = (r1 <= dist) * (dist <= r2)

    # Make data torch tensors
    x = (P.idata, P.qdata)

    # Make 75-angle image
    dasN = DAS_PW(P, grid, rxfnum=fnum)
    idasN, qdasN = dasN(x)
    idasN, qdasN = idasN.detach().cpu().numpy(), qdasN.detach().cpu().numpy()
    iqN = idasN + 1j * qdasN
    bimgN = 20 * np.log10(np.abs(iqN))  # Log-compress
    bimgN -= np.amax(bimgN)  # Normalize by max value

    # Display images via matplotlib
    xext = (np.array([-0.5, grid.shape[1] - 0.5]) * dx + xlims[0]) * 1e3
    zext = (np.array([-0.5, grid.shape[0] - 0.5]) * dz + zlims[0]) * 1e3
    extent = [xext[0], xext[1], zext[1], zext[0]]
    plt.clf()
    opts = {"extent": extent, "origin": "upper"}
    plt.imshow(bimgN, vmin=-40, cmap="gray", **opts)
    plt.contour(roi_i, [0.5], colors="c", **opts)
    plt.contour(roi_o, [0.5], colors="m", **opts)
    plt.suptitle("%s%03d (c = %d m/s)" % (data_source, acq, np.round(P.c)))
    # Check to make sure save directory exists, if not, create it
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir, "roi%02d.png" % (idx)))

    # Save ROI locations
    xgrid = grid[:, :, 0]
    ygrid = grid[:, :, 1]
    zgrid = grid[:, :, 2]
    grid_i = np.stack([xgrid[roi_i], ygrid[roi_i], zgrid[roi_i]], axis=1)
    grid_o = np.stack([xgrid[roi_o], ygrid[roi_o], zgrid[roi_o]], axis=1)
    grid_i = np.expand_dims(grid_i, 1)
    grid_o = np.expand_dims(grid_o, 1)
    mdict = {
        "grid": grid,
        "grid_i": grid_i,
        "grid_o": grid_o,
        "data_source": data_source,
        "acq": acq,
        "xctr": xctr,
        "zctr": zctr,
        "r0": r0,
        "r1": r1,
        "r2": r2,
        "extent": extent,
        "roi_i": roi_i,
        "roi_o": roi_o,
    }
    hdf5storage.savemat(os.path.join(outdir, "roi%02d" % (idx)), mdict)
Exemple #3
0
def measure_speckle(beamformer, moniker, center_angle=False, verbose=True):
    snrs = []
    bimgs = []
    for idx in range(nrois):
        torch.cuda.empty_cache()
        # Load ROI information
        mdict = hdf5storage.loadmat(
            os.path.join("scoring", "rois", "speckle", "roi%02d.mat" % idx))
        data_source = mdict["data_source"]
        acq = mdict["acq"]
        img_grid = mdict["grid"]
        extent = mdict["extent"]

        # Load plane wave channel data
        P, _, _ = load_data(data_source, acq)
        if center_angle:
            # Grab only the center angle's worth of data
            aidx = len(P.angles) // 2
            P.idata = P.idata[[aidx]]
            P.qdata = P.qdata[[aidx]]
            P.angles = P.angles[[aidx]]
            P.time_zero = P.time_zero[[aidx]]

        # Normalize input to [-1, 1] range
        maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
        P.idata /= maxval
        P.qdata /= maxval

        # Beamform the ROI
        bimg = beamformer(P, img_grid)
        bimgs.append(bimg)

        # Compute statistics
        snrs.append(snr(bimg))

        if verbose:
            print("roi%02d SNR: %f" % (idx, snrs[idx]))

    hdf5storage.savemat(os.path.join("results", moniker, "speckle"), {
        "snrs": snrs,
        "bimgs": bimgs
    })

    plt.figure(figsize=[10, 6])
    for idx in range(nrois):
        # Display images via matplotlib
        plt.subplot(2, 3, idx + 1)
        plt.imshow(
            20 * np.log10(bimgs[idx]),
            vmin=-40,
            cmap="gray",
            extent=extent,
            origin="upper",
        )

    plt.suptitle("%s: Speckle Targets" % moniker)
    plt.pause(0.01)
    outdir = os.path.join("results", moniker)
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir, "speckle.jpg"))
Exemple #4
0
import torch
import matplotlib.pyplot as plt
import numpy as np
from cubdl.das_torch import DAS_PW
from datasets.PWDataLoaders import load_data, get_filelist
from cubdl.PixelGrid import make_pixel_grid

device = torch.device("cuda:0")
# Find all the CUBDL Task 1 Data
# Optional other data subsets:
#   "all", "phantom", "invivo", "postcubdl", "simulation", "task1"
filelist = get_filelist(data_type="task1")

for data_source in filelist:
    for acq in filelist[data_source]:
        P, xlims, zlims = load_data(data_source, acq)

        # Define pixel grid limits (assume y == 0)
        wvln = P.c / P.fc
        dx = wvln / 2.5
        dz = dx  # Use square pixels
        grid = make_pixel_grid(xlims, zlims, dx, dz)
        fnum = 1

        # Make data torch tensors
        x = (P.idata, P.qdata)

        # Make 75-angle image
        dasN = DAS_PW(P, grid, rxfnum=fnum)
        idasN, qdasN = dasN(x)
        idasN, qdasN = idasN.detach().cpu().numpy(), qdasN.detach().cpu(
Exemple #5
0
def measure_image(beamformer, moniker, center_angle=False, verbose=True):
    nrois = 12
    l1_lins, l2_lins, l1_logs, l2_logs, = [], [], [], []
    psnrs, nccs, bimgs, exts = [], [], [], []
    for idx in range(nrois):
        torch.cuda.empty_cache()
        # Load ROI information
        mdict = hdf5storage.loadmat(os.path.join("scoring","rois","image","roi%02d.mat" % idx))
        data_source = mdict["data_source"]
        acq = mdict["acq"]
        img_grid = mdict["grid"]
        extent = mdict["extent"]
        yimg = mdict["ground_truth"]
        exts.append(extent)

        # Load plane wave channel data
        P, _, _ = load_data(data_source, acq)
        if center_angle:
            # Grab only the center angle's worth of data
            aidx = len(P.angles) // 2
            P.idata = P.idata[[aidx]]
            P.qdata = P.qdata[[aidx]]
            P.angles = P.angles[[aidx]]
            P.time_zero = P.time_zero[[aidx]]

        # Normalize input to [-1, 1] range
        maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
        P.idata /= maxval
        P.qdata /= maxval

        # Beamform the ROI
        bimg = beamformer(P, img_grid)

        # Statistics will only be computed using image values within -40dB of max value
        mask = (20 * np.log10(yimg / np.amax(yimg))) >= -40
        mask2 = (20 * np.log10(bimg / np.amax(bimg))) < -40
        bimg[mask & mask2] = 10 ** (-40 / 20) * np.amax(bimg)

        # Find L1, L2 optimal image scaling factors
        bimg_l1 = bimg * wopt_mae(yimg[mask], bimg[mask])
        bimg_l2 = bimg * wopt_mse(yimg[mask], bimg[mask])
        bimgs.append(bimg_l2)

        # Compute statistics
        l1_lins.append(l1loss(yimg[mask], bimg_l1[mask]))
        l2_lins.append(l2loss(yimg[mask], bimg_l2[mask]))
        l1_logs.append(l1loss(np.log(yimg[mask]), np.log(bimg_l1[mask])))
        l2_logs.append(l2loss(np.log(yimg[mask]), np.log(bimg_l2[mask])))
        psnrs.append(psnr(yimg[mask], bimg_l2[mask]))
        nccs.append(ncc(yimg[mask], bimg[mask]))

        if verbose:
            print("roi%02d L1 lin: %f" % (idx, l1_lins[idx]))
            print("roi%02d L1 log: %f" % (idx, l1_logs[idx]))
            print("roi%02d L2 lin: %f" % (idx, l2_lins[idx]))
            print("roi%02d L2 log: %f" % (idx, l2_logs[idx]))
            print("roi%02d PSNR:   %f" % (idx, psnrs[idx]))
            print("roi%02d NCC:    %f" % (idx, nccs[idx]))

    hdf5storage.savemat(
        os.path.join("results", moniker, "image"),
        {
            "l1_lins": l1_lins,
            "l1_logs": l1_logs,
            "l2_lins": l2_lins,
            "l2_logs": l2_logs,
            "psnrs": psnrs,
            "nccs": nccs,
            "bimgs": bimgs,
            "mask": mask,
        },
    )

    plt.figure(figsize=[10, 6])
    for idx in range(nrois):
        # Display images via matplotlib
        plt.subplot(3, 4, idx + 1)
        plt.imshow(
            20 * np.log10(bimgs[idx]),
            vmin=-60,
            cmap="gray",
            extent=exts[idx],
            origin="upper",
        )

    plt.suptitle("%s: Image Targets" % moniker)
    plt.pause(0.01)
    outdir = os.path.join("results",moniker)
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir, "image.jpg"))
Exemple #6
0
        savedir = os.path.join("datasets", "soundspeed",
                               "%s%03d" % (data_source, acq))
        pathlib.Path(savedir).mkdir(parents=True, exist_ok=True)

        # If the output file already exists, skip
        fname = "%s/data.mat" % savedir
        if os.path.exists(fname):
            print("%s exists. Skipping..." % fname)
            continue
        else:
            print("Processing %s..." % fname)

        xlims = [-10e-3, 10e-3]
        zlims = [20e-3, 40e-3]

        P, _, _ = load_data(data_source, acq)
        P.c = 1540

        if data_source == "MYO":
            zlims = [15e-3, 35e-3]
        elif data_source == "EUT":
            zlims = [15e-3, 35e-3]
        elif data_source == "INS":
            if acq == 24:
                # Acqs 10, 11, 23, 24 are challenging to find a good speckle ROI
                xlims = [-12e-3, 12e-3]
                zlims = [14e-3, 24e-3]

        # Define pixel grid limits (assume y == 0)
        wvln = P.c / P.fc
        dx = wvln / 3
Exemple #7
0
def rois_point(idx, outdir=os.path.join("scoring", "rois", "point")):
    if idx == 0:
        data_source, acq = "MYO", 3
        P, _, _ = load_data(data_source, acq)
        xlims = [0e-3, 20e-3]
        zlims = [22e-3, 32e-3]
        pts = [[13.4e-3, 0, 27.75e-3], [14.55e-3, 0, 26.8e-3],
               [15.15e-3, 0, 25.85e-3]]
    elif idx == 1:
        data_source, acq = "UFL", 4
        P, _, _ = load_data(data_source, acq)
        xlims = [-6e-3, 10e-3]
        zlims = [22e-3, 32e-3]
        pts = [[-2.8e-3, 0, 27.65e-3], [-3.95e-3, 0, 26.7e-3],
               [-4.56e-3, 0, 25.7e-3]]
    elif idx == 2:
        data_source, acq = "UFL", 2
        P, _, _ = load_data(data_source, acq)
        xlims = [-3e-3, 3e-3]
        zlims = [12e-3, 38e-3]
        pts = [
            [-0.29e-3, 0, 15.5e-3],
            [-0.31e-3, 0, 20.6e-3],
            [-0.43e-3, 0, 25.4e-3],
            [-0.20e-3, 0, 30.8e-3],
            [-0.12e-3, 0, 35.7e-3],
        ]
    elif idx == 3:
        data_source, acq = "MYO", 2
        P, _, _ = load_data(data_source, acq)
        xlims = [-15e-3, 11e-3]
        zlims = [38e-3, 42e-3]
        pts = [[-11.95e-3, 0, 39.4e-3], [-2e-3, 0, 39.55e-3],
               [8e-3, 0, 39.6e-3]]
    else:
        raise NotImplementedError

    # Define pixel grid limits (assume y == 0)
    wvln = P.c / P.fc
    dx = wvln / 3
    dz = dx  # Use square pixels
    grid = make_pixel_grid(xlims, zlims, dx, dz)
    fnum = 1

    # Normalize input to [-1, 1] range
    maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
    P.idata /= maxval
    P.qdata /= maxval

    # Make data torch tensors
    x = (P.idata, P.qdata)

    # Make 75-angle image
    dasN = DAS_PW(P, grid, rxfnum=fnum)
    idasN, qdasN = dasN(x)
    idasN, qdasN = idasN.detach().cpu().numpy(), qdasN.detach().cpu().numpy()
    iqN = idasN + 1j * qdasN
    bimgN = 20 * np.log10(np.abs(iqN))  # Log-compress
    bimgN -= np.amax(bimgN)  # Normalize by max value

    # Display images via matplotlib
    xext = (np.array([-0.5, grid.shape[1] - 0.5]) * dx + xlims[0]) * 1e3
    zext = (np.array([-0.5, grid.shape[0] - 0.5]) * dz + zlims[0]) * 1e3
    extent = [xext[0], xext[1], zext[1], zext[0]]
    plt.clf()
    plt.imshow(bimgN, vmin=-40, cmap="gray", extent=extent, origin="upper")
    plt.suptitle("%s%03d (c = %d m/s)" % (data_source, acq, np.round(P.c)))
    bar = np.array([-1e-3, 1e-3])
    tmp = np.array([0, 0])
    for pt in pts:
        plt.plot((pt[0] + bar) * 1e3, (pt[2] + tmp) * 1e3, "c-")
        plt.plot((pt[0] + tmp) * 1e3, (pt[2] + bar) * 1e3, "c-")
    # Check to make sure save directory exists, if not, create it
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir, "roi%02d.png" % (idx)))

    # Save
    mdict = {
        "grid": grid,
        "data_source": data_source,
        "acq": acq,
        "extent": extent,
        "pts": pts,
    }
    hdf5storage.savemat(os.path.join(outdir, "roi%02d" % (idx)), mdict)
Exemple #8
0
def measure_point(beamformer, moniker, center_angle=False, verbose=True):
    x_fwhms = []
    z_fwhms = []
    bimgs = []
    exts = []
    for idx in range(4):
        torch.cuda.empty_cache()
        # Load ROI information
        mdict = hdf5storage.loadmat(os.path.join("scoring","rois","point","roi%02d.mat" % idx))
        data_source = mdict["data_source"]
        acq = mdict["acq"]
        img_grid = mdict["grid"]
        extent = mdict["extent"]
        pts = mdict["pts"]
        exts.append(extent)

        # Load plane wave channel data
        P, _, _ = load_data(data_source, acq)
        if center_angle:
            # Grab only the center angle's worth of data
            aidx = len(P.angles) // 2
            P.idata = P.idata[[aidx]]
            P.qdata = P.qdata[[aidx]]
            P.angles = P.angles[[aidx]]
            P.time_zero = P.time_zero[[aidx]]

        # Normalize input to [-1, 1] range
        maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
        P.idata /= maxval
        P.qdata /= maxval

        # Make grid based on ROIs
        bimg = beamformer(P, img_grid)
        bimgs.append(bimg)

        x_fwhm = []
        z_fwhm = []
        for i, pt in enumerate(pts):
            # One option is to directly beamform a line of pixels over the point targets
            # at high pixel density. However, this may be unfair to methods that rely on
            # a consistent pixel spacing, or to those that require 2D images to operate
            # upon.
            # Instead, we choose to interpolate the original beamformed image.
            ax = img_grid[:, 0, 2]  # Axial pixel positions [m]
            az = img_grid[0, :, 0]  # Azimuthal pixel positions [m]
            f = interp2d(ax, az, bimg)

            # Define pixel grid limits (assume y == 0)
            dp = P.c / P.fc / 3 / 100  # Interpolate 100-fold
            roi = np.arange(-1e-3, 1e-3, dp)
            roi -= np.mean(roi)
            zeros = np.zeros_like(roi)
            # Horizontal grid
            xroi = f(pt[2] + zeros, pt[0] + roi)[0]
            zroi = f(pt[2] + roi, pt[0] + zeros)[:, 0]

            x_fwhm.append(res_FWHM(xroi) * dp)
            z_fwhm.append(res_FWHM(zroi) * dp)

        x_fwhms.append(np.mean(x_fwhm))
        z_fwhms.append(np.mean(z_fwhm))
        if verbose:
            print("ROI %d, x-FWHM: %dum" % (idx, np.round(x_fwhms[idx] * 1e6)))
            print("ROI %d, z-FWHM: %dum" % (idx, np.round(z_fwhms[idx] * 1e6)))

    hdf5storage.savemat(
        os.path.join("results",moniker,"point"),
        {"x_fwhms": x_fwhms, "z_fwhms": z_fwhms, "bimgs": bimgs, "exts": exts},
    )

    # Display images via matplotlib
    plt.figure(figsize=[10, 6])
    plt.subplot(2, 3, 1)
    plt.imshow(_dB(bimgs[0]), vmin=-40, cmap="gray", extent=exts[0], origin="upper")
    plt.subplot(2, 3, 2)
    plt.imshow(_dB(bimgs[1]), vmin=-40, cmap="gray", extent=exts[1], origin="upper")
    plt.subplot(1, 3, 3)
    plt.imshow(_dB(bimgs[2]), vmin=-40, cmap="gray", extent=exts[2], origin="upper")
    plt.subplot(2, 2, 3)
    plt.imshow(_dB(bimgs[3]), vmin=-40, cmap="gray", extent=exts[3], origin="upper")
    plt.suptitle("Point Targets")
    plt.pause(0.01)
    outdir = os.path.join("results",moniker)
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir,"point.jpg"))
Exemple #9
0
def rois_speckle(idx, outdir=os.path.join("scoring", "rois", "speckle")):
    if idx == 0:
        data_source, acq = "UFL", 4
        P, _, _ = load_data(data_source, acq)
        xlims = [0e-3, 12e-3]
        zlims = [14e-3, 26e-3]
    elif idx == 1:
        data_source, acq = "OSL", 7
        P, _, _ = load_data(data_source, acq)
        xlims = [-6e-3, 6e-3]
        zlims = [14e-3, 26e-3]
    elif idx == 2:
        data_source, acq = "MYO", 2
        P, _, _ = load_data(data_source, acq)
        xlims = [-6e-3, 6e-3]
        zlims = [14e-3, 26e-3]
    elif idx == 3:
        data_source, acq = "EUT", 3
        P, _, _ = load_data(data_source, acq)
        xlims = [-6e-3, 6e-3]
        zlims = [25e-3, 37e-3]
    elif idx == 4:
        data_source, acq = "INS", 4
        P, _, _ = load_data(data_source, acq)
        xlims = [-6e-3, 6e-3]
        zlims = [25e-3, 37e-3]
    elif idx == 5:
        data_source, acq = "INS", 16
        P, _, _ = load_data(data_source, acq)
        xlims = [-6e-3, 6e-3]
        zlims = [25e-3, 37e-3]
    else:
        raise NotImplementedError

    # Define pixel grid limits (assume y == 0)
    wvln = P.c / P.fc
    dx = wvln / 3
    dz = dx  # Use square pixels
    grid = make_pixel_grid(xlims, zlims, dx, dz)
    fnum = 1

    # Normalize input to [-1, 1] range
    maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
    P.idata /= maxval
    P.qdata /= maxval

    # Make data torch tensors
    x = (P.idata, P.qdata)

    # Make 75-angle image
    dasN = DAS_PW(P, grid, rxfnum=fnum)
    idasN, qdasN = dasN(x)
    idasN, qdasN = idasN.detach().cpu().numpy(), qdasN.detach().cpu().numpy()
    iqN = idasN + 1j * qdasN
    bimgN = 20 * np.log10(np.abs(iqN))  # Log-compress
    bimgN -= np.amax(bimgN)  # Normalize by max value

    # Display images via matplotlib
    xext = (np.array([-0.5, grid.shape[1] - 0.5]) * dx + xlims[0]) * 1e3
    zext = (np.array([-0.5, grid.shape[0] - 0.5]) * dz + zlims[0]) * 1e3
    extent = [xext[0], xext[1], zext[1], zext[0]]
    plt.clf()
    plt.imshow(bimgN, vmin=-40, cmap="gray", extent=extent, origin="upper")
    plt.suptitle("%s%03d (c = %d m/s)" % (data_source, acq, np.round(P.c)))
    # Check to make sure save directory exists, if not, create it
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir, "roi%02d.png" % (idx)))

    # Save
    mdict = {
        "grid": grid,
        "data_source": data_source,
        "acq": acq,
        "extent": extent
    }
    hdf5storage.savemat(os.path.join(outdir, "roi%02d" % (idx)), mdict)
Exemple #10
0
def measure_lesion(beamformer, moniker, center_angle=False, verbose=True):
    contrasts = []
    cnrs = []
    gcnrs = []
    brois = []
    bimgs = []
    for idx in range(8):
        torch.cuda.empty_cache()
        # Load ROI information
        mdict = hdf5storage.loadmat(os.path.join("scoring","rois","lesion","roi%02d.mat" % idx))
        data_source = mdict["data_source"]
        acq = mdict["acq"]
        # roi_grid = np.concatenate((mdict["grid_i"], mdict["grid_o"]), axis=0)
        roi_i = mdict["roi_i"]
        roi_o = mdict["roi_o"]
        img_grid = mdict["grid"]
        extent = mdict["extent"]
        # ni = mdict["grid_i"].shape[0]

        # Load plane wave channel data
        P, _, _ = load_data(data_source, acq)
        # Normalize input to [-1, 1] range
        maxval = np.maximum(np.abs(P.idata).max(), np.abs(P.qdata).max())
        P.idata /= maxval
        P.qdata /= maxval

        if center_angle:
            # Grab only the center angle's worth of data
            aidx = len(P.angles) // 2
            P.idata = P.idata[[aidx]]
            P.qdata = P.qdata[[aidx]]
            P.angles = P.angles[[aidx]]
            P.time_zero = P.time_zero[[aidx]]

        # Beamform the ROI and image
        # broi = beamformer(P, roi_grid)
        bimg = beamformer(P, img_grid)
        # brois.append(broi)
        bimgs.append(bimg)

        # Compute statistics
        # b_inner, b_outer = broi[:ni], broi[ni:]
        b_inner = bimgs[idx][roi_i]
        b_outer = bimgs[idx][roi_o]
        contrasts.append(contrast(b_inner, b_outer))
        cnrs.append(cnr(b_inner, b_outer))
        gcnrs.append(gcnr(b_inner, b_outer))

        if verbose:
            print("roi%02d Contrast: %f" % (idx, contrasts[idx]))
            print("roi%02d CNR: %f" % (idx, cnrs[idx]))
            print("roi%02d gCNR: %f" % (idx, gcnrs[idx]))

    hdf5storage.savemat(
        os.path.join("results",moniker,"lesion"),
        {
            "contrasts": contrasts,
            "cnrs": cnrs,
            "gcnrs": gcnrs,
            "brois": brois,
            "bimgs": bimgs,
        },
    )
    plt.figure(figsize=[10, 6])
    for idx in range(8):
        # Display images via matplotlib
        plt.subplot(2, 4, idx + 1)
        plt.imshow(
            20 * np.log10(bimgs[idx]),
            vmin=-40,
            cmap="gray",
            extent=extent,
            origin="upper",
        )

    plt.suptitle("%s: Anechoic Lesions" % moniker)
    plt.pause(0.01)
    outdir = os.path.join("results",moniker)
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    plt.savefig(os.path.join(outdir,"lesion.jpg"))