Beispiel #1
0
def PlayGame(model):

    # get init image
    reward, image, end = pong.sweet(10)
    image = rgb2gray(image)
    image = resize(image, (80, 80))
    thresh = threshold_mean(image)
    binary = image > thresh
    binary = np.expand_dims(binary, axis=2)

    reward = 0
    policy_images = []
    policy_action = []
    while True:
        action = model.predict(np.expand_dims(binary, axis=0))
        reward_now, nextImage, end = pong.sweet(action)
        if end:
            break
        policy_images.append(binary)
        policy_action.append(action)
        if reward_now > reward:
            reward = reward_now

        nextImage = rgb2gray(nextImage)
        nextImage = resize(image, (80, 80))
        thresh = threshold_mean(nextImage)
        binary = nextImage > thresh
        binary = np.expand_dims(binary, axis=2)

    return reward, np.asarray(policy_images), np.asarray(policy_action)
Beispiel #2
0
def burst_intensity(Data, n):

    intensity_matrix = Data[n]
    intensity_list = intensity_matrix.tolist()
    time = list(xrange(180))

    plt.plot(time, intensity_list, 'k')
    #plt.xlim([200,300])
    plt.xlim([50, 150])
    plt.xlabel('Time (Seconds)')
    plt.ylabel('Intensity')
    plt.title('Burst Intensity at 55 Mhz')

    #plt.hlines(threshold_otsu(Data), 100, 400, 'r', linestyles='dashed', label='Otsu')
    #plt.hlines(threshold_yen(Data), 100, 400, 'b', linestyles='dashed', label='Yen')
    #plt.hlines(threshold_isodata(Data), 100, 400, 'r', linestyles='dashed', label='Isodata')
    #plt.hlines(threshold_li(Data), 100, 400, 'g', linestyles='dashed', label='Li')
    #plt.hlines(threshold_minimum(Data), 100, 400, 'c', linestyles='dashed', label='Minimum')
    plt.hlines(threshold_mean(Data),
               0,
               400,
               'y',
               linestyles='dashed',
               label='Mean')
    #plt.hlines(threshold_triangle(Data), 100, 400, 'k', linestyles='dashed', label='Triangle')

    mean_1std = np.std(Data) + threshold_mean(Data)
    mean_2std = np.std(Data) + np.std(Data) + threshold_mean(Data)

    plt.hlines(mean_1std, 0, 400, 'r', linestyles='dashed', label='1σ')
    plt.hlines(mean_2std, 0, 400, 'r', linestyles='solid', label='2σ')

    plt.legend(loc='upper right', title="Thresholds")
    plt.show
    def _threshold_image(image_array, k, lightbg, darkbg):
        """
        Handler to properly threshold the image_array to a binary image of
        foreground and background. Algorithm used is a k-means clustering. 
        :param image_array: 
        :return: a 2D binary image
        """
        channel_image = ImageSegmenter._optimal_thresholding_channel_image(
            image_array)
        #histogram = ImageSegmenter._image_histogram(channel_image)
        #cluster_vector = ImageSegmenter._k_means_iterate(histogram, k)
        #has_light_bg = sum(histogram[0:50]) < sum(histogram[205:])
        #t0_min = threshold_minimum(image_array)

        if (lightbg == 'auto' and darkbg == 'auto'):
            # filter the image slightly
            sizefoot = [2, 2]
            channel_image = ndimage.median_filter(channel_image, sizefoot)
            channel_image = adjust_gamma(channel_image, gamma=1.4, gain=1)
            histogram = ImageSegmenter._image_histogram(channel_image)
            t0_min = threshold_mean(
                channel_image[0:np.argwhere(channel_image).max(0)[0],
                              0:np.argwhere(channel_image).max(0)[1]])
            has_light_bg = sum(histogram[0:5]) < sum(histogram[250:])
        else:
            channel_image = ImageSegmenter._optimal_thresholding_channel_image(
                image_array)
            histogram = ImageSegmenter._image_histogram(channel_image)
            t0_min = threshold_mean(channel_image)
            has_light_bg = sum(histogram[0:5]) < sum(histogram[250:])
        return ImageSegmenter._apply_cluster_threshold(
            t0_min, channel_image, has_light_bg, lightbg,
            darkbg)  # ImageSegmenter._has_dark_objects(channel_image))
Beispiel #4
0
def game(center):
    global V
    global zone
    global img_rgb
    global zone2
    global count_of_jps
    state = 0
    V = 110.0
    count_of_jps = 0
    for i in range(100000):
        img_rgb = get_img()
        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
        thresh = threshold_mean(img_gray)
        binary = (img_gray > thresh).astype(int)
        x_start, x_end = center[0] + width // 2, center[0] + width // 2 + int(
            V)
        y_start, y_end = center[1] - height // 2, center[1] + height // 2 - 15
        zone = binary[y_start:y_end, x_start:x_end]

        yt_start, yt_end = center[1] - height // 2, center[1] + height // 2 - 15
        zone2 = binary[yt_start:yt_end, x_start:x_end]
        if 0 in zone and state == 0:
            press()
            count_of_jps += 1
            V += (8.0 / 60)
            state = 1
        if (0 not in zone2) and state == 1:
            state = 2
            down()
        if (0 in zone2) and state == 2:
            state = 0
Beispiel #5
0
def threshold(img):
    #img = color.rgb2grey(img)
    #img = img[:,:,2]
    img = color.rgb2grey(img)
    thresh = filters.threshold_mean(img)
    binary = img > thresh
    return binary
def count_seg(filename):
    image = io.imread(filename)
    gray_image = color.rgb2gray(np.invert(image))
    thresh = filters.threshold_mean(gray_image)
    binary = gray_image > thresh
    label_arr, num_seg = ndi.label(np.invert(binary))
    return num_seg
Beispiel #7
0
def countCirciulatyC1(nda):
    thresh = threshold_mean(nda)
    binary = nda > thresh
    count = np.array(binary)
    a = np.count_nonzero(count == True)
    value = 2 * math.sqrt(a / math.pi)
    labelFirstValue.configure(text=value)
    def threshold(self, threshold_name):
        if self.scene.circles:
            self.scene.reset()
        if self.current_augments['overlay_applied']:
            del self.scene.coords
            self.init_scene()
            self.read_excel()
            self.current_augments['overlay_applied'] = False
        if threshold_name == "origional":
            self.showimage(self.overview)
            self.thresholdval = None
            self.current_augments["threshold"] = False
            return
        self.thresholdval = threshold_name

        im = rgb2gray(self.overview)
        if threshold_name == "otsu":
            threshold = threshold_otsu(im)
        if threshold_name == "li":
            threshold = threshold_li(im)
        if threshold_name == "mean":
            threshold = threshold_mean(im)
        if threshold_name == "triangle":
            threshold = threshold_triangle(im)
        self.current_augments["threshold"] = threshold_name
        self.current_image = im < threshold
        self.showimage(self.current_image)
Beispiel #9
0
def find_roi_bbox_1(rgb_image, show=False):  # rgb
    # hsv -> 3 channel
    hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)
    # plt.imshow(hsv)
    # plt.show()
    thres = threshold_mean(hsv[..., 0])
    # fig, ax = try_all_threshold(hsv[..., 0])
    # plt.show()
    mask = (hsv[..., 0] > thres).astype('uint8')

    # close_kernel = np.ones((11, 11), dtype=np.uint8)
    close_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
    image_close = cv2.morphologyEx(np.array(mask), cv2.MORPH_CLOSE,
                                   close_kernel)
    # open_kernel = np.ones((7, 7), dtype=np.uint8)
    open_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
    image_open = cv2.morphologyEx(np.array(image_close), cv2.MORPH_OPEN,
                                  open_kernel)
    image_open = cv2.morphologyEx(
        np.array(image_open), cv2.MORPH_DILATE,
        cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
    image_fill = hole_fill(image_open)
    image_fill = max_prop(image_fill)
    bounding_boxes, rgb_contour = get_bbox(np.array(image_fill), rgb_image,
                                           show)
    return bounding_boxes, rgb_contour, image_fill
Beispiel #10
0
def threshold(file='zones/0.png', t='otsu', img=None):
    from skimage.filters import try_all_threshold
    from skimage.filters import threshold_mean, threshold_li, threshold_otsu

    if img is None:
        img = misc.imread(file)

    fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False)
    plt.show()

    thresh = None
    if t == 'otsu':
        thresh = threshold_otsu(img)
    elif t == 'mean':
        thresh = threshold_mean(img)
    else:
        thresh = threshold_li(img)

    binary = img > thresh

    fig, axes = plt.subplots(ncols=2, figsize=(8, 3))
    ax = axes.ravel()

    ax[0].imshow(img, cmap=plt.cm.gray)
    ax[0].set_title('Original image')

    ax[1].imshow(binary, cmap=plt.cm.gray)
    ax[1].set_title('Result')

    for a in ax:
        a.axis('off')

    plt.show()
    return binary
Beispiel #11
0
def carve(roi, thresh=None, holes_area=None, return_unfilled=False):
    """Carve image by thresholding and filling in small holes.
    
    Args:
        roi: Image as Numpy array.
        thresh: Value by which to threshold. Defaults to None, in which 
            case a mean threshold will be applied.
        holes_area: Maximum area of holes to fill.
        return_unfilled: True to return the thresholded by unfilled image.
    
    Returns:
        Tuple of ``roi_carved``, the carved image; ``maks``, the mask 
        used to carve; and, if ``return_unfilled`` is True, ``roi_unfilled``, 
        the image after carving but before filling in holes.
    """
    roi_carved = np.copy(roi)
    if thresh is None:
        thresh = filters.threshold_mean(roi_carved)
    mask = roi_carved > thresh
    if holes_area:
        pxs_orig = np.sum(mask)
        mask = morphology.remove_small_holes(mask, holes_area)
        print("{} pxs in holes recovered".format(np.sum(mask) - pxs_orig))
        roi_unfilled = np.copy(roi_carved) if return_unfilled else None
    roi_carved[~mask] = 0

    if holes_area and return_unfilled:
        return roi_carved, mask, roi_unfilled
    return roi_carved, mask
def threshold_mean_filter(
    folder
):  # iterate through folders, assembling feature, label, and classname data objects
    class_id = 0
    features = []
    labels = np.array([])
    classnames = []
    for root, dirs, filenames in os.walk(folder):
        for d in sorted(dirs):
            #print("Reading data from", d)
            classnames.append(
                d)  # use the folder name as the class name for this label
            files = os.listdir(os.path.join(root, d))
            for f in files:
                imgFile = os.path.join(root, d, f)  # Load the image file
                img = plt.imread(imgFile)
                img = cv2.resize(
                    img,
                    (128,
                     128))  # Resizing all the images to insure proper reading
                img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                threshold_mean_filt = threshold_mean(img)

                features.append(threshold_mean_filt.ravel())
                labels = np.append(
                    labels, class_id)  # Add it to the numpy array of labels
            class_id += 1

    features = np.array(
        features)  # Convert the list of features into a numpy array
    return features, labels, classnames
Beispiel #13
0
def binary(img, method):
    """Threshold image

    :param img: grayscale image (numpy array)
    :param method: thresholding method
    :return: binary image
    """
    if method == 'otsu':
        thresh = threshold_otsu(img)
        binary = img > thresh

    elif method == 'mean':
        thresh = threshold_mean(img)
        binary = img > thresh
        binary = 1 - binary

    elif method == 'local':
        thresh = threshold_local(img, 35, offset=10)
        binary = img > thresh

    else:
        thresh = threshold_minimum(img)
        binary = img > thresh

    return binary
def itcd(input_img,
         smoothing=30,
         min_distance=10,
         thres_coef=1,
         equalization=False):
    """
    Returns boundaries of tree crowns in the imageself.
    Implementation of canopies thresholding and watershed segmentation.

    input_img: input image (np.array)
    """
    if equalization:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            input_img = equalize_adapthist(input_img)

    img_gaussian = gaussian(input_img, smoothing)

    canopy_mask = img_gaussian > thres_coef * threshold_mean(img_gaussian)

    masked_gaussian = np.copy(img_gaussian)
    masked_gaussian[canopy_mask == False] = 0

    local_maxima = peak_local_max(masked_gaussian,
                                  min_distance=min_distance,
                                  exclude_border=0,
                                  indices=False)
    markers, n_labels = ndi.label(local_maxima)

    segments = watershed(-img_gaussian, markers, mask=canopy_mask)
    # has to be modified in order to segment not segemented areas further
    # segments[np.where((segments==0) & (canopy_mask==True))] = n_labels+1

    return segments
Beispiel #15
0
def montage_wb_ratio(input_image, patch_shape, n_filters, ele_print=False):

    patches = view_as_windows(input_image, patch_shape)
    patches = patches.reshape(-1, patch_shape[0] * patch_shape[1])[::8]
    fb, _ = kmeans2(patches, n_filters, minit='random')
    fb = fb.reshape((-1, ) + patch_shape)
    fb_montage = montage2d(fb, fill=False, rescale_intensity=True)
    shape_var = np.ceil(np.sqrt(n_filters))
    elements = np.split(np.hstack(np.split(fb_montage, shape_var)),
                        shape_var**2,
                        axis=1)
    del elements[n_filters:]
    wb_ratios = []
    bin_elements = []

    for element in elements:
        thresh = threshold_mean(element)
        binary = element > thresh
        ratio = np.sum(binary) / binary.size
        wb_ratios.append(ratio)

        if ele_print:
            bin_elements.append(binary)

    wb_ratios = sorted(wb_ratios, reverse=True)

    if ele_print:
        show_images(elements)
        show_images(bin_elements)

    return (wb_ratios)
Beispiel #16
0
def get_pixelsize(img):
    # the linear measure is 20 micron
    line_length=20
    # 4th layer codes the pixelsize
    im = np.asarray(img,dtype=np.uint8)

    im_last=im[:,:,3]

    thresh = filters.threshold_mean(im_last)
    binary = im_last < thresh

    label_img = measure.label(binary)
    regions = measure.regionprops(label_img)

    length=np.NaN
    if len(regions)==1:
        bb = regions[0].bbox
        length=bb[3]-bb[1]
# length in pixel per micron    
        pixel_per_micron=length/line_length
    else:
        pixel_per_micron=1.5
    if pixel_per_micron<1:
        pixel_per_micron=1.5
    return pixel_per_micron
 def __apply_threshold(image_array):
     """
     Apply a mean threshold to the image information so that
     every mid-tones are converted to either black or white.
     :param {Numpy.ndarray} image_array: Input image array
     :return: {Numpy.ndarray} Bitmap containing only boolean values
     """
     return image_array > threshold_mean(image_array)
Beispiel #18
0
def classify_border(border_array):
    norm_arr = normalize(border_array)
    kernel = np.ones((3, 3)).astype("uint8")
    filtered_arr = opening(norm_arr, kernel)
    # thres = threshold_triangle(filtered_arr)
    thres = threshold_mean(filtered_arr)
    thres_img = filtered_arr > thres
    thres_img = thres_img.astype('uint8')
    return thres_img
Beispiel #19
0
    def threshold(self, thresh, **kwargs):
        """Threshold the image

        Parameters
        ----------
        thresh : str or float
            If a float in [0,1] is provided, pixels whose grayscale value is
            above said threshold will be white, others black.

            A number of additional methods are supported:

            *  'mean': Threshold image based on the mean of grayscale values.
            *  'minimum': Threshold image based on the minimum method, where
                          the histogram of the input image is computed and
                          smoothed until there are only two maxima.
            *  'local': Threshold image based on `local pixel neighborhood
                        <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_local>_.
                        Requires ``block_size``: odd number of pixels in the
                        neighborhood.
            *  'otsu': `Otsu's method
                       <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_otsu>_
            *  'isodata': `ISODATA method
                          <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_isodata>`_,
                          also known as the Ridler-Calvard method or
                          intermeans.

        Returns
        -------
        stim : `ImageStimulus`
            A copy of the stimulus object with two gray levels 0.0 and 1.0
        """
        if len(self.img_shape) > 2:
            raise ValueError("Thresholding is only supported for grayscale "
                             "(i.e., single-channel) images. Use `rgb2gray` "
                             "first.")
        img = self.data.reshape(self.img_shape)
        if isinstance(thresh, str):
            if thresh.lower() == 'mean':
                img = img > threshold_mean(img)
            elif thresh.lower() == 'minimum':
                img = img > threshold_minimum(img, **kwargs)
            elif thresh.lower() == 'local':
                img = img > threshold_local(img, **kwargs)
            elif thresh.lower() == 'otsu':
                img = img > threshold_otsu(img, **kwargs)
            elif thresh.lower() == 'isodata':
                img = img > threshold_isodata(img, **kwargs)
            else:
                raise ValueError("Unknown threshold method '%s'." % thresh)
        elif np.isscalar(thresh):
            img = self.data.reshape(self.img_shape) > thresh
        else:
            raise TypeError("Threshold type must be str or float, not "
                            "%s." % type(thresh))
        return ImageStimulus(img,
                             electrodes=self.electrodes,
                             metadata=self.metadata)
Beispiel #20
0
def threshold_mean(arr1d):
    """
    WORKS !!!
    :param arr1d:
    :return:
    """
    import skimage.filters as sf
    thresh = sf.threshold_mean(arr1d)
    return thresh
Beispiel #21
0
def hysteresis(image, alpha=1.0):
    """Hystersis thresholding with low and high clipped values
    determined by the mean, li and isodata threshold"""

    low = np.min([alpha * threshold_mean(image), threshold_li(image)])
    high = threshold_isodata(image)

    threshold = apply_hysteresis_threshold(image, low, high)

    return threshold
def getLowerThreshold(jellyimage):
    """
    Returns the expected lower threshold of an image based on mean pixel intensity.
    Through method testing the mean threshold was found to be best at segmenting the jellyfish
    :param jellyimage: rgb np image array (shape: y, x, 3)
    :return: float of intensity to threshold around
    """
    grayJelly = getGrayJelly(jellyimage)
    lower_bound = filters.threshold_mean(grayJelly)
    return lower_bound
Beispiel #23
0
def preprocessing(d):
    w, h = d.shape
    threshold = threshold_mean(d)
    # print(threshold)
    binary_value = d > threshold  #returns True or False
    shift = 2 * (binary_value * 1) - 1  # Boolean to int conversion
    # print(shift)
    # Reshape
    flatten = np.reshape(shift, (w * h))
    return flatten
Beispiel #24
0
def preprocessing(img):
    w, h = img.shape
    # Thresholding
    thresh = threshold_mean(img)
    binary = img > thresh
    shift = 2 * (binary * 1) - 1  # Boolian to int

    # Reshape
    flatten = np.reshape(shift, (w * h))
    return flatten
Beispiel #25
0
class BinaryAlg:
    _operations = {     
    'Isodata': lambda x : 1*((abs(x) > skfilters.threshold_isodata(x))),    
    'Li': lambda x : 1*((abs(x) > skfilters.threshold_li(x))), 
    'Mean': lambda x : 1*((abs(x) > skfilters.threshold_mean(x))),
    'Minimum': lambda x : 1*((abs(x) > skfilters.threshold_minimum(x))),
    'Otsu': lambda x : 1*((abs(x) > skfilters.threshold_otsu(x))),
    'Triangle': lambda x : 1*((abs(x) > skfilters.threshold_triangle(x))),
    'Yen': lambda x : 1*((abs(x) > skfilters.threshold_yen(x)))
    }   
Beispiel #26
0
def max_thresholding(im):
    '''Computes maximum projection and binarisation on images
    Input: Image to process
    Ouput: Image after Maximum projection and binarization
    '''

    max_im = np.max(im, axis=0)
    thresh = threshold_mean(max_im)
    binary_im = max_im > thresh
    return binary_im
Beispiel #27
0
    def _binarize(g_orig, erode=False, thresh_option='mean'):
        g_orig = rescale(g_orig)  # rescale mask to [0, 1]
        thresh = threshold_mean(
            g_orig) if thresh_option == 'mean' else threshold_local(
                g_orig, block_size=15)
        g = (g_orig > thresh).astype(np.float)
        if erode:  # Take 1-pixel radial erosion from the raw gt mask
            g = erosion(g, disk(1))

        return g
def label_segments(filename, savename='/testing_segment/', pwd=''):
    imgname = filename.split('/')[-1][:-4]
    image = io.imread(filename)
    gray_image = color.rgb2gray(image)
    thresh = filters.threshold_mean(gray_image)
    binary = gray_image > thresh
    bw_img = pwd + savename + imgname + '_binary.jpg'
    cv2.imwrite(bw_img, binary * 255)
    label_arr, num_seg = ndi.label(binary * 255)
    segments = np.arange(1, num_seg + 1)
    return binary, np.array(label_arr), segments, image
Beispiel #29
0
def removeBackground(img, hueValue, threshold=0):
    distance = hueDistance(img, hueValue)

    image_copy = img.copy()

    if threshold == 0:
        image_copy[distance < filters.threshold_mean(distance)] = 0
    else:
        image_copy[distance < threshold] = 0

    return image_copy
def preprocessing(img, w=100, h=100):
    # Resize image
    img = resize(img, (w,h), mode='reflect')

    # Thresholding
    thresh = threshold_mean(img)
    binary = img > thresh
    shift = 2*(binary*1)-1 # Boolian to int

    # Reshape
    flatten = np.reshape(shift, (w*h))
    return flatten
plt.show()

######################################################################
# How to apply a threshold?
# =========================
#
# Now, we illustrate how to apply one of these thresholding algorithms.
# This example uses the mean value of pixel intensities. It is a simple
# and naive threshold value, which is sometimes used as a guess value.
#

from skimage.filters import threshold_mean


image = data.camera()
thresh = threshold_mean(image)
binary = image > thresh

fig, axes = plt.subplots(ncols=2, figsize=(8, 3))
ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title('Original image')

ax[1].imshow(binary, cmap=plt.cm.gray)
ax[1].set_title('Result')

for a in ax:
    a.axis('off')

plt.show()