def test_apply_parallel_rgb_channel_axis(depth, chunks):
    cat = img_as_float(data.chelsea())

    func = color.rgb2ycbcr
    cat_ycbcr_expected = func(cat)
    cat_ycbcr = apply_parallel(func,
                               cat,
                               chunks=chunks,
                               depth=depth,
                               dtype=cat.dtype,
                               channel_axis=-1)
    assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)

    # channels axis along first dimension instead
    cat = np.moveaxis(cat, -1, 0)
    cat_ycbcr = apply_parallel(func,
                               cat,
                               chunks=chunks,
                               depth=depth,
                               dtype=cat.dtype,
                               channel_axis=0)
    # move channels of output back to the last dimension
    cat_ycbcr = np.moveaxis(cat_ycbcr, 0, -1)

    assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)
Ejemplo n.º 2
0
def test_apply_parallel_rgb_channel_axis(depth, chunks, channel_axis):
    """Test channel_axis combinations.

    For depth and chunks, test in three ways:
    1.) scalar (to be applied over all axes)
    2.) tuple of length ``image.ndim - 1`` corresponding to spatial axes
    3.) tuple of length ``image.ndim`` corresponding to all axes
    """
    cat = img_as_float(data.chelsea())

    func = color.rgb2ycbcr
    cat_ycbcr_expected = func(cat, channel_axis=-1)

    # move channel axis to another position
    cat = np.moveaxis(cat, -1, channel_axis)
    if chunks == 'ndim':
        # explicitly specify the chunksize for the channel axis
        chunks = [128, 128]
        chunks.insert(channel_axis % cat.ndim, cat.shape[channel_axis])
    if depth == 'ndim':
        # explicitly specify the depth for the channel axis
        depth = [8, 8]
        depth.insert(channel_axis % cat.ndim, 0)
    cat_ycbcr = apply_parallel(func,
                               cat,
                               chunks=chunks,
                               depth=depth,
                               dtype=cat.dtype,
                               channel_axis=channel_axis,
                               extra_keywords=dict(channel_axis=channel_axis))
    # move channels of output back to the last dimension
    cat_ycbcr = np.moveaxis(cat_ycbcr, channel_axis, -1)

    assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)
def main(out_range=0.4):
    image = color.rgb2gray(img_as_float(data.chelsea()))
    image = exposure.rescale_intensity(image, out_range=(0, 4 * np.pi))
    image_wrapped = np.angle(np.exp(1j * image))
    image_unwrapped = unwrap_phase(image_wrapped)

    fig, ax = plt.subplots(2, 2, sharex=True, sharey=True)
    ax1, ax2, ax3, ax4 = ax.ravel()

    fig.colorbar(ax1.imshow(image, cmap='gray', vmin=0, vmax=4 * np.pi),
                 ax=ax1)
    ax1.set_title('Original')

    fig.colorbar(ax2.imshow(image_wrapped,
                            cmap='gray',
                            vmin=-np.pi,
                            vmax=np.pi),
                 ax=ax2)
    ax2.set_title('Wrapped phase')

    fig.colorbar(ax3.imshow(image_unwrapped, cmap='gray'), ax=ax3)
    ax3.set_title('After phase unwrapping')

    fig.colorbar(ax4.imshow(image_unwrapped - image, cmap='gray'), ax=ax4)
    ax4.set_title('Unwrapped minus original')

    plt.tight_layout()
    plt.show()
Ejemplo n.º 4
0
def color_check(plugin, fmt='png'):
    """Check roundtrip behavior for color images.

    All major input types should be handled as ubytes and read
    back correctly.
    """
    img = img_as_ubyte(data.chelsea())
    r1 = roundtrip(img, plugin, fmt)
    testing.assert_allclose(img, r1)

    img2 = img > 128
    r2 = roundtrip(img2, plugin, fmt)
    testing.assert_allclose(img2.astype(np.uint8), r2)

    img3 = img_as_float(img)
    r3 = roundtrip(img3, plugin, fmt)
    testing.assert_allclose(r3, img)

    img4 = img_as_int(img)
    if fmt.lower() in (('tif', 'tiff')):
        img4 -= 100
        r4 = roundtrip(img4, plugin, fmt)
        testing.assert_allclose(r4, img4)
    else:
        r4 = roundtrip(img4, plugin, fmt)
        testing.assert_allclose(r4, img_as_ubyte(img4))

    img5 = img_as_uint(img)
    r5 = roundtrip(img5, plugin, fmt)
    testing.assert_allclose(r5, img)
Ejemplo n.º 5
0
def denoise_img(file_name):
    if file_name is not None:
        image = cv2.imread(file_name)
        original = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        noisy = original
    else:
        original = img_as_float(data.chelsea()[100:250, 50:300])
        sigma = 0.155
        noisy = random_noise(original, var=sigma**2)
    print("img shape", np.shape(noisy))
    fig, ax = plt.subplots(nrows=2,
                           ncols=4,
                           figsize=(8, 5),
                           sharex=True,
                           sharey=True)
    plt.gray()
    # Estimate the average noise standard deviation across color channels.
    sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
    # Due to clipping in random_noise, the estimate will be a bit smaller than the
    # specified sigma.
    print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))
    ax[0, 0].imshow(noisy)
    ax[0, 0].axis('off')
    ax[0, 0].set_title('Noisy')
    ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
    ax[0, 1].axis('off')
    ax[0, 1].set_title('TV')
    ax[0, 2].imshow(
        denoise_bilateral(noisy,
                          sigma_color=0.05,
                          sigma_spatial=15,
                          multichannel=True))
    ax[0, 2].axis('off')
    ax[0, 2].set_title('Bilateral')
    ax[0, 3].imshow(denoise_wavelet(noisy, multichannel=True))
    ax[0, 3].axis('off')
    ax[0, 3].set_title('Wavelet denoising')

    ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.02,
                                         multichannel=True))
    ax[1, 1].axis('off')
    ax[1, 1].set_title('(more) TV')
    ax[1, 2].imshow(
        denoise_bilateral(noisy,
                          sigma_color=0.001,
                          sigma_spatial=3,
                          multichannel=True))
    ax[1, 2].axis('off')
    ax[1, 2].set_title('(more) Bilateral')
    ax[1,
       3].imshow(denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True))
    ax[1, 3].axis('off')
    ax[1, 3].set_title('Wavelet denoising\nin YCbCr colorspace')
    ax[1, 0].imshow(original)
    ax[1, 0].axis('off')
    ax[1, 0].set_title('Original')

    fig.tight_layout()

    plt.show()
Ejemplo n.º 6
0
def sharpen():
    #img_color = cv2.imread('../images/lena.jpg')
    img_color = data.chelsea()
    #b,g,r = cv2.split(img_color)
    #img = color.rgb2gray(img_color)
    #img = data.camera()
    img = cv2.cvtColor(img_color, cv2.COLOR_RGB2GRAY)
    #Robert_b = Roberts(b)
    #Robert_g = Roberts(g)
    #Robert_r = Roberts(r)
    #Roberts_img = cv2.merge([Robert_r,Robert_g,Robert_b])
    Roberts_img = Roberts(img)
    #Sobel_b = Sobel(b)
    #Sobel_g = Sobel(g)
    #Sobel_r = Sobel(r)
    #Sobel_img = cv2.merge([Sobel_r,Sobel_g,Sobel_b])
    Sobel_img = Sobel(img)
    #Laplacian_b = Laplace(b)
    #Laplacian_g = Laplace(g)
    #Laplacian_r = Laplace(r)
    Laplacian_img = Laplace(img)
    #Laplacian_img = cv2.merge([Laplacian_r,Laplacian_g,Laplacian_b])
    plt.subplot(221), plt.imshow(Roberts_img, cmap='gray')
    plt.title('Roberts')
    plt.subplot(222), plt.imshow(Sobel_img, cmap='gray')
    plt.title('Sobel')
    plt.subplot(223), plt.imshow(Laplacian_img, cmap='gray')
    plt.title('Laplacian')
    plt.show()
Ejemplo n.º 7
0
class TestMatchHistogram:

    image_rgb = cp.asarray(data.chelsea())
    template_rgb = cp.asarray(data.astronaut())

    @pytest.mark.parametrize(
        'image, reference, multichannel',
        [(image_rgb, template_rgb, True),
         (image_rgb[:, :, 0], template_rgb[:, :, 0], False)])
    def test_match_histograms(self, image, reference, multichannel):
        """Assert that pdf of matched image is close to the reference's pdf for
        all channels and all values of matched"""

        # when
        matched = exposure.match_histograms(image,
                                            reference,
                                            multichannel=multichannel)

        matched = cp.asnumpy(matched)
        matched_pdf = self._calculate_image_empirical_pdf(matched)
        reference_pdf = self._calculate_image_empirical_pdf(
            cp.asnumpy(reference))

        # then
        for channel in range(len(matched_pdf)):
            reference_values, reference_quantiles = reference_pdf[channel]
            matched_values, matched_quantiles = matched_pdf[channel]

            for i, matched_value in enumerate(matched_values):
                closest_id = (np.abs(reference_values -
                                     matched_value)).argmin()
                assert_almost_equal(matched_quantiles[i],
                                    reference_quantiles[closest_id],
                                    decimal=1)

    @pytest.mark.parametrize('image, reference',
                             [(image_rgb, template_rgb[:, :, 0]),
                              (image_rgb[:, :, 0], template_rgb)])
    def test_raises_value_error_on_channels_mismatch(self, image, reference):
        with pytest.raises(ValueError):
            exposure.match_histograms(image, reference)

    @classmethod
    def _calculate_image_empirical_pdf(cls, image):
        """Helper function for calculating empirical probability density
        function of a given image for all channels"""

        if image.ndim > 2:
            image = image.transpose(2, 0, 1)
        channels = np.array(image, copy=False, ndmin=3)

        channels_pdf = []
        for channel in channels:
            channel_values, counts = np.unique(channel, return_counts=True)
            channel_quantiles = np.cumsum(counts).astype(np.float64)
            channel_quantiles /= channel_quantiles[-1]

            channels_pdf.append((channel_values, channel_quantiles))

        return np.asarray(channels_pdf, dtype=object)
def show_image():
    image = data.chelsea()
    io.imshow(image)
    io.show()

    gray = color.rgb2gray(image)
    fig, axes = plt.subplots(1, 2, figsize=(8, 4))
    ax = axes.ravel()

    ax[0].imshow(image)
    ax[0].set_title("Input RGB")
    ax[1].imshow(gray, cmap=plt.cm.gray)
    ax[1].set_title("gray")

    fig.tight_layout()
    plt.show()

    hsv_img = color.rgb2hsv(image)
    hue_img = hsv_img[:, :, 0]
    value_img = hsv_img[:, :, 2]

    fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(8, 2))

    ax0.imshow(image)
    ax0.set_title("RGB image")
    ax0.axis('off')
    ax1.imshow(hue_img, cmap='hsv')
    ax1.set_title("Hue channel")
    ax1.axis('off')
    ax2.imshow(value_img)
    ax2.set_title("Value channel")
    ax2.axis('off')

    fig.tight_layout()
    plt.show()
Ejemplo n.º 9
0
def dft_dct():
    #encoding
    #img = cv2.imread('../images/lena.jpg', 0)
    #img = cv2.resize(img, (240, 360))
    img = data.chelsea()
    img = color.rgb2gray(img)
    #do dft
    dft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)
    magnitude_spectrum_dft = 20 * np.log(
        cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
    #or use numpy:
    #magnitude_spectrum_dft = 20*np.log(np.abs(dft_shift))

    #do dct
    dct = cv2.dct(np.float32(img))
    dct_img = np.log(abs(dct))

    #plot
    plt.subplot(221), plt.imshow(img, cmap='gray')
    plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(222), plt.imshow(magnitude_spectrum_dft, cmap='gray')
    plt.title('DFT Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(223), plt.imshow(dct_img, cmap='gray')
    plt.title('DCT result'), plt.xticks([]), plt.yticks([])
    plt.show()
Ejemplo n.º 10
0
def test_model_predict_b2_imagenet21k_ft1k():
    model = keras_efficientnet_v2.EfficientNetV2B2(pretrained="imagenet21k-ft1k")
    imm = tf.image.resize(chelsea(), model.input_shape[1:3])  # Chelsea the cat
    pred = model(tf.expand_dims(imm / 128 - 1, 0)).numpy()
    out = keras.applications.imagenet_utils.decode_predictions(pred)[0][0]

    assert out[1] == "Egyptian_cat"
    assert abs(out[2] - 0.58329606) <= 1e-5
Ejemplo n.º 11
0
def test_model_predict_s_imagenet_preprocessing():
    model = keras_efficientnet_v2.EfficientNetV2S(pretrained="imagenet", include_preprocessing=True)
    imm = tf.image.resize(chelsea(), model.input_shape[1:3])  # Chelsea the cat
    pred = model(tf.expand_dims(imm, 0)).numpy()
    out = keras.applications.imagenet_utils.decode_predictions(pred)[0][0]

    assert out[1] == "Egyptian_cat"
    assert abs(out[2] - 0.8642885) <= 1e-5
Ejemplo n.º 12
0
def test_model_predict_s_imagenet21k():
    """ Run a single forward pass with EfficientNetV2S on imagenet21k """
    model = keras_efficientnet_v2.EfficientNetV2S(num_classes=21843, pretrained="imagenet21k")
    imm = tf.image.resize(chelsea(), model.input_shape[1:3])  # Chelsea the cat
    pred = model(tf.expand_dims(imm / 128 - 1, 0)).numpy()

    assert pred.argmax() == 2389
    assert abs(pred.max() - 0.15546332) <= 1e-5
Ejemplo n.º 13
0
def run_main():
    color_image = data.chelsea()

    red_chanel = color_image[:, :, 0]
    print(color_image.shape)
    plt.imshow(red_chanel)
    plt.show()
    return ''
Ejemplo n.º 14
0
def float_and_ubyte():
    img = data.chelsea()
    image_float = img_as_float(img)
    image_ubyte = img_as_ubyte(img)
    print('type min max:', image_float.dtype, image_float.min(),
          image_float.max())
    print('type min max:', image_ubyte.dtype, image_ubyte.min(),
          image_ubyte.max())
Ejemplo n.º 15
0
def test_model_predict_v1_b3_noisy_student_preprocessing():
    """ Run a single forward pass with EfficientNetV1B6 on noisy_student """
    model = keras_efficientnet_v2.EfficientNetV1B3(pretrained="noisy_student", include_preprocessing=True)
    imm = tf.image.resize(chelsea(), model.input_shape[1:3])  # Chelsea the cat
    pred = model(tf.expand_dims(imm, 0)).numpy()
    out = keras.applications.imagenet_utils.decode_predictions(pred)[0][0]

    assert out[1] == "Egyptian_cat"
    assert abs(out[2] - 0.8770545) <= 1e-5
Ejemplo n.º 16
0
def operate_pixel_test():
    img = data.chelsea()
    #输出图片 G 通道中第 20 行第 30 列的像素值 
    pixel = img[20, 30, 1]
    print(pixel)
    #显示猫图片红色通道的图片 
    R = img[:, :, 0]
    io.imshow(R)
    io.show()
Ejemplo n.º 17
0
def test_model_predict_v1_b1_noisy_student():
    """ Run a single forward pass with EfficientNetV1B2 on imagenet """
    model = keras_efficientnet_v2.EfficientNetV1B1(pretrained="noisy_student")
    imm = tf.image.resize(chelsea(), model.input_shape[1:3])  # Chelsea the cat
    pred = model(tf.expand_dims(imm / 128 - 1, 0)).numpy()
    out = keras.applications.imagenet_utils.decode_predictions(pred)[0][0]

    assert out[1] == "Egyptian_cat"
    assert abs(out[2] - 0.8223327) <= 1e-5
Ejemplo n.º 18
0
def test_denoise_bilateral_pad():
    """This test checks if the bilateral filter is returning an image
    correctly padded."""
    img = img_as_float(data.chelsea())[100:200, 100:200]
    img_bil = restoration.denoise_bilateral(img,
                                            sigma_color=0.1,
                                            sigma_spatial=10,
                                            multichannel=True)
    condition_padding = np.count_nonzero(np.isclose(img_bil, 0, atol=0.001))
    assert_equal(condition_padding, 0)
Ejemplo n.º 19
0
    def test_instanciate_segmentation_algorithm(self):
        img = img_as_float(chelsea()[::2, ::2])

        # wrapped functions provide the same result
        fn = SegmentationAlgorithm('quickshift', kernel_size=3, max_dist=6,
                                   ratio=0.5, random_seed=133)
        fn_result = fn(img)
        original_result = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5,
                                     random_seed=133)

        # same segments
        self.assertTrue(np.array_equal(fn_result, original_result))
Ejemplo n.º 20
0
def test_line_profile_rgb():
    """ Test a line profile using an ndim=3 image"""
    plugin = setup_line_profile(data.chelsea(), limits=None)
    for i in range(6):
        plugin.line_tool._thicken_scan_line()
    line_image, scan_data = plugin.output()
    assert_equal(line_image[line_image == 128].size, 750)
    assert_equal(line_image[line_image == 255].size, 151)
    assert_equal(line_image.shape, (300, 451))
    assert_equal(scan_data.shape, (151, 3))
    assert_allclose(scan_data.max(), 0.772, rtol=1e-3)
    assert_allclose(scan_data.mean(), 0.4359, rtol=1e-3)
Ejemplo n.º 21
0
def test_line_profile_rgb():
    """ Test a line profile using an ndim=3 image"""
    plugin = setup_line_profile(data.chelsea())
    for i in range(6):
        plugin.line_tool._thicken_scan_line()
    line_image, scan_data = plugin.output()
    assert_equal(line_image[line_image == 128].size, 755)
    assert_equal(line_image[line_image == 255].size, 151)
    assert_equal(line_image.shape, (300, 451))
    assert_equal(scan_data.shape, (152, 3))
    assert_allclose(scan_data.max(), 0.772, rtol=1e-3)
    assert_allclose(scan_data.mean(), 0.4355, rtol=1e-3)
Ejemplo n.º 22
0
def main():

    #im = Image.open('mri_demo.png')
    #im = im.convert('RGB')
    #data = np.array(im)

    data = chelsea()
    print('1', data.shape)
    plot_polar_image(data, origin=None)
    #plot_directional_intensity(data, origin=None)

    plt.show()
Ejemplo n.º 23
0
def operate_pixel_test_1():
    img=data.chelsea()
    img_gray=color.rgb2gray(img)
    rows,cols=img_gray.shape
    for i in range(rows):
                for j in range(cols):
                    if (img_gray[i,j] <= 0.5):
                            img_gray[i,j]=0
                    else:
                            img_gray[i,j]=1
    io.imshow(img_gray)
    io.show()
Ejemplo n.º 24
0
def test_ssim_multichannel_chelsea():
    # color image example
    Xc = data.chelsea()
    sigma = 15.0
    Yc = np.clip(Xc + sigma * np.random.randn(*Xc.shape), 0, 255)
    Yc = Yc.astype(Xc.dtype)

    # multichannel result should be mean of the individual channel results
    mssim = ssim(Xc, Yc, multichannel=True)
    mssim_sep = [ssim(Yc[..., c], Xc[..., c]) for c in range(Xc.shape[-1])]
    assert_almost_equal(mssim, np.mean(mssim_sep))

    # ssim of image with itself should be 1.0
    assert_equal(ssim(Xc, Xc, multichannel=True), 1.0)
Ejemplo n.º 25
0
def chelsea():
    """What a cute RGB kitty!

    Only use for visual confirmation to help debugging. Mark these tests with:
        @pytest.mark.visual

    Returns
    -------
    numpy.ndarray
        (H,W,3) uint8_t RGB test image.
    """
    from skimage import data

    return data.chelsea()
Ejemplo n.º 26
0
def convert_pixel_type_test():
    img = data.chelsea()
    print(img.dtype.name)

    # 进行转换
    img_grey = img_as_float(img)
    # 显示转换后的类型         
    print(img_grey.dtype.name)

    
    img = np.array([[0.2], [0.5], [0.1]], dtype=float)
    print(img.dtype.name)
    img_unit8 = img_as_ubyte(img)
    print(img_unit8.dtype.name)
Ejemplo n.º 27
0
def main():

    im = Image.open('square.png')

    im = im.convert('L')
    data = np.array(im)
    print(data[1, 1])

    data = chelsea()[..., 0]

    plot_polar_image(data, origin=None)
    #plot_polar_image(data, (100,100))
    #plot_directional_intensity(data, origin=None)

    plt.show()
Ejemplo n.º 28
0
def test_apply_parallel_rgb(depth, chunks, dtype):
    cat = data.chelsea().astype(dtype) / 255.

    func = color.rgb2ycbcr
    cat_ycbcr_expected = func(cat)
    cat_ycbcr = apply_parallel(func,
                               cat,
                               chunks=chunks,
                               depth=depth,
                               dtype=dtype,
                               multichannel=True)

    assert_equal(cat_ycbcr.dtype, cat.dtype)

    assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)
Ejemplo n.º 29
0
def main():
    cat = data.chelsea()
    print(type(cat))
    print(cat.shape)

    # Select reddish pixels
    mask_reddish = cat[:, :, 0] > 160

    # Change to green
    cat[mask_reddish] = [0, 255, 0]

    # Resize image
    new_image = skimage.transform.resize(cat, (128, 256, 3))
    skimage.io.imsave('mycat.png', new_image)
    skimage.io.imshow(new_image)
def encoder():
    block_size = 8
    img = data.chelsea()
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #cv2.imshow('input image', img)
    #cv2.waitKey(0)
    # get size of the image
    [h, w] = img.shape
    # compute number of blocks by diving height and width of image by block size
    h = np.float32(h)
    w = np.float32(w)
    nbh = math.ceil(h / block_size)
    nbh = np.int32(nbh)
    nbw = math.ceil(w / block_size)
    nbw = np.int32(nbw)

    H = block_size * nbh
    W = block_size * nbw

    padded_img = np.zeros((H, W))
    for i in range(h):
        for j in range(w):
            pixel = img[i, j]
            padded_img[i, j] = pixel

    #cv2.imshow('input padded image', np.uint8(padded_img))
    for i in range(nbh):
        row_ind_1 = i * block_size
        # Compute end row index of the block
        row_ind_2 = row_ind_1 + block_size
        for j in range(nbw):
            col_ind_1 = j * block_size
            col_ind_2 = col_ind_1 + block_size
            block = padded_img[row_ind_1:row_ind_2, col_ind_1:col_ind_2]
            DCT = cv2.dct(block)
            reordered = zigzag(DCT)
            reshaped = np.reshape(reordered, (block_size, block_size))
            padded_img[row_ind_1:row_ind_2, col_ind_1:col_ind_2] = reshaped

    #cv2.imshow('encoded image', np.uint8(padded_img))

    np.savetxt('./encoded.txt', padded_img)
    np.savetxt('./size.txt', [h, w, block_size])
    plt.subplot(211), plt.imshow(img, cmap='gray')
    plt.title('origin')
    plt.subplot(212), plt.imshow(padded_img, cmap='gray')
    plt.title('after padded')
    plt.show()
Ejemplo n.º 31
0
def test_structural_similarity_multichannel_chelsea():
    # color image example
    Xc = cp.asarray(data.chelsea())
    sigma = 15.0
    Yc = cp.clip(Xc + sigma * cp.random.randn(*Xc.shape), 0, 255)
    Yc = Yc.astype(Xc.dtype)

    # multichannel result should be mean of the individual channel results
    mssim = structural_similarity(Xc, Yc, multichannel=True)
    mssim_sep = [
        float(structural_similarity(Yc[..., c], Xc[..., c]))
        for c in range(Xc.shape[-1])
    ]
    assert_almost_equal(mssim, np.mean(mssim_sep))

    # structural_similarity of image with itself should be 1.0
    assert_equal(structural_similarity(Xc, Xc, multichannel=True), 1.0)
Ejemplo n.º 32
0
def image():
    # sample image from scikit-image
    return chelsea()
Ejemplo n.º 33
0
Some signals can only be observed modulo 2*pi, and this can also apply to
two- and three dimensional images. In these cases phase unwrapping is
needed to recover the underlying, unwrapped signal. In this example we will
demonstrate an algorithm [1]_ implemented in ``skimage`` at work for such a
problem. One-, two- and three dimensional images can all be unwrapped using
skimage. Here we will demonstrate phase unwrapping in the two dimensional case.
"""

import numpy as np
from matplotlib import pyplot as plt
from skimage import data, img_as_float, color, exposure
from skimage.restoration import unwrap_phase


# Load an image as a floating-point grayscale
image = color.rgb2gray(img_as_float(data.chelsea()))
# Scale the image to [0, 4*pi]
image = exposure.rescale_intensity(image, out_range=(0, 4 * np.pi))
# Create a phase-wrapped image in the interval [-pi, pi)
image_wrapped = np.angle(np.exp(1j * image))
# Perform phase unwrapping
image_unwrapped = unwrap_phase(image_wrapped)

fig, ax = plt.subplots(2, 2)
ax1, ax2, ax3, ax4 = ax.ravel()

fig.colorbar(ax1.imshow(image, cmap='gray', vmin=0, vmax=4 * np.pi), ax=ax1)
ax1.set_title('Original')

fig.colorbar(ax2.imshow(image_wrapped, cmap='gray', vmin=-np.pi, vmax=np.pi), ax=ax2)
ax2.set_title('Wrapped phase')
Ejemplo n.º 34
0
BayesShrink
-----------
The BayesShrink algorithm is an adaptive approach to wavelet soft thresholding
where a unique threshold is estimated for each wavelet subband.  This generally
results in an improvement over what can be obtained with a single threshold.

"""
import matplotlib.pyplot as plt

from skimage.restoration import (denoise_wavelet, estimate_sigma)
from skimage import data, img_as_float
from skimage.util import random_noise
from skimage.measure import compare_psnr


original = img_as_float(data.chelsea()[100:250, 50:300])

sigma = 0.12
noisy = random_noise(original, var=sigma**2)

fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5),
                       sharex=True, sharey=True)

plt.gray()

# Estimate the average noise standard deviation across color channels.
sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
# Due to clipping in random_noise, the estimate will be a bit smaller than the
# specified sigma.
print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))
Ejemplo n.º 35
0
def test_chelsea():
    """ Test that "chelsea" image can be loaded. """
    data.chelsea()
from tqdm import tqdm
import os
import numpy as np
import photomosaic as pm
from skimage.io import imsave
from skimage.data import chelsea
from skimage import img_as_float


here = os.path.dirname(__file__)
POOL_PATH = '/tmp/photomosaic-docs-pool/pool.json'
pool = pm.import_pool(os.path.join(POOL_PATH))

image = img_as_float(chelsea())
converted_img = pm.perceptual(image)
scaled_img = pm.rescale_commensurate(converted_img, grid_dims=(30, 30),
                                     depth=0)
tiles = pm.partition(scaled_img, grid_dims=(30, 30), depth=0)
tile_colors = [np.mean(scaled_img[tile].reshape(-1, 3), 0)
               for tile in tiles]
match = pm.simple_matcher(pool)
matches = [match(tc) for tc in tile_colors]
canvas = np.ones_like(scaled_img)  # white canvas
mos = pm.draw_mosaic(canvas, tiles, matches)

imsave(os.path.join(here, '..', '_static', 'generated_images',
                    'no-palette-adjustment.png'), mos)

adapted_img = pm.adapt_to_pool(converted_img, pool)
imsave(os.path.join(here, '..', '_static', 'generated_images',
                    'adapted-chelsea.png'), pm.rgb(adapted_img))
Ejemplo n.º 37
0
from skimage import data
from skimage.restoration import denoise_tv_chambolle
from skimage.util import img_as_float
from numpy import random, clip

from skimage.viewer import ImageViewer
from skimage.viewer.widgets import (Slider, CheckBox, OKCancelButtons,
                                    SaveButtons)
from skimage.viewer.plugins.base import Plugin


image = img_as_float(data.chelsea())
sigma = 30/255.

image = image + random.normal(loc=0, scale=sigma, size=image.shape)
image = clip(image, 0, 1)
viewer = ImageViewer(image)

plugin = Plugin(image_filter=denoise_tv_chambolle)
plugin += Slider('weight', 0.01, 5, value=0.3, value_type='float')
plugin += Slider('n_iter_max', 1, 100, value=20, value_type='int')
plugin += CheckBox('multichannel', value=True)
plugin += SaveButtons()
plugin += OKCancelButtons()

viewer += plugin
viewer.show()
Ejemplo n.º 38
0
from skimage import data
from skimage.viewer import ImageViewer
from skimage.viewer.plugins.lineprofile import LineProfile


image = data.chelsea()
viewer = ImageViewer(image)
viewer += LineProfile()
line, rgb_profiles = viewer.show()[0]
Ejemplo n.º 39
0
import os
import photomosaic as pm


here = os.path.dirname(__file__)
POOL_PATH = '/tmp/photomosaic-docs-pool/pool.json'
pool = pm.import_pool(os.path.join(POOL_PATH))

# Load a sample image
from skimage import data
img = data.chelsea()  # cat picture!
# Create a mosiac with 15x15 tiles.
mos = pm.basic_mosaic(img, pool, (30, 30), depth=1)
from skimage.io import imsave
imsave(os.path.join(here, '..', '_static', 'generated_images', 'basic-depth1.png'), mos)
Ejemplo n.º 40
0
import os
from skimage.data import chelsea
from skimage.io import imsave


here = os.path.dirname(__file__)
img = chelsea()
imsave(os.path.join(here, '..', '_static', 'generated_images', 'chelsea.png'),
       img)
Ejemplo n.º 41
0
from skimage import data
from paper import savefig

import matplotlib.pyplot as plt
plt.imshow(data.chelsea())

savefig('fig_chelsea.png')