def test_binarization(): """Testing function binarization.binarization. Summary ------- We pass a test image to binarization.binarization and check if its results are equal to the expected. Expected -------- Expected tags, ruler and lepidopteran are equal to the ones returned by binarization.binarization. """ lepid_rgb = imread(IMAGE_RGB) tags_result, ruler_result, lepid_result = binarization.binarization( image_rgb=lepid_rgb, weights=WEIGHTS_BIN) tags_expected = img_as_bool(imread(TAGS_SEG)) assert (tags_expected.all() == tags_result.all()) ruler_expected = img_as_bool(imread(RULER_SEG)) assert (ruler_expected.all() == ruler_result.all()) lepid_expected = img_as_bool(imread(LEPID_SEG)) assert (lepid_expected.all() == lepid_result.all())
def binarize(img): """ Thresholds and binarizes the given image and returns the binarized image. """ gray_img = img_as_ubyte(rgb2gray(img)) height, width = gray_img.shape num_mid_gray = np.sum((gray_img < 240) & (gray_img > 15)) if num_mid_gray < 0.1 * height * width: # Global Thresholding thresh = threshold_otsu(gray_img) bw_img = gray_img > thresh else: # Adaptive Thresholding if height * width >= 2000 * 1000: gray_img = cv2.GaussianBlur(gray_img, ksize=(11, 11), sigmaX=3, sigmaY=3) # Set the window size of the filter based on image dimensions win_size = int(round(min(height / 60, width / 60))) # Get the window mean of each pixel by filtering using an averaging filter window_means = rank.mean(gray_img, np.ones((win_size, win_size))) print gray_img.dtype # Remove the mean and threshold. Also inverts the image. demeaned = window_means.astype(np.float32) - gray_img.astype( np.float32) - 10 demeaned[demeaned > 0] = 1.0 demeaned[demeaned <= 0] = 0.0 demeaned = img_as_float(demeaned) bw_img = img_as_ubyte(demeaned) # Remove small noise pixels. noise_size = int(0.0001 * height * width) bw_img = remove_small_objects(img_as_bool(bw_img), noise_size, connectivity=2) # Close gaps in edges bw_img = binary_closing(bw_img, square(4)) # Fill small holes (less than 5% of area of image) hole_size = int(0.0005 * height * width) bw_img = remove_small_holes(img_as_bool(bw_img), area_threshold=hole_size) # Return image to original polarity. bw_img = ~bw_img bw_img = img_as_ubyte(bw_img) # plt.figure() # plt.imshow(bw_img, cmap="gray") # plt.show() return bw_img
def tissue_region_from_rgb(_img, _min_area=150, _g_th=None): """ TISSUE_REGION_FROM_RGB detects the region(s) of the image containing the tissue. The original image is supposed to represent a haematoxylin-eosin -stained pathology slide. The main purpose of this function is to detect the parts of a large image which most probably contain tissue material, and to discard the background. Usage: tissue_mask = tissue_from_rgb(img, _min_area=150, _g_th=None) Args: img (numpy.ndarray): the original image in RGB color space _min_area (int, default: 150): any object with an area smaller than the indicated value, will be discarded _g_th (int, default: None): the processing is done on the GREEN channel and all pixels below _g_th are considered candidates for "tissue pixels". If no value is given to _g_th, one is computed by K-Means clustering (K=2), and is returned. Returns: numpy.ndarray: a binary image containing the mask of the regions considered to represent tissue fragments int: threshold used for GREEN channel """ if _g_th is None: # Apply vector quantization to remove the "white" background - work in the # green channel: vq = MiniBatchKMeans(n_clusters=2) _g_th = int( np.round(0.95 * np.max( vq.fit(_G(_img).reshape((-1, 1))).cluster_centers_.squeeze()))) mask = _G(_img) < _g_th skm.binary_closing(mask, skm.disk(3), out=mask) mask = img_as_bool(mask) mask = skm.remove_small_objects(mask, min_size=_min_area, in_place=True) # Some hand-picked rules: # -at least 5% H and E # -at most 25% background # for a region to be considered tissue h, e, b = rgb2he2(_img) mask &= (h > np.percentile(h, 5)) | (e > np.percentile(e, 5)) mask &= (b < np.percentile(b, 50)) # at most at 50% of "other components" mask = mh.close_holes(mask) return img_as_bool(mask), _g_th
def tissue_region_from_rgb(_img, _min_area=150, _g_th=None): """ TISSUE_REGION_FROM_RGB detects the region(s) of the image containing the tissue. The original image is supposed to represent a haematoxylin-eosin -stained pathology slide. The main purpose of this function is to detect the parts of a large image which most probably contain tissue material, and to discard the background. Usage: tissue_mask = tissue_from_rgb(img, _min_area=150, _g_th=None) Args: img (numpy.ndarray): the original image in RGB color space _min_area (int, default: 150): any object with an area smaller than the indicated value, will be discarded _g_th (int, default: None): the processing is done on the GREEN channel and all pixels below _g_th are considered candidates for "tissue pixels". If no value is given to _g_th, one is computed by K-Means clustering (K=2), and is returned. Returns: numpy.ndarray: a binary image containing the mask of the regions considered to represent tissue fragments int: threshold used for GREEN channel """ if _g_th is None: # Apply vector quantization to remove the "white" background - work in the # green channel: vq = MiniBatchKMeans(n_clusters=2) _g_th = int(np.round(0.95 * np.max(vq.fit(_G(_img).reshape((-1,1))) .cluster_centers_.squeeze()))) mask = _G(_img) < _g_th skm.binary_closing(mask, skm.disk(3), out=mask) mask = img_as_bool(mask) mask = skm.remove_small_objects(mask, min_size=_min_area, in_place=True) # Some hand-picked rules: # -at least 5% H and E # -at most 25% background # for a region to be considered tissue h, e, b = rgb2he2(_img) mask &= (h > np.percentile(h, 5)) | (e > np.percentile(e, 5)) mask &= (b < np.percentile(b, 50)) # at most at 50% of "other components" mask = mh.close_holes(mask) return img_as_bool(mask), _g_th
def test_selem_overflow(): strel = np.ones((17, 17), dtype=np.uint8) img = np.zeros((20, 20), dtype=bool) img[2:19, 2:19] = True binary_res = binary.binary_erosion(img, strel) grey_res = img_as_bool(grey.erosion(img, strel)) testing.assert_array_equal(binary_res, grey_res)
def test_footprint_overflow(): footprint = np.ones((17, 17), dtype=np.uint8) img = np.zeros((20, 20), dtype=bool) img[2:19, 2:19] = True binary_res = binary.binary_erosion(img, footprint) gray_res = img_as_bool(gray.erosion(img, footprint)) assert_array_equal(binary_res, gray_res)
def find_plate(img, radii_range): """ Identifies the location of the plate """ # Read image, and convert to floating point img = img_as_bool(imread(img, mode="F", flatten=True)) # Detect edges edges = canny(img, sigma=2) # Find circles hough_radii = np.arange(radii_range[0], radii_range[1], 2) hough_res = hough_circle(edges, hough_radii) centers, accums, radii = [], [], [] for radius, h in zip(hough_radii, hough_res): # For each radius, extract two circles num_peaks = 1 peaks = peak_local_max(h, num_peaks=num_peaks) centers.extend(peaks) accums.extend(h[peaks[:, 0], peaks[:, 1]]) radii.extend([radius] * num_peaks) center = np.mean(centers, axis=0) radius = (sum(radii) * 1.0) / len(radii) return center, radius
def test_selem_overflow(): strel = np.ones((17, 17), dtype=np.uint8) img = np.zeros((20, 20), dtype=bool) img[2:19, 2:19] = True binary_res = binary.binary_erosion(img, strel) gray_res = img_as_bool(gray.erosion(img, strel)) testing.assert_array_equal(binary_res, gray_res)
def rescale(img, params): scale_x = params['scale_x'] scale_y = params['scale_y'] order = params['order'] mode = params['mode'] cval = params['cval'] clip = params['clip'] anti_aliasing = params['anti_aliasing'] scale = (scale_x, scale_y) preserve_range = True if img.ndim == 2: multichannel = False else: multichannel = True retval = skimage.transform.rescale(img, scale, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, multichannel=multichannel, anti_aliasing=anti_aliasing) if img.dtype == np.uint8: return img_as_ubyte(retval) elif img.dtype == np.float64: return img_as_float64(retval) elif img.dtype == np.bool: return img_as_bool(retval) else: return retval
def fixedThreshold(img, params): if img.ndim > 2: raise ValueError("Threshold only applicable to grayscale images!") thresh = params['thresh'] maxval = 1 thresh_type = params['thresh_type'] thresh_algorithm = params['thresh_algorithm'] thresh_type = eval('cv2.{}'.format(thresh_type)) if thresh_algorithm == 'none': pass elif thresh_algorithm == 'otsu': thresh_type += cv2.THRESH_OTSU elif thresh_algorithm == 'triangle': thresh_type += cv2.THRESH_TRIANGLE _, retval = cv2.threshold(img, thresh, maxval, thresh_type) if thresh_type in [cv2.THRESH_BINARY, cv2.THRESH_BINARY_INV]: return img_as_bool(retval) elif thresh_type in [ cv2.THRESH_TRUNC, cv2.THRESH_TOZERO, cv2.THRESH_TOZERO_INV ]: return img_as_float64(retval) else: return retval
def Driver(): images = [os.path.basename(x) for x in glob.glob('images/*.png')] avD = 0 avS = 0 avH = 0 length = len(images) for i in range(0, length): I = util.img_as_float(io.imread('images/' + images[i])) J = util.img_as_bool(io.imread('groundtruth/thresh' + images[i])) A = segleaf(I) dsc = DSC(A, J) msd = MSD(A, J) hs = HS(A, J) print(images[i]) print("DSC: ", dsc) print("MSD: ", msd) print("HS: ", hs) if (dsc > 0.6): print("Recognized as a leaf") avD += dsc avS += msd avH += hs print("Average DSC: ", avD / length) print("Average MSD: ", avS / length) print("Average HS: ", avH / length)
def test_selem_overflow(): strel = np.ones((17, 17), dtype=np.uint8) img = np.zeros((20, 20)) img[2:19, 2:19] = 1 binary_res = binary.binary_erosion(img, strel) with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.erosion(img, strel)) testing.assert_array_equal(binary_res, grey_res)
def gt_transform(im): im = rgb2gray(im) if (GT_TRANSFORM == 'img_as_bool'): return img_as_bool(im) elif (GT_TRANSFORM == 'threshold_yen'): return im > threshold_yen(im) else: raise NotImplementedError( '`{}` tranform for GT not implemented.'.format(GT_TRANSFORM))
def imread_goldstd(image): """Auxiliary function intended to be used with skimage.io.ImageCollection. Helps to read and process Larson et al's gold standard images. """ data = io.imread(image) if np.unique(data).size > 2: data = data == 217 return util.img_as_bool(data)
def binarization(image_rgb, weights=WEIGHTS_BIN): """Extract the shape of the elements in an input image using the U-net deep learning architecture. Parameters ---------- image_rgb : (M, N, 3) ndarray Input RGB image of a lepidopteran, with ruler and tags. weights : str or pathlib.Path Path of the file containing weights for segmentation. Returns ------- tags_bin : (M, N) ndarray Binary image containing tags in the input image. ruler_bin : (M, N) ndarray Binary image containing the ruler in the input image. lepidop_bin : (M, N) ndarray Binary image containing the lepidopteran in the input image. """ if isinstance(weights, str): weights = Path(weights) connection.download_weights(weights) learner = load_learner(fname=weights) print('Processing U-net...') _, _, classes = learner.predict(image_rgb) _, tags_bin, ruler_bin, lepidop_bin = classes[:4] # rescale the predicted images back up and binarize them. tags_bin = img_as_bool(_rescale_image(image_rgb, tags_bin)) ruler_bin = img_as_bool(_rescale_image(image_rgb, ruler_bin)) lepidop_bin = img_as_bool(_rescale_image(image_rgb, lepidop_bin)) return tags_bin, ruler_bin, lepidop_bin
def skew_correct(im): im = ~im edges = canny(im, sigma=7) h, theta, d = hough_line(edges) h, theta, d = hough_line_peaks(h, theta, d, min_distance=0, min_angle=0, num_peaks=4) theta = [int(round(math.degrees(t))) for t in theta] if len(list(set(theta))) == 4: dominant_orientation = theta[0] else: dominant_orientation = max(theta, key=theta.count) # The dominant orientation will be detected as the complement of the # skewing angle. Subtract 90 degrees to get the deskewing angle. # (Subtracting from 90 gets the skewing angle. Deskewing angle is the # negative of that.) deskewing_angle = dominant_orientation - 90 print deskewing_angle # Limit angle to -45 to 45 while abs(deskewing_angle) > 45: deskewing_angle = deskewing_angle - (abs(deskewing_angle) / deskewing_angle) * 90 print deskewing_angle # Perform the deskewing deskew_img = rotate(im, deskewing_angle, mode='constant', cval=0, preserve_range=True, clip=True) deskew_img = deskew_img.astype(np.uint8) deskew_img = img_as_ubyte(deskew_img) # deskew_img = gaussian(deskew_img, sigma=0.4) deskew_img[deskew_img > 0] = 255 deskew_img = img_as_bool(deskew_img) # deskew_img = binary_closing(deskew_img, square(5)) deskew_img = ~deskew_img return deskew_img
def adaptiveThreshold(img, params): if img.ndim > 2: raise ValueError("Threshold only applicable to grayscale images!") maxval = 1 adaptive_method = params['adaptive_method'] thresh_type = params['thresh_type'] block_size = params['block_size'] subtract_cval = params['subtract_cval'] adaptive_method = eval('cv2.{}'.format(adaptive_method)) thresh_type = eval('cv2.{}'.format(thresh_type)) retval = cv2.adaptiveThreshold(img_as_ubyte(img), maxval, adaptive_method, thresh_type, block_size, subtract_cval) return img_as_bool(retval)
def mlss_auxiliar(image, detail, initial_level, level): ''' ''' sum_details = 0 for i in range(initial_level, level): temp = detail[i] * (image.max() / detail[i].max()) sum_details += temp # possivelmente normalizar aqui # output = np.array((sum_aux != 0), dtype=np.uint8)*255 output = img_as_bool(sum_details) return output
def avg_dice_coeff(target, prediction): with torch.no_grad(): run_dice_coeff = 0.0 batch_size = target.shape[0] assert batch_size == prediction.shape[0] true_mask = img_as_bool(target.cpu().numpy()) convt_pred = prediction.cpu().numpy() pred_mask = (convt_pred > 0.5) for index in range(batch_size): truth = true_mask[index, 0] predicted = pred_mask[index, 0] run_dice_coeff += dice_coeff(truth, predicted) run_dice_coeff /= batch_size return run_dice_coeff
def process_goldstd_images(data_goldstd): """Reads a gold standard image from Larson et al., returning only the fibers within it. Parameters ---------- data_goldstd : (M, N) array Input image from Larson et al. Returns ------- bin_goldstd : (M, N) array Binary image containing fibers detected by Larson et al.'s algorithm. """ if np.unique(data_goldstd).size > 2: data_goldstd = data_goldstd == 217 return util.img_as_bool(data_goldstd)
def Driver(): ''' Performs the Random Walker Segmentation on each of the noisy image files and does a DSC comparison with each equivelent ground truth image :return: Nothing ''' images = [os.path.basename(x) for x in glob.glob('noisyimages/*.png')] avD = 0 length = len(images) for i in range(0, length): I = util.img_as_float(io.imread('noisyimages/' + images[i])) J = util.img_as_bool(io.imread('groundtruth/thresh' + images[i])) A = segleaf(I) dsc = dice_coefficient(A, J) print(images[i]) print("DSC: ", dsc) if (dsc > 0.6): print("Recognized as a leaf") avD += dsc print("Average DSC: ", avD / length)
def avg_iou(target, prediction): with torch.no_grad(): run_iou = 0.0 batch_size = target.shape[0] assert batch_size == prediction.shape[0] true_mask = img_as_bool(target.cpu().numpy()) convt_pred = prediction.cpu().numpy() #convt_mask = (convt_target > 0.5) * 255 #pred_mask = convt_mask.astype(np.uint8) pred_mask = (convt_pred > 0.5) for index in range(batch_size): truth = true_mask[index, 0] predicted = pred_mask[index, 0] run_iou += iou(truth, predicted) run_iou /= batch_size return run_iou
def return_largest_region(image_bin): """Returns the largest region in the input image. Parameters ---------- image_bin : (M, N) ndarray A binary image. Returns ------- image_bin : (M, N) ndarray The input binary image containing only the largest region. """ props = regionprops(label(image_bin)) # largest_reg will receive the largest region properties. largest_reg = max(props, key=lambda x: x.area) image_bin[label(image_bin) != largest_reg.label] = 0 return img_as_bool(image_bin)
def segmentation(im_seg): im_seg_bool = img_as_bool(im_seg) im_inv = ~(im_seg_bool) plt.figure() plt.imshow(im_inv, cmap="gray") plt.show() se = ones((3, 3)) exp = binary_erosion(im_inv, se) eq_edges = exp ^ im_inv plt.figure() plt.imshow(eq_edges, cmap="gray") plt.show() lab = label(eq_edges, neighbors=8) reg = regionprops(lab) print len(reg) s = [item.centroid for item in reg] ch = [item.convex_image for item in reg] bb = [item.bbox for item in reg] imgs = [item.image for item in reg] bb = floor(bb) bb[:, 2:4] = bb[:, 2:4] + 1 idx = [] for i in len(s): x = ch[:i + 1, 1] y = ch[:i + 1, 2] for j in len(ch): x_ch = ch[:j + 1, 1] y_ch = ch[:j + 1, 1] p = Path( [(x_ch, y_ch)] ) # square with legs length 1 and bottom left corner at the origin if (sum(~p.contains_points([(x, y)]) == 0)) and (i != j): BB_outer
def difference_bin_gt(data_test, data_ref): """Returns where the resulting image and its ground truth differ. Parameters ---------- data_test : ndarray Test binary data. data_ref : ndarray Reference binary data. Returns ------- data_diff : ndarray Image showing where the resulting image and its ground truth differ. Notes ----- The reference binary data is also known as ground truth or gold standard. """ data_test = util.img_as_bool(data_test) data_ref = utils.process_goldstd_images(data_ref) return data_test ^ data_ref
def load_data(train_path, test_path, img_size): start = time.time() X_train = np.zeros( (len(train_ids), img_size, img_size, IMG_CHANNELS)) #, dtype=np.uint8 Y_train = np.zeros((len(train_ids), img_size, img_size, 1), dtype=np.bool) for i, _id in enumerate(train_ids): path = train_path + _id img = imread(path + '/images/' + _id + '.png')[:, :, :IMG_CHANNELS] img = resize(img, (img_size, img_size)) #[0, 255]->[0.0, 1.0] X_train[i] = img #print(np.unique(img, return_counts=True)) #print(np.unique(X_train[0], return_counts=True)) mask = np.zeros((img_size, img_size, 1), dtype=np.bool) for mask_file in next(os.walk(path + '/masks/'))[2]: mask_ = imread(path + '/masks/' + mask_file) # shape (256, 256), values: 0,255 #print(np.unique(mask_, return_counts=True)) mask_ = resize( mask_, (img_size, img_size) ) # preserve_range=False make (256, 256) 255.0 ->value range [0.1-1.0] mask_ = mask_[:, :, np.newaxis] #== np.expand_dims(mask_, axis=-1) mask_ = img_as_bool(mask_) #print(np.unique(mask_, return_counts=True)) mask = np.maximum(mask, mask_) Y_train[i] = mask X_test = np.zeros((len(test_ids), img_size, img_size, IMG_CHANNELS)) shapes_test = [] for i, _id in enumerate(test_ids): path = test_path + _id img = imread(path + '/images/' + _id + '.png')[:, :, :IMG_CHANNELS] shapes_test.append(img.shape) X_test[i] = resize(img, (img_size, img_size)) end = time.time() print("load data time: ", (end - start) / 60.0) return X_train, Y_train, X_test, shapes_test
def test_binary_opening(): strel = selem.square(3) binary_res = binary.binary_opening(bw_img, strel) grey_res = img_as_bool(grey.opening(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res)
def test_non_square_image(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img[:100, :200], strel) grey_res = img_as_bool(grey.erosion(bw_img[:100, :200], strel)) testing.assert_array_equal(binary_res, grey_res)
from skimage import io, util, morphology import numpy import scipy #img = util.img_as_bool(io.imread("itd33517_examples/binary2.pbm", as_gray=True)) #img = util.img_as_bool(io.imread("bilder/letters-and-objects.tif", as_gray=True)) #elems = util.img_as_bool(io.imread("itd33517_examples/se_cross.pbm", as_gray=True)) elems = numpy.ones((20, 20), dtype=bool) #ero = scipy.ndimage.morphology.binary_erosion(img, elems) #open = morphology.binary_dilation(img, elems) #bound = img * (1 - ero) #bound = img ^ ero comp = util.img_as_bool(io.imread("bilder/balls-with-reflections.tif")) img = numpy.invert(comp) seeds = util.img_as_bool(io.imread("washers_seeds.png", as_gray=True)) seeds_old = None count = 0 while not numpy.array_equal(seeds, seeds_old): count += 1 seeds_old = seeds.copy() seeds = scipy.ndimage.morphology.binary_dilation(seeds, elems) seeds *= comp print(count) out = img + seeds io.imsave("output.png", out * 255) #io.imshow(out) #io.show()
def main(): p = opt.ArgumentParser(description=""" Constructs a dictionary for image representation based on a set of specified local descriptors. The dictionary is built from a set of images given as a list in an input file. """) p.add_argument('config', action='store', help='a configuration file') args = p.parse_args() cfg_file = args.config parser = SafeConfigParser() parser.read(cfg_file) #--------- # sampler: if not parser.has_section('sampler'): raise ValueError('"sampler" section is mandatory') if not parser.has_option('sampler', 'type'): raise ValueError('"sampler.type" is mandatory') tmp = parser.get('sampler', 'type').lower() if tmp not in ['random', 'sliding']: raise ValueError('Unkown sampling type') sampler_type = tmp if not parser.has_option('sampler', 'window_size'): raise ValueError('"sampler.window_size" is mandatory') wnd_size = ast.literal_eval(parser.get('sampler', 'window_size')) if type(wnd_size) != tuple: raise ValueError('"sampler.window_size" specification error') it_start = (0,0) it_step = (1,1) if sampler_type == 'sliding': if parser.has_option('sampler', 'start'): it_start = ast.literal_eval(parser.get('sampler','start')) if parser.has_option('sampler', 'step'): it_step = ast.literal_eval(parser.get('sampler','step')) nwindows = parser.getint('sampler', 'nwindows') local_descriptors = [] #--------- # haar: if parser.has_section('haar'): tmp = True if parser.has_option('haar', 'norm'): tmp = parser.getboolean('haar', 'norm') if len(parser.items('haar')) == 0: # empty section, use defaults h = HaarLikeDescriptor(HaarLikeDescriptor.haars1()) else: h = HaarLikeDescriptor([ast.literal_eval(v) for n, v in parser.items('haar') if n.lower() != 'norm'], _norm=tmp) local_descriptors.append(h) #--------- # identity: if parser.has_section('identity'): local_descriptors.append(IdentityDescriptor()) #--------- # stats: if parser.has_section('stats'): tmp = [] if parser.has_option('stats', 'mean') and parser.getboolean('stats', 'mean'): tmp.append('mean') if parser.has_option('stats', 'std') and parser.getboolean('stats', 'std'): tmp.append('std') if parser.has_option('stats', 'kurtosis') and parser.getboolean('stats', 'kurtosis'): tmp.append('kurtosis') if parser.has_option('stats', 'skewness') and parser.getboolean('stats', 'skewness'): tmp.append('skewness') if len(tmp) == 0: tmp = None local_descriptors.append(StatsDescriptor(tmp)) #--------- # hist: if parser.has_section('hist'): tmp = (0.0, 1.0) tmp2 = 10 if parser.has_option('hist', 'min_max'): tmp = ast.literal_eval(parser.get('hist', 'min_max')) if type(tmp) != tuple: raise ValueError('"hist.min_max" specification error') if parser.has_option('hist', 'nbins'): tmp2 = parser.getint('hist', 'nbins') local_descriptors.append(HistDescriptor(_interval=tmp, _nbins=tmp2)) #--------- # HoG if parser.has_section('hog'): tmp = 9 tmp2 = (128, 128) tmp3 = (4, 4) if parser.has_option('hog', 'norient'): tmp = parser.getint('hog', 'norient') if parser.has_option('hog', 'ppc'): tmp2 = ast.literal_eval(parser.get('hog', 'ppc')) if type(tmp2) != tuple: raise ValueError('"hog.ppc" specification error') if parser.has_option('hog', 'cpb'): tmp3 = ast.literal_eval(parser.get('hog', 'cpb')) if type(tmp3) != tuple: raise ValueError('"hog.cpb" specification error') local_descriptors.append(HOGDescriptor(_norient=tmp, _ppc=tmp2, _cpb=tmp3)) #--------- # LBP if parser.has_section('lbp'): tmp = 3 tmp2 = 8*tmp tmp3 = 'uniform' if parser.has_option('lbp', 'radius'): tmp = parser.getint('lbp', 'radius') if parser.has_option('lbp', 'npoints'): tmp2 = parser.getint('lbp', 'npoints') if tmp2 == 0: tmp2 = 8* tmp if parser.has_option('lbp', 'method'): tmp3 = parser.get('lbp', 'method') local_descriptors.append(LBPDescriptor(radius=tmp, npoints=tmp2, method=tmp3)) #--------- # Gabor if parser.has_section('gabor'): tmp = np.array([0.0, np.pi / 4.0, np.pi / 2.0, 3.0 * np.pi / 4.0], dtype=np.double) tmp2 = np.array([3.0 / 4.0, 3.0 / 8.0, 3.0 / 16.0], dtype=np.double) tmp3 = np.array([1.0, 2 * np.sqrt(2.0)], dtype=np.double) if parser.has_option('gabor', 'theta'): tmp = ast.literal_eval(parser.get('gabor', 'theta')) if parser.has_option('gabor', 'freq'): tmp2 = ast.literal_eval(parser.get('gabor', 'freq')) if parser.has_option('gabor', 'sigma'): tmp3 = ast.literal_eval(parser.get('gabor', 'sigma')) local_descriptors.append(GaborDescriptor(theta=tmp, freq=tmp2, sigma=tmp3)) print('No. of descriptors: ', len(local_descriptors)) #--------- # data if not parser.has_section('data'): raise ValueError('Section "data" is mandatory.') data_path = parser.get('data', 'input_path') img_ext = parser.get('data', 'image_type') res_path = parser.get('data', 'output_path') img_files = glob.glob(data_path + '/*.' + img_ext) if len(img_files) == 0: return ## Process: sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # unbuferred output for img_name in img_files: print("Image: ", img_name, " ...reading... ", end='') im = imread(img_name) print("preprocessing... ", end='') # -preprocessing if im.ndim == 3: im_h, _, _ = rgb2he2(im) else: raise ValueError('Input image must be RGB.') # detect object region: # -try to load a precomputed mask: mask_file_name = data_path+'/mask/'+ \ os.path.splitext(os.path.split(img_name)[1])[0]+ \ '_tissue_mask.pbm' if os.path.exists(mask_file_name): print('(loading mask)...', end='') mask = imread(mask_file_name) mask = img_as_bool(mask) mask = remove_small_objects(mask, min_size=500, connectivity=1, in_place=True) else: print('(computing mask)...', end='') mask, _ = tissue_region_from_rgb(im, _min_area=500) row_min, col_min, row_max, col_max = bounding_box(mask) im_h[np.logical_not(mask)] = 0 # make sure background is 0 mask = None im = None im_h = im_h[row_min:row_max+1, col_min:col_max+1] print("growing the bag...", end='') # -image bag growing bag = None # bag for current image for d in local_descriptors: if bag is None: bag = grow_bag_from_new_image(im_h, d, wnd_size, nwindows, discard_empty=True) else: bag[d.name] = grow_bag_with_new_features(im_h, bag['regs'], d)[d.name] # save the results for each image, one file per descriptor desc_names = bag.keys() desc_names.remove('regs') # keep all keys but the regions # -save the ROI from the original image: res_file = res_path + '/' + 'roi-' + \ os.path.splitext(os.path.split(img_name)[1])[0] + '.dat' with open(res_file, 'w') as f: f.write('\t'.join([str(x_) for x_ in [row_min, row_max, col_min, col_max]])) for dn in desc_names: res_file = res_path + '/' + dn + '_bag-' + \ os.path.splitext(os.path.split(img_name)[1])[0] + '.dat' with open(res_file, 'w') as f: n = len(bag[dn]) # total number of descriptors of this type for i in range(n): s = '\t'.join([str(x_) for x_ in bag['regs'][i]]) + '\t' + \ '\t'.join([str(x_) for x_ in bag[dn][i]]) + '\n' f.write(s) print('OK') bag = None gc.collect() gc.collect()
def test_binary_opening(): strel = selem.square(3) binary_res = binary.binary_opening(bw_img, strel) gray_res = img_as_bool(gray.opening(bw_img, strel)) testing.assert_array_equal(binary_res, gray_res)
def test_non_square_image(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img[:100, :200], strel) gray_res = img_as_bool(gray.erosion(bw_img[:100, :200], strel)) testing.assert_array_equal(binary_res, gray_res)
def test_non_square_image(): strel = selem.square(3) binary_res = binary.binary_erosion(bw_img[:100, :200], strel) with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.erosion(bw_img[:100, :200], strel)) testing.assert_array_equal(binary_res, grey_res)
def test_binary_closing(): strel = selem.square(3) binary_res = binary.binary_closing(bw_lena, strel) grey_res = img_as_bool(grey.closing(bw_lena, strel)) testing.assert_array_equal(binary_res, grey_res)
def test_binary_dilation(): strel = selem.square(3) binary_res = binary.binary_dilation(bw_lena, strel) grey_res = img_as_bool(grey.dilation(bw_lena, strel)) testing.assert_array_equal(binary_res, grey_res)
def test_binary_opening(): strel = selem.square(3) binary_res = binary.binary_opening(bw_img, strel) with expected_warnings(['precision loss']): grey_res = img_as_bool(grey.opening(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res)
def test_binary_dilation(): strel = selem.square(3) binary_res = binary.binary_dilation(bw_img, strel) grey_res = img_as_bool(grey.dilation(bw_img, strel)) testing.assert_array_equal(binary_res, grey_res)
import matplotlib.pyplot as plt from skimage import io, util # Load image image = io.imread('imgs/wyeth.jpg') image = util.img_as_float(image) mask = io.imread('imgs/wyeth_mask.jpg', as_grey=True) mask = util.img_as_bool(mask) plt.subplot(1, 2, 1) plt.title('Original Image') plt.imshow(image) plt.subplot(1, 2, 2) plt.title('Mask of the object to remove') plt.imshow(mask) plt.show() from seam_carving import remove_object # Use your function to remove the object out = remove_object(image, mask) plt.subplot(2, 2, 1) plt.title('Original Image') plt.imshow(image) plt.subplot(2, 2, 2) plt.title('Mask of the object to remove') plt.imshow(mask)