示例#1
0
def DoG(image_name, Test=False, perceptron=False):
    train_path = "/home/rajiv/Documents/lectures/BIC/project_conv_sdnn/datasets/TrainingSet/Face/"
    test_path = "/home/rajiv/Documents/lectures/BIC/project_conv_sdnn/datasets/TestingSet/faces_labeled/"
    perceptron_path = "/home/rajiv/Documents/lectures/BIC/project_conv_sdnn/datasets/TrainingSet/faces_labeled/"
    if Test:
        image = Image.open(test_path + image_name)
        image = np.array(image.resize((400, 400), Image.BILINEAR))
        filtered_image = difference_of_gaussians(image, 1.5)
        filtered_image = np.expand_dims(filtered_image, axis=0)
        filtered_image = np.expand_dims(filtered_image, axis=0)
        return filtered_image
    elif perceptron:
        image = Image.open(perceptron_path + image_name)
        image = np.array(image.resize((400, 400), Image.BILINEAR))
        filtered_image = difference_of_gaussians(image, 1.5)
        filtered_image = np.expand_dims(filtered_image, axis=0)
        filtered_image = np.expand_dims(filtered_image, axis=0)
        return filtered_image
    else:
        image = Image.open(train_path + image_name)
        image = np.array(image.resize((400, 400), Image.BILINEAR))
        filtered_image = difference_of_gaussians(image, 1.5)
        filtered_image = np.expand_dims(filtered_image, axis=0)
        filtered_image = np.expand_dims(filtered_image, axis=0)
        return filtered_image
def get_filted(img, k, sigma):
    filted = difference_of_gaussians(img, sigma, k * sigma)
    filter_img = filted * window('hann', img.shape)
    result = fftshift(np.abs(fftn(filter_img)))
    result = cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX)
    result = np.uint8(result * 255.)
    return result
def mask_area(img, scale):
    class Map_coord():
        """CV2 class for storing left button clicks
                    
      Notes
      ----------
      Loads button clicks through cv2 and saves them in a list instantiated with the class
      
      """
        def __init__(self):
            self.points = []

        def select_point(self, event, x, y, flags, param):
            if event == cv2.EVENT_LBUTTONDOWN:
                self.points.append([x, y])
                cv2.drawMarker(frame, (x, y), (0, 0, 0),
                               markerType=cv2.MARKER_CROSS,
                               markerSize=15,
                               thickness=2)
                cv2.imshow("image", frame)

    #Instantiate class for getting button clicks
    coordinateStore = Map_coord()
    frame = normalize(difference_of_gaussians(img, 1, 5))
    frame = cv2.resize(frame, (0, 0), fx=scale, fy=scale)
    cv2.imshow("image", frame)
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", coordinateStore.select_point)

    while (1):
        cv2.imshow('image', frame)
        key = cv2.waitKey(1) & 0xFF

        if key == ord("q"):
            break

    cv2.destroyAllWindows()

    coords = []

    for elements in coordinateStore.points:
        coords.append(list(elements)[::])

    for obj in coords:
        if obj in sorted(coords, key=lambda l: l[1])[:2]:
            obj[1] = 0
        if obj in sorted(coords, key=lambda l: l[1])[-2:]:
            obj[1] = frame.shape[0]

    coords = [np.array(coords)]

    if len(coords[0]) > 4:
        stencil = np.zeros(frame.shape).astype(frame.dtype)
        color = [255, 255, 255]
        cv2.fillPoly(stencil, coords, color)
        return imutils.resize(stencil, width=img.shape[1], height=img.shape[0])

    else:
        return None
示例#4
0
def test_auto_sigma2(s):
    image = np.random.rand(10, 10)
    im1 = gaussian(image, s, preserve_range=True)
    s2 = 1.6 * np.array(s)
    im2 = gaussian(image, s2, preserve_range=True)
    dog = im1 - im2
    dog2 = difference_of_gaussians(image, s, s2)
    assert np.allclose(dog, dog2)
示例#5
0
def test_dog_invalid_sigma_dims():
    image = np.ones((5, 5, 3))
    with pytest.raises(ValueError):
        difference_of_gaussians(image, (1, 2))
    with pytest.raises(ValueError):
        difference_of_gaussians(image, 1, (3, 4))
    with pytest.raises(ValueError):
        with expected_warnings(["`multichannel` is a deprecated argument"]):
            difference_of_gaussians(image, (1, 2, 3), multichannel=True)
    with pytest.raises(ValueError):
        difference_of_gaussians(image, (1, 2, 3), channel_axis=-1)
示例#6
0
def test_difference_of_gaussians(s, s2, channel_axis):
    image = np.random.rand(10, 10)
    if channel_axis is not None:
        n_channels = 5
        image = np.stack((image, ) * n_channels, channel_axis)
    im1 = gaussian(image, s, preserve_range=True, channel_axis=channel_axis)
    im2 = gaussian(image, s2, preserve_range=True, channel_axis=channel_axis)
    dog = im1 - im2
    dog2 = difference_of_gaussians(image, s, s2, channel_axis=channel_axis)
    assert np.allclose(dog, dog2)
 def best_z(self, crop):
     """
     Returns crop Z plane with the max average intensity in a central 3x3 square after applying a bandpass filter 
     """
     crop_pad = self.crop_pad
     return np.argmax(
         np.mean(difference_of_gaussians(crop, 1,
                                         7)[:, crop_pad - 1:crop_pad + 2,
                                            crop_pad - 1:crop_pad + 2],
                 axis=(1, 2)))
示例#8
0
    def _find_angle(img_original, img_deformed):
        # First, band-pass filter both images
        image = img_original
        rts_image = img_deformed
        image = difference_of_gaussians(image, 5, 15)
        rts_image = difference_of_gaussians(rts_image, 5, 15)
        # window images
        wimage = image * window('hann', image.shape)
        rts_wimage = rts_image * window('hann', rts_image.shape)

        # work with shifted FFT magnitudes
        image_fs = np.abs(fftshift(fft2(wimage)))
        rts_fs = np.abs(fftshift(fft2(rts_wimage)))

        # Create log-polar transformed FFT mag images and register
        shape_or = image_fs.shape
        shape_def = rts_fs.shape

        radius_or = shape_or[0] // 8
        radius_def = shape_def[0] // 8  # only take lower frequencies
        warped_image_fs = warp_polar(image_fs,
                                     radius=radius_or,
                                     output_shape=shape_or,
                                     scaling='log',
                                     order=0)
        warped_rts_fs = warp_polar(rts_fs,
                                   radius=radius_def,
                                   output_shape=shape_or,
                                   scaling='log',
                                   order=0)

        warped_image_fs = warped_image_fs[:shape_or[
            0], :]  # only use half of FFT
        warped_rts_fs = warped_rts_fs[:shape_or[0], :]
        shifts, error, phasediff = phase_cross_correlation(warped_image_fs,
                                                           warped_rts_fs,
                                                           upsample_factor=10)

        # Use translation parameters to calculate rotation and scaling parameters
        shiftr, shiftc = shifts[:2]
        recovered_angle = (360 / shape_or[0]) * shiftr
        return recovered_angle
示例#9
0
def wavelet(I, level, wavelet="db3", threshold=64.0, hard=True):
    mode = "symmetric"
    result = np.zeros_like(I)
    print(I.shape)
    for i in range(I.shape[0]):
        s = np.zeros_like(result[i, :])
        s[0:I.shape[1], 0:I.shape[2]] = I[i, :]
        arr = np.float32(s)
        print(f"arr.shape {arr.shape}")
        coeffs = wavedec2(arr, wavelet=wavelet, level=7)
        coeffs_H = list(coeffs)

        idx = int(level)

        if hard:
            for idx in range(idx, 7):
                for idx2 in [0, 1, 2]:
                    #print(np.mean(coeffs_H[idx][idx2]), np.max(coeffs_H[idx][idx2]), np.min(coeffs_H[idx][idx2]))
                    coeffs_H[idx][idx2][coeffs_H[idx][idx2] < threshold] = 0

            #coeffs_H[-idx] == tuple([np.zeros_like(v) for v in coeffs_H[-idx]])
        else:
            for idx in range(idx, 0, -1):
                for idx2 in [0, 1, 2]:
                    coeffs_H[idx] = list(coeffs_H[idx])
                    #coeffs_H[idx][idx2] = np.sign(coeffs_H[idx][idx2]) * np.abs(coeffs_H[idx][idx2] + threshold)
                    coeffs_H[idx][idx2][coeffs_H[idx][idx2] <
                                        threshold] = difference_of_gaussians(
                                            coeffs_H[idx][idx2]
                                            [coeffs_H[idx][idx2] < threshold],
                                            1)

        # if hard:
        #     coeffs_H[idx][1][coeffs_H[idx][1] < threshold] = 0
        # else:
        #     coeffs_H[idx][1] = np.sign(coeffs_H[idx][1]) * np.abs(coeffs_H[idx][1] - threshold)

        arr_rec = waverec2(coeffs_H, wavelet=wavelet)
        print(f"arr_rec {arr_rec.shape}")
        result[i, 0:I.shape[1], 0:I.shape[2]] = arr_rec[0:I.shape[1],
                                                        0:I.shape[2]].copy()

    return result
示例#10
0
    def compute_dgfw(
        image: np.ndarray,
        gaussdiff: Sequence[float] = (5, 20),
        windowweight: float = 1,
        windowtype: str = "hann",
    ) -> np.ndarray:
        """Image Difference of Gaussian Filter + Window.

        Parameters
        ----------
        image : numpy.ndarray
            The input image to filter
        gaussdiff : (float, float), optional
            The low and high standard deviations for the gaussian difference band pass filter
        windowweight : float, optional
            weighting factor scaling beween windowed image and image
        windowtype : str, optional
            see `skimage.filters.window` for possible choices

        Returns
        -------
        numpy.ndarray
            modified image with bandpass filter and window applied

        Notes
        -----
        Applying this bandpass and window filter prevents artifacts from image boundaries and
        noise from contributing significantly to the fourier transform. The gaussian
        difference filter can be tuned such that the features relevant for the identification
        of the rotation angle are at the center of the band pass filter.
        """
        image_dgfw = (
            difference_of_gaussians(image, *gaussdiff)
            if gaussdiff[0] < gaussdiff[1]
            else image * 1.0
        )
        image_dgfw *= windowweight * window(windowtype, image.shape) + (
            1 - windowweight
        )
        return cast(np.ndarray, image_dgfw)
 def analyse(self):
    all_wells=[]
    for well in range(self.img_set.sizes['v']):
       self.img_set.default_coords['v'] = well
       res=[]
       if self.mask[well] is not None:
          for img in self.img_set:
             passed=[]
             im=difference_of_gaussians(img, 1, 5)
             blur=gaussian(im, sigma=2)
             black=black_tophat(blur, selem=disk(4))
             thresh=threshold_otsu((black))
             black=black*self.mask[well].astype(bool).astype(int)
             objects=regionprops(ndi.label(black>thresh)[0])
             for obj in objects:
                if obj.area>self.min_area and obj.area<self.max_area:
                   passed.append(obj.area)
             res.append(len(passed))
       else:
          res.append([])
       all_wells.append(res)
    with open("out.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerows(res)
示例#12
0
    def fourier_affine(self, img0, img1, masks=None, verbose=False):
        """Estimate translations by masked normalized
        cross-correlation after fourier transformation

        img0, img1 (numpy.ndarray [height, width]): input images
        masks (tuple): masks for keypoint detection
        verbose (bool): return additional diagnostic values

        Returns:
            np.ndarray or NoneType: affine transform to fit
                img1 onto img0, None if RMSE is > 0.4
            dict: diagnostics (if verbose)
        """
        # preprocess the images
        # First, band-pass filter both images
        low_sigma = 1
        high_sigma = None
        img0_dog = difference_of_gaussians(img0,
                                           low_sigma=low_sigma,
                                           high_sigma=high_sigma)
        img1_dog = difference_of_gaussians(img1,
                                           low_sigma=low_sigma,
                                           high_sigma=high_sigma)

        # find translations masked on non-masked
        if masks is not None:
            assert len((img0, img1)) == len(masks), 'Incorrect number of masks'
            mask0, mask1 = masks
            shifts = phase_cross_correlation(img1_dog,
                                             img0_dog,
                                             reference_mask=mask1,
                                             moving_mask=mask0)
            y_shift, x_shift = shifts[:2]
            if verbose:
                diag = {
                    'low_sigma': low_sigma,
                    'high_sigma': high_sigma,
                    'y_shift_scaled': y_shift,
                    'x_shift_scaled': x_shift
                }

        else:
            shifts, error, phasediff = phase_cross_correlation(
                img1_dog, img0_dog, upsample_factor=10)
            y_shift, x_shift = shifts[:2]

            if verbose:
                diag = {
                    'low_sigma': low_sigma,
                    'high_sigma': high_sigma,
                    'y_shift_scaled': y_shift,
                    'x_shift_scaled': x_shift,
                    'RMSE_shift': error,
                    'phasediff_shift': phasediff
                }

            # if error > 0.4 result is not acceptable
            if error > 0.4:
                return (None, diag) if verbose else None

        translation = np.array([[1, 0, x_shift], [0, 1, y_shift], [0, 0, 1]],
                               dtype=np.float32)

        return (translation, diag) if verbose else translation
示例#13
0
    print(imgname)
    # Load raw image file and read pixel size from metadata
    #filepath = os.path.join(dirpath, imgname)
    with tifffile.TiffFile(filepath) as tif:
        imgraw = tif.pages[0].asarray()  # image as numpy array
        pxs_nm = 1e9 / tif.pages[0].tags['XResolution'].value[
            0]  # pixel size in nm

    # Get binary mask and multiple the pre-processed image with this (should I do this before pre-processing? does it make a difference?).
    binarymap = binary_cell_map(imgraw, pxs_nm=pxs_nm)
    img = imgraw * binarymap

    # Preprocess image with a difference of gaussians filter and a gaussian blurring
    # take the difference of gaussians to minimize faint out of focus noise
    img = skfilt.difference_of_gaussians(img,
                                         low_sigma=0,
                                         high_sigma=difgaus_sigmahi_nm /
                                         pxs_nm)
    img[img < 0] = 0  # remove any negative values in the image
    # gaussian smoothing of the image
    img = ndi.gaussian_filter(img, sm_size_nm / pxs_nm)

    # If necessary: standardize image by dividing by mean+std, to get all images to ~the same range of values (assuming similar intensity distr)
    # Else: multiply by a fix factor to get values to roughly the same range
    if standbool:
        peakthresh = peakthresh_stand_true
        imgmean = np.ma.masked_array(img, ~binarymap).mean()
        imgstd = np.ma.masked_array(img, ~binarymap).std()
        img = np.array(img / (imgmean + imgstd))
    else:
        peakthresh = peakthresh_stand_false
        img = img * multfact
def FFT_SOBEL(channel):
    filtered_image = filters.difference_of_gaussians(channel, 1, 12)
    wimage = filtered_image * filters.window('hann', channel.shape)
    im_f_mag = fftshift(np.abs(fftn(wimage)))
    image = filters.sobel(np.log(im_f_mag))
    return image
def SOBEL_FFT(channel):
    image = filters.sobel(channel)
    image = filters.difference_of_gaussians(image, 0, 12)
    image = image * filters.window('hann', (32, 32))
    image = fftshift(np.abs(fftn(image)))
    return np.log(image)
示例#16
0
def filter_data(data, sigmas=1, sigmab=10):
    output = difference_of_gaussians(data, sigmas, sigmab)
    return output
kwargs = {'sigmas': [0.7], 'mode': 'reflect'}
Gimage = filters.gaussian(Nimage, sigma=0.7)
cv.imwrite(os.path.join(PATH + '2-Gaussian  filter_' + name), Gimage)

GN = cv.normalize(Gimage, None, 0, 255, cv.NORM_MINMAX)
GNN = GN.astype(np.uint8)  ### APPLYING Gaussian smooth filter

Eimage = filters.sobel(GN)
cv.imwrite(os.path.join(PATH + '3- Sobel Edge detection_' + name), Eimage)

Eimage += Nimage
EN = cv.normalize(Eimage, None, 0, 255, cv.NORM_MINMAX)
ENN = EN.astype(np.uint8)  ### APPLYING Sobel edge detection filter

DoG = filters.difference_of_gaussians(Gimage, 0.7)
# cv.imwrite(os.path.join(PATH+'DoG_'+name), DoG)
DoG += Nimage
DoGN = cv.normalize(DoG, None, 0, 255, cv.NORM_MINMAX)
DoGNN = DoGN.astype(np.uint8)  ### APPLYING Difference of Gaussian filter

LoG = ndimage.gaussian_laplace(Gimage, sigma=0.7)
# cv.imwrite(os.path.join(PATH+'LoG_'+name), LoG)
LoG += Nimage
LoGN = cv.normalize(LoG, None, 0, 255, cv.NORM_MINMAX)
LoGNN = LoGN.astype(np.uint8)  ### APPLYING Laplacian of Gaussian filter

GGM = ndimage.gaussian_gradient_magnitude(Gimage, sigma=0.7)
# cv.imwrite(os.path.join(PATH+'GGM_'+name), GGM)
GGM += Nimage
GGMN = cv.normalize(GGM, None, 0, 255, cv.NORM_MINMAX)
示例#18
0
def create_features(image, parameters=None):
    """
    Creates set of features for data classification

    Parameters
    ----------
    image : greyscale image for segmentation
    trainable segmentation parameters

    Returns
    -------
    set of chosen features of the inputted image.
    """
    if parameters == None:
        parameters = trainable_parameters()
    shape = [image.shape[0], image.shape[1], 1]

    image_stack = np.zeros(shape, dtype=np.float16)
    one_im = rescale_intensity(image, out_range = (-1,1))
    temp = util.img_as_ubyte(rescale_intensity(image, out_range=(0,1)))

    if parameters.gaussian[0]:
        new_layer = np.reshape(filters.gaussian(image,parameters.gaussian[1]),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if parameters.diff_gaussian[0]:
        par = parameters.diff_gaussian
        if par[1][0]:
            blur = filters.gaussian(image,par[1][1])
            new_layer = np.reshape(filters.difference_of_gaussians(blur, low_sigma=par[2],high_sigma=par[3]), shape)
        else:
            new_layer = np.reshape(filters.difference_of_gaussians(image, low_sigma=par[2],high_sigma=par[3]), shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if parameters.median[0]:
        par = parameters.median
        if par[1][0]:
            blur = filters.gaussian(one_im,par[1][1])
            new_layer = np.reshape(filters.median(blur, morphology.disk(par[2])),shape)
        else:
            new_layer = np.reshape(filters.median(one_im, morphology.disk(par[2])),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if parameters.minimum[0]:
        par = parameters.minimum
        if par[1][0]:
            blur = filters.gaussian(temp,par[1][1])
            new_layer = np.reshape(filters.rank.minimum(blur, morphology.disk(par[2])),shape)
        else:
            new_layer = np.reshape(filters.rank.minimum(temp, morphology.disk(par[2])),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)
    
    if parameters.maximum[0]:
        par = parameters.maximum
        if par[1][0]:
            blur = filters.gaussian(temp,par[1][1])
            new_layer = np.reshape(filters.rank.maximum(blur, morphology.disk(par[2])),shape)
        else:
            new_layer = np.reshape(filters.rank.maximum(temp, morphology.disk(par[2])),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if parameters.sobel[0]:
        par = parameters.sobel
        if par[1][0]:
            blur = filters.gaussian(image,par[1][1])
            new_layer = np.reshape(filters.sobel(blur),shape)
        else:
            new_layer = np.reshape(filters.sobel(image),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if parameters.hessian[0]:
        par = parameters.hessian
        if par[1][0]:
            blur = filters.gaussian(image,par[1][1])
            new_layer = np.reshape(filters.hessian(blur),shape)
        else:
            new_layer = np.reshape(filters.hessian(image),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if parameters.laplacian[0]:
        par = parameters.laplacian
        if par[1][0]:
            blur = filters.gaussian(image,par[1][1])
            new_layer = np.reshape(laplacian(blur),shape)
        else:
            new_layer = np.reshape(filters.laplacian(image),shape)
        image_stack = np.concatenate((image_stack, new_layer), axis=2)

    if True in parameters.membrane[1:]:
        par = parameters.membrane
        if par[0][0]:
            temp_im = filters.gaussian(image,par[0][1])
        else:
            temp_im = image
        indexes = np.asarray(par[1:], dtype=np.bool_)
        mem_layers = membrane_projection(image)[:,:,indexes]

        if par[1:] == [1,1,1,1,1,1]:
            mem_layers = np.squeeze(mem_layers)
        image_stack = np.append(image_stack, mem_layers, axis=2)
    
    return image_stack[:,:,1:]
示例#19
0
filtering.
"""

######################################################################
# Denoise image and reduce shadows
# ================================

import matplotlib.pyplot as plt
import numpy as np
from skimage.data import gravel
from skimage.filters import difference_of_gaussians, window
from scipy.fftpack import fftn, fftshift

image = gravel()
wimage = image * window('hann', image.shape)  # window image to improve FFT
filtered_image = difference_of_gaussians(image, 1, 12)
filtered_wimage = filtered_image * window('hann', image.shape)
im_f_mag = fftshift(np.abs(fftn(wimage)))
fim_f_mag = fftshift(np.abs(fftn(filtered_wimage)))

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(8, 8))
ax[0, 0].imshow(image, cmap='gray')
ax[0, 0].set_title('Original Image')
ax[0, 1].imshow(np.log(im_f_mag), cmap='magma')
ax[0, 1].set_title('Original FFT Magnitude (log)')
ax[1, 0].imshow(filtered_image, cmap='gray')
ax[1, 0].set_title('Filtered Image')
ax[1, 1].imshow(np.log(fim_f_mag), cmap='magma')
ax[1, 1].set_title('Filtered FFT Magnitude (log)')
plt.show()
示例#20
0
print()
print(f'Expected value for scaling difference: {scale}')
print(f'Recovered value for scaling difference: {shift_scale}')

######################################################################
# Register rotation and scaling on a translated image - Part 2
# =================================================================
#
# We next show how rotation and scaling differences, but not translation
# differences, are apparent in the frequency magnitude spectra of the images.
# These differences can be recovered by treating the magnitude spectra as
# images themselves, and applying the same log-polar + phase correlation
# approach taken above.

# First, band-pass filter both images
image = difference_of_gaussians(image, 5, 20)
rts_image = difference_of_gaussians(rts_image, 5, 20)

# window images
wimage = image * window('hann', image.shape)
rts_wimage = rts_image * window('hann', image.shape)

# work with shifted FFT magnitudes
image_fs = np.abs(fftshift(fft2(wimage)))
rts_fs = np.abs(fftshift(fft2(rts_wimage)))

# Create log-polar transformed FFT mag images and register
shape = image_fs.shape
radius = shape[0] // 8  # only take lower frequencies
warped_image_fs = warp_polar(image_fs,
                             radius=radius,
image = io.imread("images/sample.jpg")
image_gray = rgb2gray(image)

fig, axes = plt.subplots(3, 5, figsize=(16, 9))
fig.suptitle('Increase in value of Sigma(σ) --------->')

sigma = 1
#LoG
#gaussian filter with sigma value as second arguement
img_g = gaussian(image_gray, sigma)
#laplacian
img_log = laplace(img_g, ksize=3, mask=None)

#DoG
sigma2 = sigma * sqrt(2)
img_dog = difference_of_gaussians(image_gray, sigma, sigma2)

axes[0, 0].imshow(image)
axes[0, 0].set_title('Image')
axes[1, 0].imshow(img_log)
axes[1, 0].set_title('LoG, σ = 1')
axes[2, 0].imshow(img_dog)
axes[2, 0].set_title('DoG, σ1 = 1, σ2 = √2')

sigma = 0.1
y= 1
#threshold part: edge detection
while sigma < 1.7:
    img_g = gaussian(image_gray, sigma)
    # laplacian
    img_log = laplace(img_g, ksize=3, mask=None)
示例#22
0
def frequency_filters(img,filter):
    rows, cols = img.shape
    crow, ccol = int(rows / 2), int(cols / 2)  # center
    fft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
    fft_shift = np.fft.fftshift(fft)
    if filter == 'lp':
        # Circular LPF mask, center circle is 1, remaining all zeros
        mask = np.zeros((rows, cols, 2), np.uint8)
        r = 80
        center = [crow, ccol]
        x, y = np.ogrid[:rows, :cols]
        mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r*r
        mask[mask_area] = 1

        # apply mask and inverse FFT
        fshift = fft_shift * mask
        fshift_mask_mag = 2000 * np.log(cv2.magnitude(fshift[:, :, 0], fshift[:, :, 1]))
        f_ishift = np.fft.ifftshift(fshift)
        img_back = cv2.idft(f_ishift)
        img = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])
    
    elif filter == 'hp':
        # Circular HPF mask, center circle is 0, remaining all ones 
        mask = np.ones((rows, cols, 2), np.uint8) 
        r = 150 
        center = [crow, ccol] 
        x, y = np.ogrid[:rows, :cols] 
        mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r*r 
        # apply mask and inverse FFT 
        fshift = fft_shift * mask 
        fshift_mask_mag = 50 * np.log(cv2.magnitude(fshift[:, :, 0], fshift[:, :, 1])) 
        f_ishift = np.fft.ifftshift(fshift) 
        img_back = cv2.idft(f_ishift) 
        img = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])
            
    elif filter == 'bp':
        # Concentric BPF mask,with are between the two cerciles as one's, rest all zero's.
        mask = np.zeros((rows, cols, 2), np.uint8)
        r_out = 80
        r_in = 5
        center = [crow, ccol]
        x, y = np.ogrid[:rows, :cols]
        mask_area = np.logical_and(((x - center[0]) ** 2 + (y - center[1]) ** 2 >= r_in ** 2),
                                ((x - center[0]) ** 2 + (y - center[1]) ** 2 <= r_out ** 2))
        mask[mask_area] = 1
        # apply mask and inverse FFT
        fshift = fft_shift * mask
        fshift_mask_mag = 2000 * np.log(cv2.magnitude(fshift[:, :, 0], fshift[:, :, 1]))
        f_ishift = np.fft.ifftshift(fshift)
        img_back = cv2.idft(f_ishift)
        img = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])
    
    elif filter == 'bp-1':
        wimage = img * window('hann', img.shape)  # window image to improve FFT
        filtered_image = difference_of_gaussians(img, 1, 1)
        filtered_wimage = filtered_image * window('hann', img.shape)
        im_f_mag = fftshift(np.abs(fftn(wimage)))
        fim_f_mag = fftshift(np.abs(fftn(filtered_wimage)))
        img = filtered_image
    
    elif filter == 'bp-2':
        wimage = img * window('hann', img.shape)  # window image to improve FFT
        filtered_image = difference_of_gaussians(img, 10)
        filtered_wimage = filtered_image * window('hann', img.shape)
        im_f_mag = fftshift(np.abs(fftn(wimage)))
        fim_f_mag = fftshift(np.abs(fftn(filtered_wimage)))
        img = filtered_image

    return cv2.normalize(img,None,0,255,cv2.NORM_MINMAX,dtype=cv2.CV_8U )
示例#23
0

# Demonstration

# define path of the test set
test_path = os.path.dirname(dirname(
    realpath(__file__))) + '\BIC Project\images'

# import test set
test_set = images_import(test_path)

# display example image
import matplotlib.pyplot as plt
plt.imshow(test_set[0], cmap='gray')
plt.show()

# apply DoG filter
dog = difference_of_gaussians(test_set[0], 1.5)

# display example image after filter
plt.imshow(dog, cmap='gray')
plt.show()

# temporal encoding example
window = 5
layers = 1
temp_test = temporal_encoding(dog, window, layers)

for i in range(window):
    plt.imshow(temp_test[:, :, i], cmap='Greys')
    plt.show()
示例#24
0
        img.seek(I)
        imgArray[:, :, I] = np.asarray(img)
    img.close()
    return (imgArray)


data = loadtiffs('test.tif')
data = data.squeeze()

outb = sk.gaussian(data, 10)
outs = sk.gaussian(data, 1)

plt.subplot(2, 2, 1)
plt.imshow(data)

plt.subplot(2, 2, 2)
plt.imshow(outb)

plt.subplot(2, 2, 3)
plt.imshow(outs)

plt.subplot(2, 2, 4)
plt.imshow(outs - outb)

plt.show()

outd = sk.difference_of_gaussians(data, 1, 10)

plt.imshow(outd)
plt.show()
示例#25
0
def enhance_edges(im):
    im_edge_enh = difference_of_gaussians(im, 1.5, multichannel=False) * 100#, mode='constant', cval=1)
    #im_edge_enh = cv2.normalize(im_edge_enh,None,alpha=0,beta=255, norm_type=cv2.NORM_MINMAX).astype('uint8')
    im_edge_enh = exposure.rescale_intensity(im_edge_enh.astype('int8'), out_range=(0,255)).astype('uint8')
    
    return im_edge_enh
img_paths = glob.glob(
    "D:/Datasets/PlantVillage/Pepper__bell___Bacterial_spot/*.JPG")
r = 50
N = 3

for path in img_paths:
    img = cv.imread(path)
    img = cv.cvtColor(img, cv.COLOR_BGR2RGB)

    svd_decolor = TruncSVDdecolor(img, r)
    svd_decolor = ndimage.convolve(svd_decolor, np.ones((N, N)) / (N * N))
    # print(np.unique(svd_decolor))

    hue = cv.cvtColor(img, cv.COLOR_RGB2HSV)[:, :, 0]
    hue = filters.difference_of_gaussians(hue, low_sigma=4, high_sigma=5)
    # print(np.unique(hue))

    exr_img = apply_ExR(img)
    exr_img = ndimage.convolve(exr_img, np.ones((N, N)) / (N * N))
    # print(np.unique(exr_img))

    accf = (0.1 * exr_img) + svd_decolor + hue
    accf = accf * 0.5
    # accf_bin = accf < filters.threshold_mean(accf)

    plt.subplot(221)
    plt.title("SVD Decolor")
    plt.axis('off')
    plt.imshow(svd_decolor, cmap='gray')
    plt.subplot(222)
示例#27
0
def test_dog_invalid_sigma2():
    image = np.ones((3, 3))
    with pytest.raises(ValueError):
        difference_of_gaussians(image, 3, 2)
    with pytest.raises(ValueError):
        difference_of_gaussians(image, (1, 5), (2, 4))
示例#28
0
    y, x, r = blob
    c = plt.Circle((x, y), r, color='lime', linewidth=1, fill=False)
    ax.add_patch(c)
# plt.imshow(mask, cmap = plt.cm.gray)
# plt.figure()
# n, bins, patches = plt.hist(blobs_log[:, 2])

#############
# LABEL DETECTION
#############
#dilate to avoid loosing small elements on edges
#image_dil = dilation(stars_gray, np.ones((5,5)))
#make the image smooth
#image_gauss = gaussian(stars_gray, sigma=1.5)
#automatic threshold
stars_filtered = difference_of_gaussians(stars_gray, low_sigma=1, high_sigma=7)
#print("mean values : " ,stars_gray.mean())
#find contour
contours = find_contours(stars_filtered, level=0.1)

# Display the image and plot all contours found
fig_c, ax_c = plt.subplots()
ax_c.imshow(stars_gray, interpolation='nearest', cmap=plt.cm.gray)

for n, contour in enumerate(contours):
    ax_c.plot(contour[:, 1], contour[:, 0], linewidth=1)
print("Number of contours counted : ", len(contours))
ax_c.axis('image')
ax_c.set_xticks([])
ax_c.set_yticks([])
plt.show()