Exemple #1
0
def test_skimage_1():
    """
    Push two images, perform ADO function to combine and return image
    """
    session = pymcas.create_session(os.getenv('SERVER_IP'), 11911, debug=3)
    if sys.getrefcount(session) != 2:
        raise ValueError("session ref count should be 2")
    pool = session.create_pool("myPool2", int(1e9), 100)
    if sys.getrefcount(pool) != 2:
        raise ValueError("pool ref count should be 2")

    # save image
    from skimage import data, io, filters

    pool.save('camera', data.camera())
    pool.save('brick', data.brick())

    # # perform ADO invocation
    shape = pool.invoke('camera', blend_ado_function, 0.5)  # param is delta
    print("shape:{0}".format(shape))

    blend = pool.load('blended')

    io.imshow(blend)
    io.show()
Exemple #2
0
def demo(force_new=True):
    '''
    Demonstration of pymm features
    '''
    import pymm
    import numpy as np

    # create new shelf (override any existing myShelf)
    #
    s = pymm.shelf('myShelf',
                   1024,
                   pmem_path='/mnt/pmem0',
                   force_new=force_new)

    # create variable x on shelf (using shadow type)
    s.x = pymm.ndarray((1000, 1000), dtype=np.float)

    if s.x.shape != (1000, 1000):
        raise RuntimeException('demo: s.x.shape check failed')

    # perform in-place (on-shelf) operations
    s.x.fill(3)
    s.x += 2
    x_checksum = sum(s.x.tobytes())  # get checksum

    # write binary array data to file
    dfile = open("array.dat", "wb")
    dfile.write(s.x.tobytes())
    dfile.close()

    # create new instance
    s.z = np.ndarray((1000, 1000), dtype=np.float)

    # zero-copy read into instance from file
    with open("array.dat", "rb") as source:
        source.readinto(memoryview(s.z))
    z_checksum = sum(s.z.tobytes())  # get checksum
    if z_checksum != x_checksum:
        raise RuntimeError('data checksum mismatch')

    # this will create a persistent memory copy from RHS DRAM/volatile instance
    # the right hand side will be garbage collected
    from skimage import data, io

    s.i = data.camera()
    s.j = data.brick()

    s.blended = s.i + (0.5 * s.j)
    io.imshow(s.blended)
    io.show()

    # remove objects from shelf
    for item in s.items:
        s.erase(item)

    return
Exemple #3
0
def run():
    logger.info("Starting")
    file_folder = os.path.dirname(os.path.realpath(__file__))
    output_folder = os.path.join(file_folder, "output")
    os.makedirs(output_folder, exist_ok=True)

    # Simple example with a BW test image from skimage
    logger.info("Simple 512x512 example from skimage")
    sc_image = SCImage()
    sc_image.create_empty_iod()
    sc_image.initiate()
    sc_image.set_dicom_attribute("PatientName", "BWBrick^512x512")
    sc_image.set_dicom_attribute("SeriesNumber", "1")
    sc_image.add_pixel_data(data.brick())
    study_folder = os.path.join(output_folder, "data", "sc_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "brick_512x512"), exist_ok=True)
    output_file = os.path.join(
        study_folder, "brick_512x512",
        str(sc_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    sc_image.write_to_file(output_file)

    # Simple example with an RGB test image from skimage
    logger.info("RGB example from skimage")
    sc_image = SCImage()
    sc_image.create_empty_iod()
    sc_image.initiate()
    sc_image.set_dicom_attribute("PatientName", "RGBRetina^NoTiling")
    sc_image.set_dicom_attribute("SeriesNumber", "1")
    sc_image.add_pixel_data(data.retina(), photometric_interpretation="RGB")
    study_folder = os.path.join(output_folder, "data", "sc_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "retina_no_tiling"), exist_ok=True)
    output_file = os.path.join(
        study_folder, "retina_no_tiling",
        str(sc_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    sc_image.write_to_file(output_file)
    return min_i


# prepare filter bank kernels
kernels = []
for theta in range(4):
    theta = theta / 4. * np.pi
    for sigma in (1, 3):
        for frequency in (0.05, 0.25):
            kernel = np.real(gabor_kernel(frequency, theta=theta,
                                          sigma_x=sigma, sigma_y=sigma))
            kernels.append(kernel)


shrink = (slice(0, None, 3), slice(0, None, 3))
brick = img_as_float(data.brick())[shrink]
grass = img_as_float(data.grass())[shrink]
gravel = img_as_float(data.gravel())[shrink]
image_names = ('brick', 'grass', 'gravel')
images = (brick, grass, gravel)

# prepare reference features
ref_feats = np.zeros((3, len(kernels), 2), dtype=np.double)
ref_feats[0, :, :] = compute_feats(brick, kernels)
ref_feats[1, :, :] = compute_feats(grass, kernels)
ref_feats[2, :, :] = compute_feats(gravel, kernels)

print('Rotated images matched against references using Gabor filter banks:')

print('original: brick, rotated: 30deg, match result: ', end='')
feats = compute_feats(ndi.rotate(brick, angle=190, reshape=False), kernels)
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
# from PIL import Image
import math

image = data.coffee()
image2 = data.brick()
image3 = data.brick()


def convert_to_gray(image, luma=False):
    # http://poynton.ca/PDFs/ColorFAQ.pdf
    image_r = image[:, :, 0]
    image_g = image[:, :, 1]
    image_b = image[:, :, 2]

    if luma:
        params = [0.299, 0.589, 0.114]
    else:
        params = [0.2125, 0.7154, 0.0721]

    gray_image = np.ceil(np.dot(image[..., :3], params))
    gray_image[gray_image > 255] = 255

    return gray_image


# x = np.ceil((image_r + image_g + image_b) / 3)

image = convert_to_gray(image)
def run():
    logger.info("Starting")
    file_folder = os.path.dirname(os.path.realpath(__file__))
    output_folder = os.path.join(file_folder, "output")
    os.makedirs(output_folder, exist_ok=True)

    # Simple example with BW noise
    logger.info("Simple 256x256 example with noice")
    wsm_image = WSMImage()
    wsm_image.create_empty_iod()
    wsm_image.initiate()
    wsm_image.set_dicom_attribute("PatientName", "BWNoise^256x256")
    wsm_image.set_dicom_attribute("SeriesNumber", "1")
    study_folder = os.path.join(output_folder, "data", "wsm_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "noise_256x256"), exist_ok=True)
    output_file = os.path.join(
        study_folder, "noise_256x256",
        str(wsm_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    wsm_image.write_to_file(output_file)

    # Simple example with a BW test image from skimage
    logger.info("Simple 512x512 example from skimage")
    wsm_image = WSMImage()
    wsm_image.create_empty_iod()
    wsm_image.initiate()
    wsm_image.set_dicom_attribute("PatientName", "BWBrick^512x512")
    wsm_image.set_dicom_attribute("SeriesNumber", "1")
    wsm_image.add_pixel_data(data.brick())
    study_folder = os.path.join(output_folder, "data", "wsm_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "brick_512x512"), exist_ok=True)
    output_file = os.path.join(
        study_folder, "brick_512x512",
        str(wsm_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    wsm_image.write_to_file(output_file)

    # Simple example with a BW test image from skimage but with tiling
    logger.info("Simple 512x512 example from skimage with tiling")
    wsm_image = WSMImage()
    wsm_image.create_empty_iod()
    wsm_image.initiate()
    wsm_image.set_dicom_attribute("PatientName", "BWBrick^WithTiling")
    wsm_image.set_dicom_attribute("SeriesNumber", "1")
    wsm_image.add_pixel_data(data.brick(), tile_size=[256, 256])
    study_folder = os.path.join(output_folder, "data", "wsm_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "brick_512x512_tiling_256x256"),
                exist_ok=True)
    output_file = os.path.join(
        study_folder, "brick_512x512_tiling_256x256",
        str(wsm_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    wsm_image.write_to_file(output_file)

    # Simple example with an RGB  test image from skimage
    logger.info("RGB example from skimage")
    wsm_image = WSMImage()
    wsm_image.create_empty_iod()
    wsm_image.initiate()
    wsm_image.set_dicom_attribute("PatientName", "RGBRetina^NoTiling")
    wsm_image.set_dicom_attribute("SeriesNumber", "1")
    wsm_image.add_pixel_data(data.retina()[0:1410, 0:1410, :],
                             photometric_interpretation="RGB")
    study_folder = os.path.join(output_folder, "data", "wsm_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "retina_no_tiling"), exist_ok=True)
    output_file = os.path.join(
        study_folder, "retina_no_tiling",
        str(wsm_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    wsm_image.write_to_file(output_file)

    # Simple example with an RGB  test image from skimage but with tiling
    logger.info("RGB example from skimage with tiling")
    wsm_image = WSMImage()
    wsm_image.create_empty_iod()
    wsm_image.initiate()
    wsm_image.set_dicom_attribute("PatientName", "RGBRetina^WithTiling")
    wsm_image.set_dicom_attribute("SeriesNumber", "1")
    wsm_image.add_pixel_data(data.retina()[0:1410, 0:1410, :],
                             photometric_interpretation="RGB",
                             tile_size=[256, 256])
    study_folder = os.path.join(output_folder, "data", "wsm_images")
    os.makedirs(study_folder, exist_ok=True)
    os.makedirs(os.path.join(study_folder, "retina_tiling_256x256"),
                exist_ok=True)
    output_file = os.path.join(
        study_folder, "retina_tiling_256x256",
        str(wsm_image.dataset.InstanceNumber).zfill(6) + ".dcm")
    wsm_image.write_to_file(output_file)

    # Simple example with an acutal WSI image with tiling and multi-resolution
    logger.info(
        "High resolution RGB example from pexels with tiling and multi-resolution"
    )
    input_file = os.path.join(file_folder, "data", "wsi_images",
                              "image_to_encode_as_dicom.jpg")
    if not os.path.exists(input_file):
        logger.info("Data not available locally, downloading")
        url = "https://images.pexels.com/photos/1270184/pexels-photo-1270184.jpeg"
        downloaded_file = requests.get(url)
        open(input_file, "wb").write(downloaded_file.content)
    im = imread(input_file)
    im = im[:, :, 0:3]
    study_folder = os.path.join(output_folder, "data", "wsm_images",
                                "BW-skull")
    os.makedirs(study_folder, exist_ok=True)
    patient_id = ''.join(random.choice('0123456789ABCDEF') for i in range(16))
    accession_number = ''.join(
        random.choice('0123456789ABCDEF') for i in range(16))
    study_instance_uid = generate_uid()
    series_instance_uid = generate_uid()
    frame_of_reference_uid = generate_uid()
    study_date = datetime.now().strftime("%Y%m%d")
    study_time = datetime.now().strftime("%H%M%S")
    for level in range(0, 3):
        logger.info("Level: " + str(level))
        wsm_image = WSMImage()
        wsm_image.create_empty_iod()
        wsm_image.initiate()
        wsm_image.set_dicom_attribute("PatientName", "Black-White^Skull")
        wsm_image.set_dicom_attribute("PatientID", patient_id)
        wsm_image.set_dicom_attribute("StudyInstanceUID", study_instance_uid)
        wsm_image.set_dicom_attribute("AccessionNumber", accession_number)
        wsm_image.set_dicom_attribute("StudyID", accession_number)
        wsm_image.set_dicom_attribute("StudyDate", study_date)
        wsm_image.set_dicom_attribute("StudyTime", study_time)
        wsm_image.set_dicom_attribute("SeriesInstanceUID", series_instance_uid)
        wsm_image.set_dicom_attribute("FrameOfReferenceUID",
                                      frame_of_reference_uid)
        wsm_image.set_dicom_attribute("SeriesNumber", "1")
        wsm_image.set_dicom_attribute("SeriesDate", study_date)
        wsm_image.set_dicom_attribute("SeriesTime", study_time)
        wsm_image.set_dicom_attribute("InstanceNumber", str(level))
        if level > 0:
            wsm_image.set_dicom_attribute(
                "ImageType", ["DERIVED", "PRIMARY", "VOLUME", "RESAMPLED"])
        im_resized = resize(im, (int(
            im.shape[0] / pow(2, level)), int(im.shape[1] / pow(2, level)), 3),
                            preserve_range=True).astype(np.uint8)
        wsm_image.add_pixel_data(im_resized,
                                 photometric_interpretation="RGB",
                                 pixel_spacing=[
                                     0.0005 * int(pow(2, level)),
                                     0.0005 * int(pow(2, level))
                                 ],
                                 tile_size=[256, 256])
        output_file = os.path.join(
            study_folder,
            str(wsm_image.dataset.InstanceNumber).zfill(6) + ".dcm")
        wsm_image.write_to_file(output_file)
Exemple #7
0
    image = caller()
    plt.figure()
    plt.title(name)
    if image.ndim == 2:
        plt.imshow(image, cmap=plt.cm.gray)
    else:
        plt.imshow(image)

plt.show()

############################################################################
# Thumbnail image for the gallery

# sphinx_gallery_thumbnail_number = -1
fig, axs = plt.subplots(nrows=3, ncols=3)
for ax in axs.flat:
    ax.axis("off")
axs[0, 0].imshow(data.astronaut())
axs[0, 1].imshow(data.binary_blobs(), cmap=plt.cm.gray)
axs[0, 2].imshow(data.brick(), cmap=plt.cm.gray)
axs[1, 0].imshow(data.colorwheel())
axs[1, 1].imshow(data.camera(), cmap=plt.cm.gray)
axs[1, 2].imshow(data.cat())
axs[2, 0].imshow(data.checkerboard(), cmap=plt.cm.gray)
axs[2, 1].imshow(data.clock(), cmap=plt.cm.gray)
further_img = np.full((300, 300), 255)
for xpos in [100, 150, 200]:
    further_img[150 - 10:150 + 10, xpos - 10:xpos + 10] = 0
axs[2, 2].imshow(further_img, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=0.1, hspace=0.1)
# settings for LBP
radius = 3
n_points = 8 * radius


def overlay_labels(image, lbp, labels):
    mask = np.logical_or.reduce([lbp == each for each in labels])
    return label2rgb(mask, image=image, bg_label=0, alpha=0.5)


def highlight_bars(bars, indexes):
    for i in indexes:
        bars[i].set_facecolor('r')


image = data.brick()
lbp = local_binary_pattern(image, n_points, radius, METHOD)


def hist(ax, lbp):
    n_bins = int(lbp.max() + 1)
    return ax.hist(lbp.ravel(),
                   density=True,
                   bins=n_bins,
                   range=(0, n_bins),
                   facecolor='0.5')


# plot histograms of LBP of textures
fig, (ax_img, ax_hist) = plt.subplots(nrows=2, ncols=3, figsize=(9, 6))
plt.gray()
Exemple #9
0
from skimage import data, transform
from skimage.feature import local_binary_pattern
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np

# loading the necessary images
brick = data.brick()
grass = data.grass()
gravel = data.gravel()
# setting local binary pattern parameters
radius = 2
n_points = 8 * radius


# defining a scoring function
def kullback_leibler_divergence(p, q):
    p = np.asarray(p)
    q = np.asarray(q)
    filt = np.logical_and(p != 0, q != 0)
    return np.sum(p[filt] * np.log2(p[filt] / q[filt]))


# defining a function to create histogram based on found features in the descriptors
# then compare the histogram to the criteria lbp to determine the group
def match(refs, img):
    best_score = 10
    best_name = None
    lbp = local_binary_pattern(img, n_points, radius, 'uniform')
    n_bins = int(lbp.max() + 1)
    hist, _ = np.histogram(lbp, density=True, bins=n_bins, range=(0, n_bins))