Re-segments a color image to isolate an object of interest using foreground masking and kmeans
543407
def _segment_color(self, color_im, bounding_box, bgmodel, cfg, vis_segmentation=False):
        
        # read params
        foreground_mask_tolerance = cfg['foreground_mask_tolerance']
        color_seg_rgb_weight = cfg['color_seg_rgb_weight']
        color_seg_num_clusters = cfg['color_seg_num_clusters']
        color_seg_hsv_weight = cfg['color_seg_hsv_weight']
        color_seg_dist_pctile = cfg['color_seg_dist_pctile']
        color_seg_dist_thresh = cfg['color_seg_dist_thresh']
        color_seg_min_bg_dist = cfg['color_seg_min_bg_dist']
        min_contour_area= cfg['min_contour_area']
        contour_dist_thresh = cfg['contour_dist_thresh']

        # foreground masking
        binary_im = color_im.foreground_mask(foreground_mask_tolerance, bgmodel=bgmodel)
        binary_im = binary_im.prune_contours(area_thresh=min_contour_area, dist_thresh=contour_dist_thresh)
        if binary_im is None:
            return None, None, None

        color_im = color_im.mask_binary(binary_im)

        # kmeans segmentation
        segment_im = color_im.segment_kmeans(color_seg_rgb_weight,
                                             color_seg_num_clusters,
                                             hue_weight=color_seg_hsv_weight)
        
        # keep the segment that is farthest from the background
        bg_dists = []
        hsv_bgmodel = 255 * np.array(colorsys.rgb_to_hsv(float(bgmodel[0]) / 255,
                                                         float(bgmodel[1]) / 255,
                                                         float(bgmodel[2]) / 255))
        hsv_bgmodel = np.r_[color_seg_rgb_weight * np.array(bgmodel), color_seg_hsv_weight * hsv_bgmodel[:1]]

        for k in range(segment_im.num_segments-1):
            seg_mask = segment_im.segment_mask(k)
            color_im_segment = color_im.mask_binary(seg_mask)
            color_im_segment_data = color_im_segment.nonzero_data()
            color_im_segment_data = np.c_[color_seg_rgb_weight * color_im_segment_data, color_seg_hsv_weight * color_im_segment.nonzero_hsv_data()[:,:1]]

            # take the median distance from the background
            bg_dist = np.median(np.linalg.norm(color_im_segment_data - hsv_bgmodel, axis=1))
            if vis_segmentation:
                logging.info('BG Dist for segment %d: %.4f' %(k, bg_dist))
            bg_dists.append(bg_dist)

        # sort by distance
        dists_and_indices = zip(np.arange(len(bg_dists)), bg_dists)
        dists_and_indices.sort(key = lambda x: x[1], reverse=True)
        
        # mask out the segment in the binary image
        if color_seg_num_clusters > 1 and abs(dists_and_indices[0][1] - dists_and_indices[1][1]) > color_seg_dist_thresh and dists_and_indices[1][1] < color_seg_min_bg_dist:
            obj_segment = dists_and_indices[0][0]
            obj_seg_mask = segment_im.segment_mask(obj_segment)
            binary_im = binary_im.mask_binary(obj_seg_mask)
            binary_im, diff_px = binary_im.center_nonzero()
            bounding_box = Box(bounding_box.min_pt.astype(np.float32) - diff_px,
                               bounding_box.max_pt.astype(np.float32) - diff_px,
                               bounding_box.frame)

        if vis_segmentation:
            plt.figure()
            plt.subplot(1,3,1)
            plt.imshow(color_im.data)
            plt.axis('off')
            plt.subplot(1,3,2)
            plt.imshow(segment_im.data)
            plt.colorbar()
            plt.axis('off')
            plt.subplot(1,3,3)
            plt.imshow(binary_im.data, cmap=plt.cm.gray)
            plt.axis('off')
            plt.show()

        return binary_im, segment_im, bounding_box
1233932
def draw_mask(im, mask, alpha=0.5, color=None):
    
    if color is None:
        color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]
    im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),
                  im * (1 - alpha) + color * alpha, im)
    im = im.astype('uint8')
    return im
776551
def imscatter(images, positions):
    '''
        
    '''
    positions = np.array(positions)

    bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
    tops = bottoms + np.array([im.shape[1] for im in images])

    lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images])
    rigths = lefts + np.array([im.shape[0] for im in images])

    most_bottom = int(np.floor(bottoms.min()))
    most_top = int(np.ceil(tops.max()))

    most_left = int(np.floor(lefts.min()))
    most_right = int(np.ceil(rigths.max()))

    scatter_image = np.zeros(
        [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype)

    # shift, now all from zero
    positions -= [most_left, most_bottom]

    for im, pos in zip(images, positions):

        xl = int(pos[0] - im.shape[0] / 2)
        xr = xl + im.shape[0]

        yb = int(pos[1] - im.shape[1] / 2)
        yt = yb + im.shape[1]

        scatter_image[xl:xr, yb:yt, :] = im
    return scatter_image
815075
def copy_image_on_background(image, color=WHITE):
    
    background = Image.new("RGB", image.size, color)
    background.paste(image, mask=image.split()[3])
    return background
932696
def fastFilter(arr, ksize=30, every=None, resize=True, fn='median',
                  interpolation=cv2.INTER_LANCZOS4,
                  smoothksize=0,
                  borderMode=cv2.BORDER_REFLECT):
    '''
    
    '''
    if every is None:
        every = max(ksize//3, 1)
    else:
        assert ksize >= 3*every
    s0,s1 = arr.shape[:2]
    
    ss0 = s0//every
    every = s0//ss0
    ss1 = s1//every
    
    out = np.full((ss0+1,ss1+1), np.nan)
    
    c = {'median':_calcMedian,
         'nanmedian':_calcNanMedian,
         'nanmean':_calcNanMean,
         'mean':_calcMean,
         }[fn]
    ss0,ss1 = c(arr, out, ksize, every)
    out = out[:ss0,:ss1]
    
    if smoothksize:
        out = gaussian_filter(out, smoothksize)
        
    
    if not resize:
        return out
    return cv2.resize(out, arr.shape[:2][::-1],
               interpolation=interpolation)
533005
def composite(
    background_image,
    foreground_image,
    foreground_width_ratio=0.25,
    foreground_position=(0.0, 0.0),
):
    """"""

    if foreground_width_ratio <= 0:
        return background_image

    composite = background_image.copy()
    width = int(foreground_width_ratio * background_image.shape[1])
    foreground_resized = resize(foreground_image, width)
    size = foreground_resized.shape

    x = int(foreground_position[1] * (background_image.shape[1] - size[1]))
    y = int(foreground_position[0] * (background_image.shape[0] - size[0]))

    # TODO: warn if resulting coordinates are out of bounds?
    composite[y : y + size[0], x : x + size[1]] = foreground_resized

    return composite
861834
def _remove_white_background(image):
    """"""
    from PIL import ImageMath, Image
    if image.mode == "RGBA":
        bands = image.split()
        a = bands[3]
        rgb = [
            ImageMath.eval(
                'convert('
                'float(x + a - 255) * 255.0 / float(max(a, 1)) * '
                'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'
                ', "L")',
                x=x, a=a
            )
            for x in bands[:3]
        ]
        return Image.merge(bands=rgb + [a], mode="RGBA")

    return image
1312524
function analyzePixels() {

    var len = pixels.length;
    var nPix = len / 3;
    indexedPixels = [];
    var nq = new NeuQuant(pixels, len, sample);

    // initialize quantizer
    colorTab = nq.process(); // create reduced palette

    // map image pixels to new palette
    var k = 0;
    for (var j = 0; j < nPix; j++) {
      var index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff);
      usedEntry[index] = true;
      indexedPixels[j] = index;
    }

    pixels = null;
    colorDepth = 8;
    palSize = 7;

    // get closest match to transparent color if specified
    if (transparent !== null) {
      transIndex = findClosest(transparent);
    }
  }
681697
def _correctDarkCurrent(self, image, exposuretime, bgImages, date):
        '''
        
        '''
        # either exposureTime or bgImages has to be given
#         if exposuretime is not None or bgImages is not None:
        print('... remove dark current')

        if bgImages is not None:

            if (type(bgImages) in (list, tuple) or
                    (isinstance(bgImages, np.ndarray) and
                     bgImages.ndim == 3)):
                if len(bgImages) > 1:
                    # if multiple images are given: do STE removal:
                    nlf = self.noise_level_function
                    bg = SingleTimeEffectDetection(
                        bgImages, nStd=4,
                        noise_level_function=nlf).noSTE
                else:
                    bg = imread(bgImages[0])
            else:
                bg = imread(bgImages)
        else:
            bg = self.calcDarkCurrent(exposuretime, date)
        self.temp['bg'] = bg
        image -= bg
219445
def _to_image_partial_overlap(self, image):
        

        # find the overlap of the mask on the output image shape
        slices_large, slices_small = self._overlap_slices(image.shape)

        if slices_small is None:
            return None    # no overlap

        # insert the mask into the output image
        image[slices_large] = self.data[slices_small]

        return image
649275
def invert_pixel_mask(mask):
    '''
    '''
    inverted_mask = np.ones(shape=(80, 336), dtype=np.dtype('>u1'))
    inverted_mask[mask >= 1] = 0
    return inverted_mask
795945
def _extract_mask_distance(image, mask = slice(None), voxelspacing = None):
    
    if isinstance(mask, slice):
        mask = numpy.ones(image.shape, numpy.bool)
    
    distance_map = distance_transform_edt(mask, sampling=voxelspacing)
    
    return _extract_intensities(distance_map, mask)
1277838
def clean(image, mask=None, iterations = 1):
    '''
    '''
    global clean_table
    if mask is None:
        masked_image = image
    else:
        masked_image = image.astype(bool).copy()
        masked_image[~mask] = False
    result = table_lookup(masked_image, clean_table, False, iterations)
    if not mask is None:
        result[~mask] = image[~mask]
    return result
861632
def _generate_segments(im_orig, scale, sigma, min_size):
    

    # open the Image
    im_mask = skimage.segmentation.felzenszwalb(
        skimage.util.img_as_float(im_orig), scale=scale, sigma=sigma,
        min_size=min_size)

    # merge mask channel to the image as a 4th channel
    im_orig = numpy.append(
        im_orig, numpy.zeros(im_orig.shape[:2])[:, :, numpy.newaxis], axis=2)
    im_orig[:, :, 3] = im_mask

    return im_orig
263103
def mask_image_data(data):
    """"""
    if data.bands.size in (2, 4):
        if not np.issubdtype(data.dtype, np.integer):
            raise ValueError("Only integer datatypes can be used as a mask.")
        mask = data.data[-1, :, :] == np.iinfo(data.dtype).min
        data = data.astype(np.float64)
        masked_data = da.stack([da.where(mask, np.nan, data.data[i, :, :])
                                for i in range(data.shape[0])])
        data.data = masked_data
        data = data.sel(bands=BANDS[data.bands.size - 1])
    return data
1128154
def fitImg(self, img_rgb):
        '''
        
        '''
        H = self.pattern.findHomography(img_rgb)[0]
        H_inv = self.pattern.invertHomography(H)
        s = self.img_orig.shape
        warped = cv2.warpPerspective(img_rgb, H_inv, (s[1], s[0]))
        return warped
1088382
function extractHOGFromHistograms(histograms, options) {
  var blockSize = options.blockSize || 2;
  var blockStride = options.blockStride || (blockSize / 2);
  var normalize = norms[options.norm || "L2"];

  var blocks = [];
  var blocksHigh = histograms.length - blockSize + 1;
  var blocksWide = histograms[0].length - blockSize + 1;

  for (var y = 0; y < blocksHigh; y += blockStride) {
    for (var x = 0; x < blocksWide; x += blockStride) {
      var block = getBlock(histograms, x, y, blockSize);
      normalize(block);
      blocks.push(block);
    }
  }
  return Array.prototype.concat.apply([], blocks);
}