Exemplo n.º 1
0
    def __init__(self, objects, method='tifffile', debug=False, **kwargs):
        """ initialize ImageBase class """
        # set debug flag
        self._debug = debug

        # file information
        if isinstance(objects, np.ndarray) or isinstance(objects, pims.Frame):
            if objects.ndim == 3:
                self._meta = Meta('temp.tif')
                self._meta.update_dim(objects.shape[0], objects.shape[1], objects.shape[2])
                self._images = pims.Frame(objects)
            elif self._raw_images.ndim == 2:
                self._meta = Meta('temp.png')
                self._meta.update_dim(1, objects.shape[0], objects.shape[1])
                self._images = pims.Frame(objects)
        elif isinstance(objects, ImageBase):
            self._meta = ImageBase._meta
            self._images = objects._images
        elif isinstance(objects, str):
            self._meta, self._images = self.open(objects, method=method)

        self._curframe = 0
        self._single = True if self._meta['frameN'] == 1 else False

        # cache 
        self._raw_images = self._images.copy()  
        self._imgMean = []
        self._imgMax = []
        self._imgMin = []
        self._imgMedian = []
Exemplo n.º 2
0
 def get_frame(self, i):
     # Access the data you need and get it into a numpy array.
     # Then return a Frame like so:
     image = self.z_data[i]
     if self.channel == "Bias":
         return pims.Frame(image, frame_no=i)
     else:
         v_min, v_max = np.percentile(image, (0.2, 99.8))
         image = exposure.rescale_intensity(image, in_range=(v_min, v_max))
         #             image = resize(image, self.frame_shape)
         return pims.Frame(image, frame_no=i)
Exemplo n.º 3
0
    def box_view(self, box_number=0):
        """ show box area """
        if len(self.box_arr_) == 0:
            print("... use find_contour first")
            return False

        if box_number in range(len(self.box_arr_)):
            x0, y0, x1, y1 = self.box_arr_[box_number]
            if len(self._newimages) > 0:
                return pims.Frame(self._newimages[:, y0:y1, x0:x1])
            else:
                imgs = np.array(self._images[:])
                return pims.Frame(imgs[:, y0:y1, x0:x1])
Exemplo n.º 4
0
def locate_feature(image_path, particle_size, minmass):

    #image = plt.imread(image_path)
    image = cv.imread(
        image_path, -1
    )  # using cv2 https://stackoverflow.com/questions/18446804/python-read-and-write-tiff-16-bit-three-channel-colour-images

    image = image[8:-1, :]  # crop out noise

    # rotate by 180 (fudge)
    #image = np.rot90(image, 2)
    image = np.fliplr(image)

    frame = pims.Frame(image)

    # plt.figure(0)
    # plt.imshow(image)

    f = tp.locate(frame, particle_size, minmass=minmass)

    # plt.figure(1)
    # tp.annotate(f, frame)
    # plt.show(block=False)
    #
    # fig, ax = plt.subplots()
    # ax.hist(f['mass'], bins=20)
    # plt.show(block=False)

    return f
Exemplo n.º 5
0
def _exposure(img, method='adapt', intensity=-1, debug=False):
    """ preprocess image mostly by renormalization method: contrast, equalization, adapt, gamma, sigmoid """
    import skimage.exposure

    # histogram filter
    if method == 'contrast':
        if debug: print('... contrast histogram')
        if 0 < intensity < 49:
            p2_f, p98_f = intensity, 100 - intensity
        else:
            p2_f, p98_f = 2, 98
        p2, p98 = np.percentile(img, (p2_f, p98_f))
        U = skimage.exposure.rescale_intensity(img, in_range=(p2, p98))

    elif method == 'equalization':
        if debug: print('... global equalize')
        U = skimage.exposure.equalize_hist(img)

    elif method == 'adapt':
        if debug: print('... contrast limited adaptive histogram equalization (CLAHE)')
        if intensity == -1: intensity = int(img.shape[0]/8)
        U = skimage.exposure.equalize_adapthist(_rescale_to_dtype(img, 'uint16'), kernel_size=intensity, clip_limit=0.03)

    elif method == 'local':
        if debug: print('... local histogram equalization')
        if intensity == -1: intensity = 30
        from skimage.morphology import disk
        from skimage.filters import rank
        selem = disk(intensity)
        U = rank.equalize(_rescale_to_dtype(img, 'uint8'), selem=selem)

    elif method == 'gamma':
        if debug: print('... gamma equalize')
        if intensity == -1: intensity = 0.80
        U = skimage.exposure.adjust_gamma(img, gamma=intensity)

    elif method == 'sigmoid':
        if debug: print('... sigmoid equalize')
        if intensity == -1: intensity = 0.5
        U = skimage.exposure.adjust_sigmoid(img, cutoff=intensity)

    else:
        print(_operation_list("exposure"))
        U = img

    if skimage.exposure.is_low_contrast(U):
        print('... low contrast image')

    return pims.Frame(U)
Exemplo n.º 6
0
    def getframe(self, frame=-1, dtypes='pims'):
        """ get frame """

        if dtypes in ['uint8', 'uint16', 'int32', 'float', 'orig']:
            if self._single:
                self._images = _rescale_to_dtype(self._raw_images, dtypes)
            else:
                img = self._raw_images[frame, :, :]
                self._images[frame, :, :] = _rescale_to_dtype(img, dtypes)

        img = self[frame]

        if self._debug: print('... getframe [{}]: {}, {}, {}, {}'.format(frame, img.min(), img.mean(), img.max(), img.dtype))

        return pims.Frame(img)
Exemplo n.º 7
0
def _kmean(img, n_cluster=5, show=False):
    """ show k-mean clustered image """
    img_flat = img.reshape((img.shape[0] * img.shape[1], 1))

    from sklearn.cluster import MiniBatchKMeans

    clt = MiniBatchKMeans(n_clusters=n_cluster)
    labels = clt.fit_predict(img_flat)
    quant = clt.cluster_centers_[labels]

    newimg = quant.reshape((img.shape))

    if show:
        plt.imshow(np.hstack((img, newimg)))
        plt.show()
        print(clt.cluster_centers_)

    return (pims.Frame(newimg), clt.cluster_centers_)
Exemplo n.º 8
0
def locate_feature_calibrate(image_path, particle_size, minmass):

    #image = plt.imread(image_path, format='TIFF')
    image = cv.imread(
        image_path, -1
    )  # using cv2 https://stackoverflow.com/questions/18446804/python-read-and-write-tiff-16-bit-three-channel-colour-images

    #image = image[8:-1, :]  # crop out noise
    frame = pims.Frame(image)

    plt.figure(0)
    plt.imshow(image)

    f = tp.locate(frame, particle_size, minmass=minmass)

    plt.figure(1)
    tp.annotate(f, frame, plot_style={'markersize': 10, 'markeredgewidth': 1})
    plt.show(block=True)

    fig, ax = plt.subplots()
    ax.hist(f['mass'], bins=20)
    plt.show(block=True)

    return f
Exemplo n.º 9
0
 def processInput(img):
     fno = img.frame_no
     img = 255 / (mx - md) * (img - md)
     edges = np.sqrt(scharr_h(img)**2 + scharr_v(img)**2)
     return pims.Frame(np.uint8(edges), frame_no=fno + 1)
Exemplo n.º 10
0
def box(letter):
    return pims.Frame(np.array(letter))
Exemplo n.º 11
0
 def get_frame_2D(self, **ind):
     metadata = {i: ind[i] for i in ind}
     im = np.array([[ind[i] for i in sorted(ind)]])
     return pims.Frame(im, metadata=metadata)
Exemplo n.º 12
0
def _denoise(img, method='fastNl', intensity=-1, debug=False, **kwargs):
    """ denoise frame """
    from skimage.restoration import denoise_tv_bregman, denoise_tv_chambolle, denoise_wavelet, denoise_bilateral
    if 'cv2' not in dir(): import cv2

    if method in ['bilateral', 'fastNl']:
        img = _rescale_to_dtype(img, 'uint8')
    elif method == 'deforest':
        img = _rescale_to_dtype(img, 'float')

    if method == 'rof':
        if debug: print('... total-variation denoising using split-Bregman optimization')
        if intensity == -1: intensity = 70
        elif intensity == 'full': intensity = 10
        U = denoise_tv_bregman(img, intensity, **kwargs)

    elif method == 'tvl':
        if debug: print('... total-variation denoising on n-dimensional images')
        if intensity == -1: intensity = 0.01
        elif intensity == 'full': intensity = 0.05
        U = denoise_tv_chambolle(img, intensity, **kwargs)

    elif method == 'wavelet':
        if debug: print('... perform wavelet denoising')
        if intensity == -1: intensity = 1
        elif intensity == 'full': intensity = 3
        U = denoise_wavelet(img, wavelet_levels=intensity, **kwargs)

    elif method == 'bilateral2':
        if debug: print('... denoise image using bilateral filter')
        if intensity == -1: intensity = 1
        elif intensity == 'full': intensity = 3
        U = denoise_bilateral(img, sigma_spatial=intensity, multichannel=False, **kwargs)

    elif method == 'deforest':
        if intensity == -1: intensity = 3.0
        elif intensity == 'full': intensity = 3.0
        ng0 = NoiseGater(img, gamma=intensity, debug=debug, **kwargs)
        U = ng0.clean()

    elif method == 'bilateral':
        if intensity == -1: intensity = 10
        elif intensity == 'full': intensity = 75
        U = cv2.bilateralFilter(img, 5, intensity, intensity)

    elif method == 'gaussian':
        if intensity == -1: intensity = 3
        elif intensity == 'full': intensity = 7
        U = cv2.GaussianBlur(img, (intensity, intensity), 0)

    elif method == 'median':
        if intensity == -1: intensity = 3
        elif intensity == 'full': intensity = 7
        U = cv2.medianBlur(img, intensity)

    elif method == 'fastNl':
        if intensity == -1: intensity = 5
        elif intensity == 'full': intensity = 9
        U = cv2.fastNlMeansDenoising(img, h=intensity, **kwargs)

    else:
        print(_operation_list("denoise"))
        U = img

    return pims.Frame(U)
Exemplo n.º 13
0
    def _filters(self, img, method='', intensity=-1, debug=False, **kwargs):
        """ apply other filters """
        if 'cv2' not in dir(): import cv2

        if method == 'sharpen':
            if debug: print('... sharpen')
            if intensity == -1: intensity = 0.3
            elif intensity == 'full': intensity = 0.5
            img = _rescale_to_dtype(img, 'float')
            blur = kwargs.pop('blur', 3)
            img_g = cv2.GaussianBlur(img, (blur, blur), 0)
            U = img + (img - img_g) * intensity

        elif method == 'median3d':
            if debug: print('... background subtraction by median z-projection')
            if intensity == -1: intensity = self.tmedian()
            U = _rescale_to_dtype(img - intensity, 'float')

        elif method == 'min3d':
            if debug: print('... background subtraction by median z-projection')
            if intensity == -1: intensity = self.tmin()
            U = _rescale_to_dtype(img - intensity, 'float')

        elif method == 'mean3d':
            if debug: print('... background subtraction by median z-projection')
            if intensity == -1: intensity = self.tmean()
            U = _rescale_to_dtype(img - intensity, 'float')

        elif method == 'sobel':
            if debug: print('... edge detection using sobel filter')
            from skimage.filters import sobel
            U = sobel(img)

        elif method == 'canny':
            if debug: print('... edge detection using canny filter')
            img = _rescale_to_dtype(img, 'uint8')
            U = cv2.Canny(img, 50, 200, None, 3)

        elif method == 'prewitt':
            if debug: print('... edge detection using prewitt filter')
            from skimage.filters import prewitt
            U = prewitt(img)

        elif method == 'roberts':
            if debug: print('... edge detection using roberts filter')
            from skimage.filters import roberts
            U = roberts(img)

        elif method == 'scharr':
            if debug: print('... edge detection using scharr filter')
            from skimage.filters import scharr
            U = scharr(img)

        elif method == 'laplace':
            if debug: print('... edge detection using laplace filter')
            from skimage.filters import laplace
            ksize = kwargs.pop('ksize', 3)
            U = laplace(img, ksize=ksize)

        elif method == 'removecell':
            if debug: print('... cell remover using kmean filter')
            if intensity == -1: intensity = 0.3
            U = self._remove_cell(img, percentile=intensity, **kwargs)

        else:
            print(_operation_list("filters"))
            U = img

        return pims.Frame(U)
Exemplo n.º 14
0
    def asframe(self):
        """ return pims Frame object """

        return pims.Frame(self._images)