Exemplo n.º 1
0
def modify(img):
    """Randomly modify an image
    
    This is a preprocessing step for training an OCR classifier. It takes
    in an image and casts it to greyscale, reshapes it, and adds some
    (1) rotations, (2) translations and (3) noise.
    
    If more efficiency is needed, we could factor out some of the initial
    nonrandom transforms.
    """
    
    block_size = np.random.uniform(20, 40)
    rotation = 5*np.random.randn()
    
    #print 'BLOCK SIZE', block_size
    #print 'ROTATION  ', rotation
    
    img = color.rgb2grey(img)
    img = transform.resize(img, output_shape=(50,30))
    img = filter.threshold_adaptive(img, block_size=block_size)
    
    # rotate the image
    img = np.logical_not(transform.rotate(np.logical_not(img), rotation))
    # translate the image
    img = shift(img)
    # add some noise to the image
    img = noise(img)
    
    img = transform.resize(img, output_shape=(25,15))
    return filter.threshold_adaptive(img, block_size=25)
def run_cmd(method, block_size=40):
    stdin = sys.stdin.read()
    if stdin == '\n':
        exit()

    img = Image.open(StringIO.StringIO(stdin)).convert('L')
    imgc = np.array(img)

    imggray = rgb2gray(imgc)

    if method is None or method == '':
        imgthresh = threshold_adaptive(imggray, block_size, 'gaussian', offset=10)
    elif method == 'gaussian':
        imgthresh = threshold_adaptive(imggray, block_size, 'gaussian', offset=10)
    elif method == 'median':
        imgthresh = threshold_adaptive(imggray, block_size, 'median', offset=10)
    elif method == 'mean':
        imgthresh = threshold_adaptive(imggray, block_size, 'mean', offset=10)
    elif method == 'otsu':
        thresh = threshold_otsu(imggray)
        imgthresh = imggray > thresh
    elif method == 'yen':
        thresh = threshold_yen(imggray)
        imgthresh = imggray > thresh
    elif method == 'iso':
        thresh = threshold_isodata(imggray)
        imgthresh = imggray > thresh


    rescaled = (255.0 / imgthresh.max() * (imgthresh - imgthresh.min())).astype(np.uint8)

    out = Image.fromarray(rescaled)
    out.save(sys.stdout, format='PNG')
Exemplo n.º 3
0
def sino_remove_bragg_spots(sinogram, block_size=5, tolerance=0.05, sensitivity_low=1.5, sensitivity_high=0.2):
    """ If value is above some local threshold,
        replace by median. Removes dodgy highlights and shadows
        resulting from bragg peaks from large crystallites
        in diffracting orientations """

    # Footprint for median value to replace bragg spots.
    # Usually the spots are contained to one projection,
    # so we sample above and below for good values.
    footprint = np.array(
        [[  False, True, False ],
         [  True,  True,  True ],
         [  False, False, False ],
         [  True,  True,  True ],
         [  False, True, False ]])

    # Only consider pixels which differ from the local median by this offset.
    # Highlights and shadows will skew the arithmetic mean so use median.

    median_value = np.median(sinogram)
    offset_high  = np.median(sinogram[sinogram>median_value])
    offset_low   = np.median(sinogram[sinogram<median_value])

    utils.debug_print(median=median_value,offset_high=offset_high, offset_low=offset_low)

    mask_low = ~filters.threshold_adaptive(
                 sinogram,
                 block_size,
                 method='median',
                 offset=-sensitivity_low*(offset_low-median_value),
             )
    mask_high = filters.threshold_adaptive(
                 sinogram,
                 block_size,
                 method='median',
                 offset=-sensitivity_high*(offset_high-median_value),
             )
    if float(mask_high.sum()) > tolerance * mask_high.size:
        # Too many values marked as spots. Ignoring hilights.
        print('Found more than %s%% of values as hilights' % (tolerance * 100))
        mask_high = np.zeros(shape=sinogram.shape, dtype=bool)
    if float(mask_low.sum()) > tolerance * mask_low.size:
        # Too many values marked as spots. Ignoring shadows.
        print('Found more than %s%% of values as shadows' % (tolerance * 100))
        mask_low = np.zeros(shape=sinogram.shape, dtype=bool)

    mask = mask_low + mask_high
    # FIXME, only calculate values in mask.
    median = ndimage.median_filter(sinogram, footprint=footprint)
    ret = sinogram.copy()
    ret[mask==True] = median[mask==True]
    return ret
Exemplo n.º 4
0
    def segment(self, src):
        '''
            pychron: preprocessing cv.Mat
        '''
#        image = pychron.ndarray[:]
#         image = asarray(pychron)
        image = src[:]
        if self.use_adaptive_threshold:
#            block_size = 25
            markers = threshold_adaptive(image, self.block_size)

            n = markers[:].astype('uint8')
            n[markers == True] = 255
            n[markers == False] = 1
            markers = n

        else:
            markers = zeros_like(image)
            markers[image < self.threshold_low] = 1
            markers[image > self.threshold_high] = 255

        elmap = sobel(image, mask=image)
        wsrc = watershed(elmap, markers, mask=image)

#         wsrc = wsrc.astype('uint8')
        return invert(wsrc)
Exemplo n.º 5
0
    def Adaptive_Thresholding(self):
        # read image
        im = cv2.imread(self.Image)
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (7, 7), 0)
        cv2.imshow("Image", im)

        # instead of manually specifying the threshold value, we can use adaptive
        # thresholding to examine neighborhoods of pixels and adaptively threshold
        # each neighborhood -- in this example, we'll calculate the mean value
        # of the neighborhood area of 25 pixels and threshold based on that value;
        # finally, our constant C is subtracted from the mean calculation (in this
        # case 15)
        thresh = cv2.adaptiveThreshold(blurred, 255,
                                       cv2.ADAPTIVE_THRESH_MEAN_C,
                                       cv2.THRESH_BINARY_INV, 25, 15)
        cv2.imshow("OpenCV Mean Thresh", thresh)

        # personally, I prefer the scikit-image adaptive thresholding, it just
        # feels a lot more "Pythonic"
        thresh = threshold_adaptive(blurred, 30,
                                    offset=5).astype("uint8") * 255
        thresh = cv2.bitwise_not(thresh)
        cv2.imshow("scikit-image Mean Thresh", thresh)
        cv2.waitKey(0)
Exemplo n.º 6
0
def intensity_object_features(im, adaptive_t_radius=51, sample_size=None):
    """Segment objects based on intensity threshold and compute properties.

    Parameters
    ----------
    im : 2D np.ndarray of float or uint8.
        The input image.
    adaptive_t_radius : int, optional
        The radius to calculate background with adaptive threshold.
    sample_size : int, optional
        Sample this many objects randomly, rather than measuring all
        objects.

    Returns
    -------
    f : 1D np.ndarray of float
        The feature vector.
    names : list of string
        The list of feature names.
    """
    tim1 = im > imfilter.threshold_otsu(im)
    f1, names1 = object_features(tim1, im, sample_size=sample_size)
    names1 = ['otsu-threshold-' + name for name in names1]
    tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius)
    f2, names2 = object_features(tim2, im, sample_size=sample_size)
    names2 = ['adaptive-threshold-' + name for name in names2]
    f = np.concatenate([f1, f2])
    return f, names1 + names2
Exemplo n.º 7
0
def intensity_object_features(im, adaptive_t_radius=51, sample_size=None):
    """Segment objects based on intensity threshold and compute properties.

    Parameters
    ----------
    im : 2D np.ndarray of float or uint8.
        The input image.
    adaptive_t_radius : int, optional
        The radius to calculate background with adaptive threshold.
    sample_size : int, optional
        Sample this many objects randomly, rather than measuring all
        objects.

    Returns
    -------
    f : 1D np.ndarray of float
        The feature vector.
    names : list of string
        The list of feature names.
    """
    tim1 = im > imfilter.threshold_otsu(im)
    f1, names1 = object_features(tim1, im, sample_size=sample_size)
    names1 = ['otsu-threshold-' + name for name in names1]
    tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius)
    f2, names2 = object_features(tim2, im, sample_size=sample_size)
    names2 = ['adaptive-threshold-' + name for name in names2]
    f = np.concatenate([f1, f2])
    return f, names1 + names2
Exemplo n.º 8
0
    def segment(self, src):
        image = src.ndarray[:]
        if self.use_adaptive_threshold:
            block_size = 25
            markers = threshold_adaptive(image, block_size) * 255
            markers = invert(markers)

        else:
            markers = zeros_like(image)
            markers[image < self.threshold_low] = 1
            markers[image > self.threshold_high] = 255

        elmap = sobel(image, mask=image)
        wsrc = watershed(elmap, markers, mask=image)

#        elmap = ndimage.distance_transform_edt(image)
#        local_maxi = is_local_maximum(elmap, image,
#                                      ones((3, 3))
#                                      )
#        markers = ndimage.label(local_maxi)[0]
#        wsrc = watershed(-elmap, markers, mask=image)
#        fwsrc = ndimage.binary_fill_holes(out)
#        return wsrc
        if self.use_inverted_image:
            out = invert(wsrc)
        else:
            out = wsrc

#        time.sleep(1)
#        do_later(lambda:self.show_image(image, -elmap, out))
        return out
Exemplo n.º 9
0
    def __call__(self, image, window_size=10, threshold=0, fill_holes=True,
                 outline_smoothing=2, remove_borderobjects=True, size_min=1,
                 *args, **kw):

        thresh = threshold_adaptive(image, block_size=window_size,
                                    offset=-1*threshold)

        if outline_smoothing >= 1:
            thresh = outlineSmoothing(thresh, outline_smoothing)

        thresh = remove_small_objects(thresh, size_min)

        seeds = ndi.label(clear_border(~thresh))[0]
        thresh = ndi.binary_fill_holes(thresh)
        smask = seeds.astype(bool)

        # object don't touch border after outline smoothing
        if remove_borderobjects:
            thresh = clear_border(thresh)

        img = np.zeros(thresh.shape)
        img[~smask] = 1
        edt = ndi.morphology.distance_transform_edt(img)
        edt -= ndi.morphology.distance_transform_edt(seeds)

        labels = watershed(edt, seeds)
        labels[smask] = 0
        labels[~thresh] = 0

        return labels
Exemplo n.º 10
0
    def plot_preprocessed_image(self):
        """
        plots pre-processed image. The plotted image is the same as obtained at the end
        of the get_text_candidates method.
        """
        image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
        thresh = filter.threshold_adaptive(image, 21)
        bw = closing(image > thresh, square(1))
        cleared = bw.copy()

        label_image = measure.label(cleared)
        borders = np.logical_xor(bw, cleared)

        label_image[borders] = -1
        image_label_overlay = label2rgb(label_image, image=image)

        fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
        ax.imshow(image_label_overlay)

        for region in regionprops(label_image):
            if region.area < 10:
                continue

            minr, minc, maxr, maxc = region.bbox
            rect = mpatches.Rectangle((minc, minr),
                                      maxc - minc,
                                      maxr - minr,
                                      fill=False,
                                      edgecolor='red',
                                      linewidth=2)
            ax.add_patch(rect)

        plt.show()
Exemplo n.º 11
0
    def segment(self, src):
        '''
            pychron: preprocessing cv.Mat
        '''
        #        image = pychron.ndarray[:]
        #         image = asarray(pychron)
        image = src[:]
        if self.use_adaptive_threshold:
            #            block_size = 25
            markers = threshold_adaptive(image, self.block_size)

            n = markers[:].astype('uint8')
            n[markers == True] = 255
            n[markers == False] = 1
            markers = n

        else:
            markers = zeros_like(image)
            markers[image < self.threshold_low] = 1
            markers[image > self.threshold_high] = 255

        elmap = sobel(image, mask=image)
        wsrc = watershed(elmap, markers, mask=image)

        #         wsrc = wsrc.astype('uint8')
        return invert(wsrc)
def adapative_threshold(image, block_size=100):
	"""
	This method returns the adaptively-thresholded image.
	"""

	thresholded_image = threshold_adaptive(image, block_size)
	imshow(thresholded_image)

	return thresholded_image
Exemplo n.º 13
0
def adaptive_segment(args):
    """
    Applies an adaptive threshold to reconstructed data.

    Also known as local or dynamic thresholding
    where the threshold value is the weighted mean
    for the local neighborhood of a pixel subtracted
    by constant. Alternatively the threshold can be
    determined dynamically by a given function using
    the 'generic' method.

    Parameters
    ----------
    data : ndarray, float32
        3-D reconstructed data with dimensions:
        [slices, pixels, pixels]

    block_size : scalar, int
        Uneven size of pixel neighborhood which is
        used to calculate the threshold value
        (e.g. 3, 5, 7, ..., 21, ...).

    offset : scalar, float
         Constant subtracted from weighted mean of
         neighborhood to calculate the local threshold
         value. Default offset is 0.

    Returns
    -------
    output : ndarray
        Thresholded data.

    References
    ----------
    - `http://scikit-image.org/docs/dev/auto_examples/plot_threshold_adaptive.html \
    <http://scikit-image.org/docs/dev/auto_examples/plot_threshold_adaptive.html>`_
    """
    # Arguments passed by multi-processing wrapper
    ind, dshape, inputs = args

    # Function inputs
    data = mp.tonumpyarray(mp.shared_arr, dshape)  # shared-array
    block_size, offset = inputs

    for m in ind:
        img = data[m, :, :]

        # Perform scikit adaptive thresholding.
        img = threshold_adaptive(img, block_size=block_size, offset=offset)

        # Remove small white regions
        img = ndimage.binary_opening(img)

        # Remove small black holes
        img = ndimage.binary_closing(img)

        data[m, :, :] = img
Exemplo n.º 14
0
 def preprocess_image(self):
     """
     Denoises and increases contrast. 
     """
     #image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
     thresh = filter.threshold_adaptive(self.image, 21)
     self.bw = closing(self.image > thresh, square(2))
     self.cleared = self.bw.copy()
     return self.cleared
Exemplo n.º 15
0
def extract_bill(image, screen, ratio):
    """"Extract the bill of the image"""
    warped = four_point_transform(image, screen.reshape(4, 2) * ratio)

    # convert the warped image to grayscale, then threshold it
    # to give it that 'black and white' paper effect
    warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
    warped = threshold_adaptive(warped, 250, offset=10)
    warped = warped.astype("uint8") * 255
    return warped
Exemplo n.º 16
0
def image_features_hog2(img, num_features,orientation,maxcell,maxPixel):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric
     block_size = 10
     image = threshold_adaptive(img, block_size, offset=5)
     im = resize(image, (maxPixel, maxPixel))
     ##hog scikit transform
     

     return image_features_hog_fd(im)
Exemplo n.º 17
0
    def scan(cls, filepath):
        print("Starting scan")
        # load the image and compute the ratio of the old height
        # to the new height, clone it, and resize it
        image = cv2.imread(filepath)
        ratio = image.shape[0] / 500.0
        orig = image.copy()
        image = imutils.resize(image, height=500)

        # convert the image to grayscale, blur it, and find edges
        # in the image
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (5, 5), 0)
        edged = cv2.Canny(gray, 75, 200)

        # find the contours in the edged image, keeping only the
        # largest ones, and initialize the screen contour
        cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
        screenCnt = None

        # loop over the contours
        for c in cnts:
            # approximate contours
            peri = cv2.arcLength(c, True)
            approx = cv2.approxPolyDP(c, 0.02 * peri, True)

            # if our approximated contour has four points, then we
            # can assume that we have found our screen
            if len(approx) == 4:
                screenCnt = approx
                break

        # Check if we found a 4 point contour. If not, we create our own bounding box
        # with the largest contour
        if screenCnt is None:
            height, width, channels = image.shape
            imageBounds = np.array([[1, 1], [width, 1], [width, height], [1, height]])
            screenCnt = imutils.get_bounding_box(imageBounds)

        # apply the four point transform to obtain a top-down
        # view of the original image
        warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)

        # convert the warped image to grayscale, then threshold it
        # to give it that 'black and white' paper effect
        warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
        warped = threshold_adaptive(warped, 250, offset=10)
        warped = warped.astype("uint8") * 255

        # Write out image to tmp file
        filename = "tmp/tmp-result.png"
        cv2.imwrite(filename, warped)
        print("Finished scan")
        return filename
Exemplo n.º 18
0
def run_cmd(method, block_size=40):
    stdin = sys.stdin.read()
    if stdin == '\n':
        exit()

    img = Image.open(StringIO.StringIO(stdin)).convert('L')
    imgc = np.array(img)

    imggray = rgb2gray(imgc)

    if method is None or method == '':
        imgthresh = threshold_adaptive(imggray,
                                       block_size,
                                       'gaussian',
                                       offset=10)
    elif method == 'gaussian':
        imgthresh = threshold_adaptive(imggray,
                                       block_size,
                                       'gaussian',
                                       offset=10)
    elif method == 'median':
        imgthresh = threshold_adaptive(imggray,
                                       block_size,
                                       'median',
                                       offset=10)
    elif method == 'mean':
        imgthresh = threshold_adaptive(imggray, block_size, 'mean', offset=10)
    elif method == 'otsu':
        thresh = threshold_otsu(imggray)
        imgthresh = imggray > thresh
    elif method == 'yen':
        thresh = threshold_yen(imggray)
        imgthresh = imggray > thresh
    elif method == 'iso':
        thresh = threshold_isodata(imggray)
        imgthresh = imggray > thresh

    rescaled = (255.0 / imgthresh.max() *
                (imgthresh - imgthresh.min())).astype(np.uint8)

    out = Image.fromarray(rescaled)
    out.save(sys.stdout, format='PNG')
Exemplo n.º 19
0
 def thresholdImage(self):
     """Threshold Image"""
     ### THRESHOLDING ###
     #=======================================================================
     # self.ThresholdMethod:
     # thresholdGlobalOtsu = filter.threshold_otsu(pyLaneTracker.Img, 64)
     # thresholdGlobalYen = filter.threshold_yen(pyLaneTracker.Img, 64)
     #=======================================================================
     
     thresholdAdaptive = filter.threshold_adaptive(self.Img, 96, method='median', offset=0, mode='reflect', param=None)
     self.Threshold = thresholdAdaptive
def generate_mask(fn):
    try:
        img_rgb = imread(os.path.join(input_dir, fn + '.tif'))
        img = rgb2gray(img_rgb)

        entropy_mask = generate_entropy_mask(img)

        init_contours = [
            xys for xys in find_contour_points(entropy_mask.astype(np.int),
                                               sample_every=1)[1]
            if len(xys) > 50
        ]
        assert len(init_contours
                   ) > 0, 'No contour is detected from entropy mask %s' % fn

        img_adap = threshold_adaptive(img, 51)
        img_adap[~entropy_mask] = 1

        final_masks = []

        for init_cnt in init_contours:

            img_adap_gauss = gaussian(img_adap.astype(np.float), 1)

            snake = active_contour(img_adap_gauss,
                                   init_cnt.astype(np.float),
                                   alpha=1.,
                                   beta=1000.,
                                   gamma=1.,
                                   w_line=0.,
                                   w_edge=10.,
                                   max_iterations=1000)

            bg = np.zeros(img.shape[:2], bool)
            xys = points_inside_contour(snake.astype(np.int))
            bg[np.minimum(xys[:, 1], bg.shape[0] - 1),
               np.minimum(xys[:, 0], bg.shape[1] - 1)] = 1

            final_mask = bg & entropy_mask
            final_masks.append(final_mask)

        final_mask = np.any(final_masks, axis=0)

        mask_fn = os.path.join(output_dir, '%(fn)s_mask.png' % dict(fn=fn))

        if os.path.exists(mask_fn):
            sys.stderr.write('Mask exists, overwrite: %s\n' % mask_fn)

        imsave(mask_fn, img_as_ubyte(final_mask))

    except Exception as e:
        sys.stderr.write(e.message + '\n')
        sys.stderr.write('%d, Mask error: %s\n' % (len(final_masks), fn))
        return
Exemplo n.º 21
0
def image_features_resize_adaptive(img, maxPixel, num_features,imageSize):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric
     block_size = 20
     im = threshold_adaptive(img, block_size, offset=5)
     X=np.zeros(num_features, dtype=float)
     image = resize(im, (maxPixel, maxPixel))
     # Store the rescaled image pixels
     X[0:imageSize] = np.reshape(image,(1, imageSize))

     return X
Exemplo n.º 22
0
def image_features_hog2(img, num_features,orientation,maxcell,maxPixel):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric
     block_size = 10
     image = threshold_adaptive(img, block_size, offset=5)
     im = resize(image, (maxPixel, maxPixel))
     ##hog scikit transform
     fd= hog(im, orientations=orientation, pixels_per_cell=(maxcell, maxcell),
                    cells_per_block=(1, 1), visualise=False,normalise=True)

     return fd
Exemplo n.º 23
0
def preprocess(image, height=50, block_size=50):
    """Turn to greyscale, scale to a height, and then threshold to binary
    """

    image = color.rgb2grey(image)
    size_factor = float(height) / image.shape[0]
    new_size = [int(e * size_factor) for e in image.shape]
    image = transform.resize(image, new_size)
    image = filter.threshold_adaptive(image, block_size=30)

    return image
Exemplo n.º 24
0
def image_features_resize_adaptive(img, maxPixel, num_features,imageSize):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric
     block_size = 20
     im = threshold_adaptive(img, block_size, offset=5)
     X=np.zeros(num_features, dtype=float)
     image = resize(im, (maxPixel, maxPixel))
     # Store the rescaled image pixels
     X[0:imageSize] = np.reshape(image,(1, imageSize))

     return X
def determine_threshold(avg_image, block_size=100, offset=-2):
	'''Used to determine the right threshold value for the segmentation. The input
	is the average of the image stack of particles on the ring. Play with the offset
	and block size to make a clear ring with minimal background noise. Negative values
	of offset should reduce background noise. This functions returns the thresholded array
	in addition to showing what it looks like.'''
	from skimage.filter import threshold_adaptive
	threshold=threshold_adaptive(avg_image, block_size, offset=offset)
	import matplotlib.pyplot as plt
	plt.imshow(threshold)
	plt.show()
	return threshold
Exemplo n.º 26
0
def feature_vector_from_rgb(image, sample_size=None):
    """Compute a feature vector from the composite images.

    The channels are assumed to be in the following order:
     - Red: MCF-7
     - Green: cytoplasm GFP
     - Blue: DAPI/Hoechst

    Parameters
    ----------
    im : array, shape (M, N, 3)
        The input image.
    sample_size : int, optional
        For features based on quantiles, sample this many objects
        rather than computing full distribution. This can considerably
        speed up computation with little cost to feature accuracy.

    Returns
    -------
    fs : 1D array of float
        The features of the image.
    names : list of string
        The feature names.
    """
    all_fs, all_names = [], []
    ims = np.rollaxis(image[..., :3], -1, 0) # toss out alpha chan if present
    mcf, cells, nuclei = ims
    prefixes = ['mcf', 'cells', 'nuclei']
    for im, prefix in zip(ims, prefixes):
        fs, names = features.intensity_object_features(im,
                                                       sample_size=sample_size)
        names = [prefix + '-' + name for name in names]
        all_fs.append(fs)
        all_names.extend(names)
    nuclei_mean = nd.label(nuclei > np.mean(nuclei))[0]
    fs, names = features.nearest_neighbors(nuclei_mean)
    all_fs.append(fs)
    all_names.extend(['nuclei-' + name for name in names])
    mcf_mean = nd.label(mcf)[0]
    fs, names = features.fraction_positive(nuclei_mean, mcf_mean,
                                           positive_name='mcf')
    all_fs.append(fs)
    all_names.extend(names)
    cells_t_otsu = cells > threshold_otsu(cells)
    cells_t_adapt = threshold_adaptive(cells, 51)
    fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_otsu)
    all_fs.append(fs)
    all_names.extend(['otsu-' + name for name in names])
    fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_adapt)
    all_fs.append(fs)
    all_names.extend(['adapt-' + name for name in names])
    return np.concatenate(all_fs), all_names
Exemplo n.º 27
0
def split_rigid(image, charseps):
    """Split an image into characters. Charseps should be a list of ints
    giving the horizontal location to split
    """
    n_chars = len(charseps) - 1

    chars = []
    for i in range(n_chars):
        char = image[:, charseps[i] : charseps[i + 1]]
        char = transform.resize(char, output_shape=(25, 15))
        char = filter.threshold_adaptive(char, block_size=30)
        chars.append(char)

    return chars
Exemplo n.º 28
0
Arquivo: cafe.py Projeto: jni/cafe
def encode_centro_telomeres(image_centro, image_telo,
                            centro_offset=0.0, centro_factor=1.0,
                            centro_min_size=36, centro_radius=10,
                            telo_offset=0.0, telo_adapt_radius=49,
                            telo_open_radius=4):
    """Find centromeres, telomeres, and their overlap.

    Parameters
    ----------
    image_centro : array, shape (M, N)
        The grayscale channel for centromeres.
    image_telo : array, shape (M, N)
        The grayscale channel for telomeres.
    centro_offset : float, optional
        Offset Otsu's threshold by this amount (i.e. be less stringent
        about what image intensity constitutes a centromere)
    centro_factor : float, optional
        Offset Otsu's threshold by a multiplicative constant.
    centro_min_size : int, optional
        Remove objects smaller than this, as they would be too small to
        be a centromere.
    centro_radius : int, optional
        Consider anything within this radius to be "near" a centromere.
    telo_offset : float, optional
        Offset the telomere image threshold by this amount.
    telo_adapt_radius : int, optional
        Use this radius to threshold telomere image adaptively.
    telo_open_radius : int, optional
        Use this radius for a binary opening of thresholded telomeres
        (removes noise).

    Returns
    -------
    encoded_regions : array of int, shape (M, N)
        A uint8 image with the following values:
         - 0: background
         - 1: telomeres
         - 2: centromeres
         - 3: centromere/telomere overlap
    """
    centros = otsu(image_centro, centro_offset, centro_factor)
    centros = remove_small_objects(centros, centro_min_size)
    centro_strel = selem.disk(centro_radius)
    centros = nd.binary_dilation(centros, structure=centro_strel)
    telos = imfilter.threshold_adaptive(image_telo, telo_adapt_radius,
                                        offset=telo_offset)
    telo_strel = selem.disk(telo_open_radius)
    telos = nd.binary_opening(telos, structure=telo_strel)
    encoded_regions = 2 * centros.astype(np.uint8) + telos
    return encoded_regions
Exemplo n.º 29
0
def find_symbols(input_image):
    """
    Pronalazi na karti pozicije broja i boje te ih ekstraktira u nove matrice
    :param input_image: image for processing
    :return: dimensions of new image matrix for rank and suit
    """
    grey_warped_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
    black_and_white = threshold_adaptive(grey_warped_image, 250, offset=10)  # napravi binarnu sliku, crno-bijelu
    black_and_white = black_and_white.astype("uint8") * 255

    kernel = np.ones((3, 2), 'uint8')
    # print black_and_white[20][20]
    black_and_white = cv2.erode(black_and_white, kernel, iterations=1)
    # cv2.imshow('Erodirana', black_and_white)
    blob_found = False
    region_width, region_height = 32, 93
    rect_top, rect_bot = input_image[5:region_height, 5:region_width], input_image[247:(247 + 98), 208:(208 + 37)]

    blob_found = False
    region_width, region_height = 32, 93
    # rect_top, rect_bot = input_image[5:region_height, 5:region_width], input_image[247:(247 + 98), 208:(208 + 37)]
    # print black_and_white.shape
    mask = np.zeros((black_and_white.shape[0] + 2, black_and_white.shape[1] + 2), 'uint8')
    bin_card = black_and_white.copy()
    rects = []
    # cnt = 0
    for y in np.arange(5, region_height):
        for x in np.arange(5, region_width):
            bgr = black_and_white[y, x]
            if bgr == 0:
                cv2.floodFill(black_and_white, mask, (x, y), (255, 255, 255))
                # cv2.imshow("flooded", black_and_white)
                # cv2.imwrite("flooded" + str(cnt) +".jpg", black_and_white)
                # cnt += 1
                # cv2.waitKey(0)
                # cv2.destroyAllWindows()
                rects.append(xor(black_and_white, bin_card, rects))

    # print "RECTS: ", rects
    if len(rects) < 3:
        rank_dim, suit_dim = rects[0], rects[1]
    else:
        x1, y1, w1, h1 = rects[0]
        x2, y2, w2, h2 = rects[1]
        rank_dim = (x1, y1, w1 + w2 + 2, h1)
        suit_dim = rects[2]

    return rank_dim, suit_dim
Exemplo n.º 30
0
def noise(img, rho=0.01, sigma=0.5, block_size=50):
    """Add two forms of noise to a binary image
    
    First, flip a fraction, rho, of the bits. The bits to flip are
    selected uniformly at random.
    
    Second, add white noise to the image, and then re-threshold it back to
    binary. Here, errors in the thresholding lead to a new "splotchy" error
    pattern, especially near the edges.
    """
    
    mask = scipy.sparse.rand(img.shape[0], img.shape[1], density=rho)
    mask.data = np.ones_like(mask.data)
    img = np.mod(img + mask, 2)
    
    img = img + sigma * np.random.random(img.shape)
    img = filter.threshold_adaptive(img, block_size=block_size)
    
    return img
Exemplo n.º 31
0
def detect_value(input_image):
    """
    Vraca vrijednost karte (2 - 10)
    :param input_image: image for processing
    :return: value of input image
    """
    grey_warped_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
    black_and_white = threshold_adaptive(grey_warped_image, 250, offset=10)  # napravi binarnu sliku, crno-bijelu
    black_and_white = black_and_white.astype("uint8") * 255

    # cv2.imshow('binarna', black_and_white)

    kernel = np.ones((3, 3), 'uint8')
    # ignoriraj kuteve
    region_width, region_height = 32, 93
    rect_top, rect_bot = black_and_white[5:region_height, 5:region_width], black_and_white[247:(247 + 98),
                                                                           208:(208 + 37)]

    cv2.rectangle(black_and_white, (2, 2), (2 + region_width, 2 + region_height), (255, 255, 255), -1)
    cv2.rectangle(black_and_white, (218, 263), (218 + 29, 263 + 82), (255, 255, 255), -1)

    # cv2.imshow("bez kuteva", black_and_white)
    # cv2.imwrite('bezkuteva.jpg', black_and_white)

    black_and_white = cv2.dilate(black_and_white, kernel, iterations=1)

    # cv2.imshow("Dilate", black_and_white)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    black_and_white = cv2.morphologyEx(black_and_white, cv2.MORPH_CLOSE, kernel=np.ones((5, 5), 'uint8'), iterations=3)
    mask = np.zeros((black_and_white.shape[0] + 2, black_and_white.shape[1] + 2), 'uint8')
    # cv2.imshow("Closed", black_and_white)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # .imwrite("closed.jpg", black_and_white)
    count_blobs = 0
    for y in np.arange(black_and_white.shape[0]):
        for x in np.arange(black_and_white.shape[1]):
            if black_and_white[y, x] == 0:
                count_blobs += 1
                cv2.floodFill(black_and_white, mask, (x, y), (255, 255, 255))
    return count_blobs
Exemplo n.º 32
0
def _adaptive_segment(args):
    """
    Adaptive thresholding based segmentation.
    """
    data, args, ind_start, ind_end = args
    block_size, offset = args
    
    for m in range(ind_end-ind_start):
        img = data[m, :, :]
        
        # Perform scikit adaptive thresholding.
        img = threshold_adaptive(img, block_size=block_size, offset=offset)
        
        # Remove small white regions
        img = ndimage.binary_opening(img)
        
        # Remove small black holes
        img = ndimage.binary_closing(img)

        data[m, :, :] = img
    return ind_start, ind_end, data
Exemplo n.º 33
0
    def segment(self, src):
        '''
            src: preprocessing cv.Mat
        '''
        image = src.ndarray[:]


        if self.use_adaptive_threshold:
#            block_size = 25
            markers = threshold_adaptive(image, self.block_size)

            n = markers[:].astype('uint8')
            n[markers == True] = 255
            n[markers == False] = 1
            markers = n
#            print markers
#            markers = markers.astype('uint8')
#            n = ones_like(markers)
#            n[markers] = 255
#            print n
#            markers[markers] = 255
#            markers[not markers] = 1
#            print markers
#            markers = n.astype('uint8')
#            markers = invert(markers).astype('uint8')

        else:
            markers = zeros_like(image)
            markers[image < self.threshold_low] = 1
            markers[image > self.threshold_high] = 255

#        global cnt
#        # remove holes
#        if cnt % 2 == 0:
#            markers = binary_closing(markers).astype('uint8') * 255
#        cnt += 1
#        print markers
        elmap = sobel(image, mask=image)
        wsrc = watershed(elmap, markers, mask=image)
        return invert(wsrc)
Exemplo n.º 34
0
def segment_cells(img):
    """label the cells in an image.

    Returns the labeled image and the number of labels.

    """
    if img.ndim == 3 and img.shape[-1] > 1:
        img = make_grey(img)
    # # global threshold and watershed
    # binary = img < threshold_otsu(img)
    # distance = ndimage.distance_transform_edt(binary)
    # local_maxi = peak_local_max(distance, indices=False, footprint=np.ones((3, 3)), labels=binary)
    # markers = ndimage.label(local_maxi)[0]
    # labels = watershed(-distance, markers, mask=binary)

    # local threshold and erosion / dilation
    t_img = threshold_adaptive(img, 25, offset=.01)
    b_img = binary_erosion(-t_img, np.ones((3, 3)))
    d_img = binary_dilation(b_img, np.ones((3, 3)))
    clear_border(d_img)
    labels, n_labels = ndimage.label(d_img)
    return labels, n_labels
def threshold(image):

    gaussian_image = scpy.gaussian_filter(image, (10, 10))
    display(gaussian_image, 'gaussian_image', 0)
    clahe = cv2.createCLAHE(clipLimit=15.0, tileGridSize=(6, 6))
    cl1 = clahe.apply(gaussian_image)
    display(cl1, 'clahe', 0)

    threshold_image = threshold_adaptive(cl1, 255, offset=10)
    threshold_average_image = threshold_image.astype(np.uint8) * 255
    display(threshold_average_image, 'threshold_average_image', 0)

    image, contours, hier = cv2.findContours(
        threshold_average_image, cv2.RETR_TREE,
        cv2.CHAIN_APPROX_SIMPLE)  #, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    smears = []

    for cnt in contours:

        area = cv2.contourArea(cnt)
        # if area>6000 and area<25000:  #cam1
        if area > 25000 and area < 26000:  #cam3
            # if area>6800 and area<7000:  #cam5
            # if area>6800 and area<7000:  #cam0,2
            print 'area=', area
            smears.append(cnt)

    mask = np.zeros(threshold_average_image.shape, np.uint8)
    cv2.drawContours(mask, smears, -1, (255, 255, 255), -1)

    # cv2.drawContours(mask, smears, 1, (255, 255, 255), -1)  #cam 1
    # cv2.drawContours(mask, smears, 2, (255, 255, 255), -1)  #cam 1
    # cv2.drawContours(mask, smears, 3, (255, 255, 255), -1)  #cam 1

    cv2.imwrite('mask.jpg', mask)
    print 'mask saved'

    cv2.destroyAllWindows()
    return 255 - mask
Exemplo n.º 36
0
    def compute_base_mask(self,image,params):
        """Creates the base mask for the phase image

           params is a MaskParameters object with the necessary parameters
        """
        
        self.mask = np.copy(image)

        if params.auto_threshold:
            params.absolute_threshold = threshold_isodata(self.mask)

        if params.algorithm == "Local Average":
            #need to invert because threshold_adaptive sets dark parts to 0
            self.mask = 1.0-filter.threshold_adaptive(self.mask, params.blocksize,offset=params.offset)
        else:
            if params.auto_threshold:
                params.absolute_threshold = threshold_isodata(self.mask)
            #the convention is that dark is foreground and with mask set to 1            
            self.mask = img_as_float(image <= params.absolute_threshold)
            
        if params.invert:
            self.invert_mask()
    def Adaptive_Thresholding(self):
        # read image
        im = cv2.imread(self.Image)
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (7, 7), 0)
        cv2.imshow("Image", im)

        # instead of manually specifying the threshold value, we can use adaptive
        # thresholding to examine neighborhoods of pixels and adaptively threshold
        # each neighborhood -- in this example, we'll calculate the mean value
        # of the neighborhood area of 25 pixels and threshold based on that value;
        # finally, our constant C is subtracted from the mean calculation (in this
        # case 15)
        thresh = cv2.adaptiveThreshold(blurred, 255,
            cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 15)
        cv2.imshow("OpenCV Mean Thresh", thresh)

        # personally, I prefer the scikit-image adaptive thresholding, it just
        # feels a lot more "Pythonic"
        thresh = threshold_adaptive(blurred, 30, offset=5).astype("uint8") * 255
        thresh = cv2.bitwise_not(thresh)
        cv2.imshow("scikit-image Mean Thresh", thresh)
        cv2.waitKey(0)
Exemplo n.º 38
0
def get_bounding_boxes(filename):
    image = Image.open(filename)
    image = np.asarray(image)[0::1,0::1]

    block_size = image.shape[0]/7.
    binary_adaptive = np.invert(threshold_adaptive(image, block_size, offset=70))

    mask = binary_adaptive > binary_adaptive.mean()
    label_im, n_labels = ndimage.label(binary_adaptive)#mask)


    extrema = {}
    for i in range(1, n_labels+1):
        extrema[i] = ((1000, 1000), (0, 0))

    # i: row
    # j: col
    for i,row in enumerate(label_im):
        for j, label in enumerate(row):
            if label[0] > 0:
                top, bottom  = extrema[label[0]]
                if i > bottom[0]:
                    bottom = (i, bottom[1])
                if j > bottom[1]:
                    bottom = (bottom[0], j)

                if i < top[0]:
                    top = (i, top[1])
                if j < top[1]:
                    top = (top[0], j)
                extrema[label[0]] = (top, bottom)

    boxes = []
    for label,coords in extrema.items():
        b = Box(coords[0][0], coords[0][1], coords[1][0], coords[1][1])
        boxes.append(b)
    return boxes
Exemplo n.º 39
0
Arquivo: cafe.py Projeto: jni/cafe
def get_chromatin(im, background_diameter=51, opening_size=2, opening_iter=2,
                  size_filter=256):
    """Find the chromatin in an unevenly illuminated image.

    Parameters
    ----------
    im : np.ndarray, shape (M, N)
        The chromatin grayscale image.
    background_diameter : int, optional
        The diameter of the block size in which to find the background. (This
        is used by the scikit-image function `threshold_adaptive`.)
        (default: 51)
    opening_size : int, optional
        Perform a binary opening with a disk of this radius. (default: 2)
    opening_iter : int, optional
        Perform this many opening iterations. (default: 2)
    size_filter : int, optional
        After the morphological opening, filter out segments smaller than this
        size. (default: 256)

    Returns
    -------
    chrs : np.ndarray, shape (M, N)
        A thresholded image of the chromatin regions.
    """
    if im.ndim == 3 and im.shape[2] == 3:
        im = im[..., 0]
    fg = imfilter.threshold_adaptive(im, background_diameter)
    # on an unevenly lit image, `fg` will have all sorts of muck lying around,
    # in addition to the chromatin. Thankfully, the muck is noisy and full of
    # holes, whereas the chromatin is solid. An opening followed by a size
    # filtering removes it quite effectively.
    strel = selem.disk(opening_size)
    fg_open = nd.binary_opening(fg, strel, iterations=opening_iter)
    chrs = remove_small_objects(fg_open, size_filter)
    return chrs
def threshold2(path):
    i = 0
    for image_path in glob.glob(path + '/*.png'):
        print i, image_path
        img = cv2.imread(image_path, 0)

        gaussian_image = scpy.gaussian_filter(img, (10, 10))
        display(gaussian_image, 'gaussian_image', 0)

        threshold_image = threshold_adaptive(gaussian_image, 255, offset=9)
        threshold_average_image = threshold_image.astype(np.uint8) * 255
        display(threshold_average_image, 'threshold_average_image', 0)

        edge_detection_image = cv2.Canny(threshold_average_image, 200, 200)
        display(edge_detection_image, 'edge_detection_image', 0)

        (_, cnts, _) = cv2.findContours(edge_detection_image, cv2.RETR_LIST,
                                        cv2.CHAIN_APPROX_SIMPLE)

        cv2.drawContours(img, cnts, -1, (0, 0, 255), 2)
        display(img, 'final', 0)

        cv2.destroyAllWindows()
        i += 1



dirq = "data/"
files = []
for i in os.listdir(dirq) :
    if i.endswith(".jpg") :
        files.append(dirq + i)


for f in files :

	image = exposure.equalize_adapthist(io.imread(f))

	binary = filter.threshold_adaptive(exposure.adjust_sigmoid(image[:, :, 0], cutoff=0.4, gain = 30), 301).astype(bool)
	clean = morphology.binary_closing(binary, morphology.disk(3)).astype(bool)
	clean = morphology.remove_small_objects(clean, 200)
	clean = morphology.remove_small_objects( (1-clean).astype(bool), 200)

	local_density = filter.gaussian_filter(clean, 61)

	ent = filter.gaussian_filter(filter.rank.entropy(local_density, morphology.disk(3)), 75)

	ent -= ent.min()
	ent /= ent.max()

	local_density -= local_density.min()
	local_density /= local_density.max()

	info = ent * (1 + local_density)
Exemplo n.º 42
0
# Histogram
values, bins = np.histogram(image, bins=np.arange(256))

label_1 = "(b) Histogram"
ax1.plot(bins[:-1], values, lw=2, c='k')
ax1.set_xlim(xmax=256)
ax1.set_yticks([0, 400])
ax1.set_aspect(.2)
ax1.set_title(label_1)


# Apply threshold
from skimage.filter import threshold_adaptive

bw = threshold_adaptive(image, 95, offset=-15)

label_2 = "(c) Adaptive threshold"
ax2.imshow(bw, cmap=plt.cm.gray)
ax2.set_title(label_2)
ax2.axis('off')

# Find maxima
from skimage.feature import peak_local_max

coordinates = peak_local_max(image, min_distance=20)

label_3 = "(d) Peak local maxima"
ax3.imshow(image, cmap=plt.cm.gray)
ax3.autoscale(False)
ax3.plot(coordinates[:, 1], coordinates[:, 0], 'r.')
Exemplo n.º 43
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from PIL import Image
from pylab import imshow,show,subplot,array,figure,gray,zeros,ones,uint8,jet
from skimage.filter import threshold_adaptive
from scipy.ndimage import filters,measurements

file_name='../../data/cv_data/empire.jpg'
# load the image file
img_gray = array(Image.open(file_name).convert('L'))

# binary the image
img_bin = threshold_adaptive(img_gray, block_size=15, offset=10)

#refers to http://docs.scipy.org/doc/scipy/reference/ndimage.html
#none-zero pixels are considered.
#label begin from 1.
#structure defines the connect condition.
s = array([[1,1,1],[1,1,1],[1,1,1]])
labeled_array, num_features = measurements.label(img_bin, structure=s)
print labeled_array
print num_features 

figure()
gray() # don't use colors 

subplot(1,2,1)   
imshow(img_gray)

subplot(1,2,2)
Exemplo n.º 44
0
def processImage(args):
    # load the image and compute the ratio of the old height
    # to the new height, clone it, and resize it
    image = cv2.imread(args["image"])

    ratio = image.shape[0] / 500.0
    orig = image.copy()
    image = imutils.resize(image, height=500)

    edged = cv2.Canny(image, 75, 200)

    # res = np.hstack((gray,eqgray))

    # find the contours in the edged image, keeping only the
    # largest ones, and initialize the screen contour
    (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST,
                                 cv2.CHAIN_APPROX_SIMPLE)

    # sort by perimeter first and then area
    cnts = sorted(cnts, key=lambda x: cv2.arcLength(x, False),
                  reverse=True)[:3]
    contour = sorted(cnts,
                     key=lambda x: cv2.contourArea(x, False),
                     reverse=True)[0]

    def removeInlier(points, closeLine=False):
        initial_area = cv2.contourArea(points)
        new_contour = points
        ratios = []
        for i in range(len(points)):
            # new_contour = points.pop(i)
            new_contour = np.delete(new_contour, i, 0)
            new_area = cv2.contourArea(new_contour)
            ratios += [new_area / initial_area]
            new_contour = points
        index = np.argmax(ratios)
        return np.delete(points, index, 0)

    # approximate the contour
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
    approx = cv2.convexHull(approx)
    approx = approx.reshape((len(approx), 2))
    while len(approx) > 4:
        approx = removeInlier(approx)

    # apply the four point transform to obtain a top-down
    # view of the original image
    warped = four_point_transform(orig, approx.reshape(4, 2) * ratio)

    if args["bw"] == "true":
        warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
        warped = threshold_adaptive(warped, 40, offset=7)
        warped = warped.astype("uint8") * 255
    else:
        b, g, r = cv2.split(warped)  # get b,g,r
        warped = cv2.merge([r, g, b])  # switch it to rgb

    final = imutils.resize(warped, height=650)
    sheet_ratio = final.shape[0] / float(final.shape[1])

    fig = plt.figure(frameon=False)
    if str(args["a4"]) == "true":
        fig.set_size_inches(11.69, 8.27)
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        fig.add_axes(ax)
    else:
        fig.set_size_inches(3, 3 / sheet_ratio)
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        fig.add_axes(ax)

    if args["bw"] == "true":
        ax.imshow(final, aspect='auto', cmap=plt.get_cmap('gray'))
    else:
        ax.imshow(final, aspect='auto')

    format = str(args["format"])
    path = str(args["out"])
    filename = str(args["name"]).split(".")[0]
    plt.savefig(os.path.join(path, filename + "." + format),
                format=format,
                dpi=int(args["dpi"]))

    if args["koriginal"] == "true":
        orig_path = args["image"]
        orig_format = orig_path.split(".")[-1]
        shutil.copyfile(orig_path,
                        os.path.join(path, filename + "." + orig_format))
Exemplo n.º 45
0
clean[(x, y)] += 5
clean = ndimage.gaussian_filter(clean, 3)
clean = clean / np.max(clean)

# Combining both the non-uniform background
# and points
fimg = bkg + clean
fimg = fimg / np.max(fimg)

# Defining minimum neighboring size of objects
block_size = 3

# Adaptive threshold function which returns image
# map of structures that are different relative to
# background
adaptive_cut = skif.threshold_adaptive(fimg, block_size, offset=0)

# Global threshold
global_thresh = skif.threshold_otsu(fimg)
global_cut = fimg > global_thresh

# Creating figure to highlight difference between
# adaptive and global threshold methods
fig = plt.figure(figsize=(8, 4))
fig.subplots_adjust(hspace=0.05, wspace=0.05)

ax1 = fig.add_subplot(131)
ax1.imshow(fimg)
ax1.xaxis.set_visible(False)
ax1.yaxis.set_visible(False)
Exemplo n.º 46
0
from scipy import ndimage
import matplotlib.pyplot as plt
import numpy as np
import mahotas
from parser.lines import *
from skimage.filter import threshold_otsu, threshold_adaptive


image = mahotas.imread('photo.jpg')[0::20,0::20]


block_size = 50
binary_adaptive = np.invert(threshold_adaptive(image, block_size, offset=30))

mask = binary_adaptive > binary_adaptive.mean()
label_im, n_labels = ndimage.label(binary_adaptive)#mask)

print n_labels
plt.figure(figsize=(9,3))

extrema = {}
for i in range(1, n_labels+1):
    extrema[i] = ((1000, 1000), (0, 0))

# i: row
# j: col
for i,row in enumerate(label_im):
    for j, label in enumerate(row):
        if label[0] > 0:
            top, bottom  = extrema[label[0]]
            if i > bottom[0]:
Exemplo n.º 47
0
from skimage.filter import median_filter

ptsCropSouth = array([[3000, 4650], [3700, 5200]])
oilCropSouth = imcrop(ptsCropSouth, delta)
ptsCropNorth = array([[3400, 0], [5000, 1650]])
oilCropNorth = imcrop(ptsCropNorth, delta)

image = oilCropNorth

image = median_filter(image, radius=50)

global_thresh = threshold_otsu(image)
binary_global = image > global_thresh

block_size = 300
binary_adaptive = threshold_adaptive(image, block_size)

markers = ones(image.shape, dtype=uint)
markers[image < global_thresh * 0.78] = 0

# display results
plt.figure()
plt.subplot(221)
plt.imshow(image, cmap=plt.cm.gray)
plt.axis('off')
plt.title('noisy image', fontsize=20)
plt.subplot(222)
plt.imshow(binary_global, cmap=plt.cm.gray)
plt.axis('off')
plt.title('Global thresholding', fontsize=20)
plt.subplot(223)
Exemplo n.º 48
0
# from skimage import filter
from skimage import filter
import scipy.misc
import Image, numpy

# opening the image and converting it to grayscale
a = Image.open('../Figures/adaptive_example1.png').convert('L')
# a is converted to an ndarray
a = scipy.misc.fromimage(a)
# performing adaptive thresholding
b = filter.threshold_adaptive(a, 40, offset=10)
# b is converted from an ndarray to an image
b = scipy.misc.toimage(b)
# saving the image as adaptive_output.png
# in the folder Figurespb
b.save('../Figures/adaptive_output.png')
Exemplo n.º 49
0
def threshold_images(images, offset_arg):
    binary_masks = []
    for img in images:
        img = threshold_adaptive(img, 21, offset=-160)  #img > threshold
        binary_masks.append(img)
    return binary_masks
Exemplo n.º 50
0
def mySegmentation(img,s,method='adaptive',BoW='B',thr=0.75,l_th1=0,l_th2=550,seeds_thr1=50,seeds_thr2=500,block_size=7,offs=-0,visual=0):
    
    """the user can choose wether to use otsu for seeds (merkers) definition or get seeds from the standard deviation map"""
    img=Prepare_im(img);  
    sz=np.shape(img)
    seeds=np.zeros((sz[0],sz[1]))

    if method=='otsu':


        t=threshold_otsu(img.astype(uint16))*thr
        l=img<t

                #seeds=abs(seeds-1)      

        [l,N]=msr.label(l,return_num=True)

        [l,N]=remove_reg(l,l_th1,l_th2)   



    if visual:
        figure();imshow(img)
        figure();imshow(seeds)
        figure();imshow(l)
        
        
    if method=='adaptive':


        binary_adaptive = threshold_adaptive(-img, block_size, offset=offs)

        l=binary_adaptive

        [l,N]=msr.label(l,return_num=True)

        l,N=remove_reg(l,l_th1,l_th2)


        l=l!=0

        l=sgm.clear_border(l)

        l=mph.dilation(l)


        [l,n]=msr.label(l,return_num=True)


              

    if method=='std' :

#%compute otsu mask

        #s=std_image(img,0)
        t=mht.otsu(img.astype(uint16))*thr
        tempseeds=img<t
 

        s2=np.copy(s)
        s2=ndi.maximum_filter(s2,10)
        local_maxi = peak_local_max((s2 ).astype(np.double), indices=False,footprint=np.ones((10, 10)),min_distance=100000)
               

        #seeds=pymorph.regmin((-s2).astype(np.uint16)) #,array([[False,True,True,False],[False,True,True,False]]))
        seeds=local_maxi

        #seeds,n=mht.label(seeds)
        im=Prepare_im(img)
        t=threshold_otsu(im)
        mask=im<t*0.85

        seeds=msr.label(seeds)
        seeds,N=remove_reg(seeds,seeds_thr1,seeds_thr2)   
    
       # l = mht.cwatershed(img, seeds)
        l = mph.watershed(img, msr.label(local_maxi),mask=mph.binary_dilation(mask))
        #l=mph.watershed(img,seeds)
        l=l.astype(int32)        
        l,n=remove_reg(l,l_th1,l_th2)
        l=mht.labeled.remove_bordering(l)
        print 'label'
        print mht.labeled.labeled_size(l)
        [l,n]=msr.label(l,return_num=True)

    if visual:
        figure();imshow(img)
        figure();imshow(seeds)
        figure();imshow(l)
        
    return seeds,N,l


    if visual:
        figure();imshow(img)
        figure();imshow(seeds)
        figure();imshow(l)
        
    
        

    return seeds,N,l
Exemplo n.º 51
0
def adaptthreshold(array):
    return filter.threshold_adaptive(array, 40, 'gaussian')
Exemplo n.º 52
0
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import segmentation
from skimage import morphology
from skimage import filter

coins = data.coins()

simple_threshold = coins > filter.threshold_otsu(coins)

adaptive_threshold = filter.threshold_adaptive(coins, 151)
filter_res = morphology.remove_small_objects(adaptive_threshold)
clear_image = segmentation.clear_border(filter_res)

plt.figure()
plt.subplot(221)
plt.imshow(coins, cmap='gray')
plt.title('Image d\'origine')
plt.axis('off')
plt.subplot(222)
plt.imshow(simple_threshold, cmap='gray')
plt.title('Simple seuillage')
plt.axis('off')
plt.subplot(223)
plt.imshow(adaptive_threshold, cmap='gray')
plt.title('Seuillage adaptatif')
plt.axis('off')
plt.subplot(224)
plt.imshow(clear_image, cmap='gray')
plt.title('Image nettoyee')
Exemplo n.º 53
0
def extract_features(im_cat_path_list):
    '''
    Extract Features takes a list of 2 element lists:
        
        [catagory of image , path to image]
    
    and extracts 15 features from this image. The output is a list of 3 element lists:
    
        [catagory of image , path to image, [list of features]]
        
    The 15 features are:
        
        1     Product of image pixel dimensions (image size)
        2     Mean of Grayscale Image
        3     Area of Sobel Edges Normalized By Image Size
        4     Area of Sobel Edges Above 2x Mean of Sobel Edges Normalized By Image Size
        5     Area of Canny Edges (Sum of booleans) Normalized By Image Size
        6     Number of Harris Corners
        7     Unique Felzenszwalb Image Segmentation Lines
        8     Area of Vertical Sobel Edges Above 2x Mean of Sobel Edges Normalized By Image Size
        9     Area of Horizontal Sobel Edges Above 2x Mean of Sobel Edges Normalized By Image Size
        10-12 Mean of Red/Green/Blue Channels (if grayscale: mean of the only color channel)
        13    Maximum Pixel Value of the Histogram of Oriented Gradients
        14    Percent of image that is light versus dark with adaptive thresholding
        15-17 Percent of image that is red/green/blue with adaptive thresholding
    '''

    cat_path_features = []

    for im_cat, im_path in im_cat_path_list:

        #RAW IMAGE
        im_raw = imread(im_path)  #image matrix

        #RAW IMAGE FLATTENED IF NOT ALREADY FLAT
        if len(np.shape(im_raw)) == 3:
            im_raw_flat = np.median(im_raw, axis=2)
        else:
            im_raw_flat = im_raw

        #Size of image
        im_y = float(im_raw.shape[0])
        im_x = float(im_raw.shape[1])
        im_size = im_y * im_x

        #LIST OF FEATURES
        features = []

        #FEATURE 1: Product of image pixel dimensions (image size)
        features.append(float(im_size))

        #FEATURE 2: Mean of Grayscale Image
        features.append(im_raw_flat.mean())

        #FEATURE 3: Area of Sobel Edges Normalized By Image Size
        im_edge_sobel = filter.sobel(im_raw_flat)
        features.append(im_edge_sobel.sum() / im_size)

        #FEATURE 4: Area of Sobel Edges Above 2x Mean of Sobel Edges Normalized By Image Size
        features.append(
            float((im_edge_sobel > im_edge_sobel.mean() * 2).sum()) / im_size)

        #FEATURE 5: Area of Canny Edges (Sum of booleans) Normalized By Image Size
        im_canny = filter.canny(im_raw_flat, sigma=8)
        features.append(im_canny.sum().astype(float) / im_size)

        #FEATURE 6: Number of Harris Corners
        im_corners = feature.corner_peaks(feature.corner_harris(im_raw_flat),
                                          min_distance=5)
        features.append(float(len(im_corners)))

        #FEATURE 7: Unique Felzenszwalb Image Segmentation Lines
        im_raw_float = util.img_as_float(im_raw[::2, ::2])
        im_felzen_segments = segmentation.felzenszwalb(im_raw_float,
                                                       scale=100,
                                                       sigma=0.5,
                                                       min_size=50)
        features.append(float(len(np.unique(im_felzen_segments))))

        #FEATURE 8: Area of Vertical Sobel Edges Above 2x Mean of Sobel Edges Normalized By Image Size
        im_edge_vsobel = filter.vsobel(im_raw_flat)
        features.append(
            float(
                (im_edge_vsobel > im_edge_vsobel.mean() * 2).sum()) / im_size)

        #FEATURE 9: Area of Horizontal Sobel Edges Above 2x Mean of Sobel Edges Normalized By Image Size
        im_edge_hsobel = filter.hsobel(im_raw_flat)
        features.append(
            float(
                (im_edge_hsobel > im_edge_hsobel.mean() * 2).sum()) / im_size)

        #FEATURE 10-12: Mean of Red/Green/Blue Channels (if grayscale: mean of the only color channel)
        if len(np.shape(im_raw)) == 3:
            features.append(im_raw[..., 0].mean())
            features.append(im_raw[..., 1].mean())
            features.append(im_raw[..., 2].mean())
        else:
            features.append(im_raw_flat.mean())
            features.append(im_raw_flat.mean())
            features.append(im_raw_flat.mean())

        #FEATURE 13: Maximum Pixel Value of the Histogram of Oriented Gradients
        im_fd, im_hog = feature.hog(im_raw_flat,
                                    orientations=8,
                                    pixels_per_cell=(16, 16),
                                    cells_per_block=(1, 1),
                                    visualise=True)
        features.append(im_hog.max())

        #FEATURE 14: Percent of image that is light versus dark with adaptive thresholding
        im_thres_flat = filter.threshold_adaptive(im_raw_flat, 100, 'mean')
        features.append(im_thres_flat.sum() / im_size)

        #FEATURE 15-17: Percent of image that is red/green/blue with adaptive thresholding
        im_thres_red = filter.threshold_adaptive(im_raw[..., 0], 100, 'mean')
        im_thres_green = filter.threshold_adaptive(im_raw[..., 1], 100, 'mean')
        im_thres_blue = filter.threshold_adaptive(im_raw[..., 2], 100, 'mean')
        features.append(im_thres_red.sum() / im_size)
        features.append(im_thres_green.sum() / im_size)
        features.append(im_thres_blue.sum() / im_size)

        #BUILD OUTPUT LIST FOR THIS IMAGE
        cat_path_features.append([im_cat, im_path, features])

        #CLEAR IMAGE PROC DATA
        del im_raw
        del im_raw_flat
        del im_raw_float
        del im_edge_sobel
        del im_canny
        del im_corners
        del im_felzen_segments
        del im_edge_vsobel
        del im_edge_hsobel
        del im_fd
        del im_hog

    return cat_path_features
Exemplo n.º 54
0
plt.imshow(gy)

mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)

plt.imshow(angle)

##

from skimage.filter import threshold_otsu, threshold_adaptive

global_thresh = threshold_otsu(gray0.astype(np.float32))
binary_global = gray0.astype(np.float32) > global_thresh
plt.imshow(binary_global)

block_size = 45
binary_adaptive = threshold_adaptive(gray0, block_size, offset=5)
plt.imshow(binary_adaptive)

from skimage.filters import gabor
from skimage import data, io
from matplotlib import pyplot as plt

#### ESSE E FODA !!!!!
filt_real, filt_imag = gabor(gray0, frequency=2.1)
plt.figure()
io.imshow(filt_real)
io.show()

plt.figure()
io.imshow(filt_imag)
io.show()
Exemplo n.º 55
0
def threshold(image, block_size=100, offset=-5):
    return image_filter.threshold_adaptive(renorm(image),
                                           block_size=block_size,
                                           offset=offset)
Exemplo n.º 56
0
from skimage import io
from skimage import filter
from skimage import img_as_uint
from skimage import data

image = io.imread('/home/mallikarjuna/Desktop/white.png')
#image2 = data.page()
#print (type(image2))
import numpy as np
#print(np.shape(image2))
global_thresh = filter.threshold_otsu(image)
binary_global = image > global_thresh
io.imsave('/home/mallikarjuna/Desktop/global2.png', img_as_uint(binary_global))

block_size = 35
binary_adaptive = filter.threshold_adaptive(image, block_size, offset=10)
io.imsave('/home/mallikarjuna/Desktop/adaptive2.png',
          img_as_uint(binary_adaptive))
fig, axes = plt.subplots(nrows=3, figsize=(7, 8))
ax0, ax1, ax2 = axes
plt.gray()

ax0.imshow(image)
ax0.set_title('Image')

ax1.imshow(binary_global)
ax1.set_title('Global thresholding')

ax2.imshow(binary_adaptive)
ax2.set_title('Adaptive thresholding')
                cv2.waitKey(1)
                if GPIO.input(button) == False:
                    break

            lcd.clear()
            lcd.message("Capturing Image.")
            speak("Capturing Image")
            time.sleep(2)

            ret, img = camera.read()

            camera.release()
            cv2.imwrite("test1.jpeg", img)

            warped = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            warped = threshold_adaptive(warped, 251, offset=10)
            warped = warped.astype("uint8") * 255

            time.sleep(1)
            lcd.clear()

            lcd.message("Image captured")
            speak("Image captured.")
            time.sleep(1)
            # show the original and scanned images
            print("STEP 3: Apply perspective transform")

            lcd.clear()
            lcd.message('Processing...')
            speak("Processing for the speech.")
            time.sleep(2)