def test_structuring_element8(): # check the output for a custom structuring element r = np.array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 255, 0, 0, 0], [0, 0, 255, 255, 255, 0], [0, 0, 0, 255, 255, 0], [0, 0, 0, 0, 0, 0]]) # 8-bit image = np.zeros((6, 6), dtype=np.uint8) image[2, 2] = 255 elem = np.asarray([[1, 1, 0], [1, 1, 1], [0, 0, 1]], dtype=np.uint8) out = np.empty_like(image) mask = np.ones(image.shape, dtype=np.uint8) rank.maximum(image=image, selem=elem, out=out, mask=mask, shift_x=1, shift_y=1) assert_array_equal(r, out) # 16-bit image = np.zeros((6, 6), dtype=np.uint16) image[2, 2] = 255 out = np.empty_like(image) rank.maximum(image=image, selem=elem, out=out, mask=mask, shift_x=1, shift_y=1) assert_array_equal(r, out)
def test_smallest_selem16(): # check that min, max and mean returns identity if structuring element # contains only central pixel image = np.zeros((5, 5), dtype=np.uint16) out = np.zeros_like(image) mask = np.ones_like(image, dtype=np.uint8) image[2, 2] = 255 image[2, 3] = 128 image[1, 2] = 16 elem = np.array([[1]], dtype=np.uint8) rank.mean(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(image, out) rank.minimum(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(image, out) rank.maximum(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(image, out)
def split_object(self, labeled_image): """ split object when it's necessary """ labeled_image = labeled_image.astype(np.uint16) labeled_mask = np.zeros_like(labeled_image, dtype=np.uint16) labeled_mask[labeled_image != 0] = 1 #ift structuring element about center point. This only affects eccentric structuring elements (i.e. selem with even num=============================== labeled_image = skr.median(labeled_image, skm.disk(4)) labeled_mask = np.zeros_like(labeled_image, dtype=np.uint16) labeled_mask[labeled_image != 0] = 1 distance = scipym.distance_transform_edt(labeled_image).astype(np.uint16) #======================================================================= # binary = np.zeros(np.shape(labeled_image)) # binary[labeled_image > 0] = 1 #======================================================================= distance = skr.mean(distance, skm.disk(15)) l_max = skr.maximum(distance, skm.disk(5)) #l_max = skf.peak_local_max(distance, indices=False,labels=labeled_image, footprint=np.ones((3,3))) l_max = l_max - distance <= 0 l_max = skr.maximum(l_max.astype(np.uint8), skm.disk(6)) marker = ndimage.label(l_max)[0] split_image = skm.watershed(-distance, marker) split_image[split_image[0,0] == split_image] = 0 return split_image
def test_empty_selem(): # check that min, max and mean returns zeros if structuring element is # empty image = np.zeros((5, 5), dtype=np.uint16) out = np.zeros_like(image) mask = np.ones_like(image, dtype=np.uint8) res = np.zeros_like(image) image[2, 2] = 255 image[2, 3] = 128 image[1, 2] = 16 elem = np.array([[0, 0, 0], [0, 0, 0]], dtype=np.uint8) rank.mean(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(res, out) rank.minimum(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(res, out) rank.maximum(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(res, out)
def test_compare_with_cmorph_dilate(): # compare the result of maximum filter with dilate image = (np.random.rand(100, 100) * 256).astype(np.uint8) out = np.empty_like(image) mask = np.ones(image.shape, dtype=np.uint8) for r in range(1, 20, 1): elem = np.ones((r, r), dtype=np.uint8) rank.maximum(image=image, selem=elem, out=out, mask=mask) cm = cmorph._dilate(image=image, selem=elem) assert_array_equal(out, cm)
def test_compare_with_cmorph_dilate(): # compare the result of maximum filter with dilate image = (np.random.random((100, 100)) * 256).astype(np.uint8) out = np.empty_like(image) mask = np.ones(image.shape, dtype=np.uint8) for r in range(1, 20, 1): elem = np.ones((r, r), dtype=np.uint8) rank.maximum(image=image, selem=elem, out=out, mask=mask) cm = cmorph.dilate(image=image, selem=elem) assert_array_equal(out, cm)
def test_percentile_max(): # check that percentile p0 = 1 is identical to local max img = data.camera() img16 = img.astype(np.uint16) selem = disk(15) # check for 8bit img_p0 = rank.percentile(img, selem=selem, p0=1.) img_max = rank.maximum(img, selem=selem) assert_array_equal(img_p0, img_max) # check for 16bit img_p0 = rank.percentile(img16, selem=selem, p0=1.) img_max = rank.maximum(img16, selem=selem) assert_array_equal(img_p0, img_max)
def substract_background(data, radius, background='mean', show=0): dmin, dmax = data.min(), data.max() tmp = ((data - dmin) / (dmax - dmin) * 255).astype(np.uint8) lforeground = rank.minimum(tmp, disk(radius // 2)) if background == 'mean': lbackground = rank.mean(lforeground, disk(radius * 4)).astype(int) elif background == 'median': lbackground = rank.median(lforeground, disk(radius * 4)).astype(int) elif background == 'maximum': lbackground = rank.maximum(lforeground, disk(radius * 4)).astype(int) else: lbackground = rank.modal(lforeground, disk(radius * 4)).astype(int) rdata = (lforeground - lbackground) if show > 2: fig, axes = plt.subplots(ncols=3, nrows=1, figsize=(30, 10)) for ax, im, title in zip(axes, [lforeground, lbackground, rdata], ['Foreground', 'Background', 'Substraction']): ax.imshow(im, 'optiona') ax.set_xticks([]) ax.set_yticks([]) ax.set_title(title) plt.show() return rdata
def test_16bit(): image = np.zeros((21, 21), dtype=np.uint16) selem = np.ones((3, 3), dtype=np.uint8) for bitdepth in range(17): value = 2**bitdepth - 1 image[10, 10] = value assert rank.minimum(image, selem)[10, 10] == 0 assert rank.maximum(image, selem)[10, 10] == value assert rank.mean(image, selem)[10, 10] == int(value / selem.size)
def test_16bit(): image = np.zeros((21, 21), dtype=np.uint16) selem = np.ones((3, 3), dtype=np.uint8) for bitdepth in range(17): value = 2 ** bitdepth - 1 image[10, 10] = value assert rank.minimum(image, selem)[10, 10] == 0 assert rank.maximum(image, selem)[10, 10] == value assert rank.mean(image, selem)[10, 10] == int(value / selem.size)
def test_empty_selem(): # check that min, max and mean returns zeros if structuring element is empty image = np.zeros((5, 5), dtype=np.uint16) out = np.zeros_like(image) mask = np.ones_like(image, dtype=np.uint8) res = np.zeros_like(image) image[2, 2] = 255 image[2, 3] = 128 image[1, 2] = 16 elem = np.array([[0, 0, 0], [0, 0, 0]], dtype=np.uint8) rank.mean(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(res, out) rank.minimum(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(res, out) rank.maximum(image=image, selem=elem, out=out, mask=mask, shift_x=0, shift_y=0) assert_array_equal(res, out)
def run(self, workspace): cell_object = workspace.object_set.get_objects(self.primary_objects.value) cell_labeled = cell_object.get_segmented() cell_image = cell_object.get_parent_image() cell_image = (cell_image * 1000).astype(np.uint16) # object_count = cell_labeled.max() maxi = skr.maximum(cell_image.astype(np.uint8), skm.disk(10)) local_max = maxi - cell_image < 10 local_max_labelize, object_count = scipy.ndimage.label(local_max, np.ones((3, 3), bool)) histo_local_max, not_use = np.histogram(local_max_labelize, range(object_count + 2)) old = local_max_labelize.copy() # filter in intensity mean # ======================================================================= # # regionprops_result = skmes.regionprops(local_max_labelize, intensity_image=cell_image) # # for region in regionprops_result: # if region["mean_intensity"] # ======================================================================= # filter on size for i in range(object_count + 1): value = histo_local_max[i] if value > self.range_size.max or value < self.range_size.min: local_max_labelize[local_max_labelize == i] = 0 # split granule for each cell cell_labeled = skm.label(cell_labeled) cell_count = np.max(cell_labeled) for cell_object_value in range(1, cell_count): cell_object_mask = cell_labeled == cell_object_value granule_in_cell = np.logical_and(cell_object_mask, local_max_labelize) granule_in_cell = skm.label(granule_in_cell) # =================================================================== # plt.imshow(granule_in_cell + cell_object_mask) # plt.show() # =================================================================== # # get the filename # measurements = workspace.measurements file_name_feature = self.source_file_name_feature filename = measurements.get_current_measurement("Image", file_name_feature) print "filename = ", filename
.. note:: `skimage.dilate` and `skimage.erode` are equivalent filters (see below for comparison). Here is an example of the classical morphological gray-level filters: opening, closing and morphological gradient. """ from skimage.filter.rank import maximum, minimum, gradient noisy_image = img_as_ubyte(data.camera()) closing = maximum(minimum(noisy_image, disk(5)), disk(5)) opening = minimum(maximum(noisy_image, disk(5)), disk(5)) grad = gradient(noisy_image, disk(5)) # display results fig = plt.figure(figsize=[10, 7]) plt.subplot(2, 2, 1) plt.imshow(noisy_image, cmap=plt.cm.gray) plt.title('Original') plt.axis('off') plt.subplot(2, 2, 2) plt.imshow(closing, cmap=plt.cm.gray) plt.title('Gray-level closing') plt.axis('off')
.. note:: `skimage.dilate` and `skimage.erode` are equivalent filters (see below for comparison). Here is an example of the classical morphological greylevel filters: opening, closing and morphological gradient. """ from skimage.filter.rank import maximum, minimum, gradient ima = data.camera() closing = maximum(minimum(ima, disk(5)), disk(5)) opening = minimum(maximum(ima, disk(5)), disk(5)) grad = gradient(ima, disk(5)) # display results fig = plt.figure(figsize=[10, 7]) plt.subplot(2, 2, 1) plt.imshow(ima, cmap=plt.cm.gray) plt.xlabel('original') plt.subplot(2, 2, 2) plt.imshow(closing, cmap=plt.cm.gray) plt.xlabel('greylevel closing') plt.subplot(2, 2, 3) plt.imshow(opening, cmap=plt.cm.gray) plt.xlabel('greylevel opening') plt.subplot(2, 2, 4)
plt.imshow(out_pile) try: io.imsave('C:/users/attialex/Desktop/out_pile_3.png', skimage.img_as_uint(out_pile)) io.imsave('C:/users/attialex/Desktop/out_cell_3.png', skimage.img_as_uint(out_cell)) except Exception as e: print e.message try: bg = normalize3Chan(imex * 1.) fg_c = normalize3Chan(out_cell) fg_p = normalize3Chan(out_pile) fg_c[:, :, 0] = 0 fg_c[:, :, 2] = 0 s1 = cv2.addWeighted(bg, .8, fg_c, .2, 0) cv2.imshow('cell', s1) s2 = cv2.addWeighted(bg, .8, fg_p, .2, 0) cv2.imshow('pile', s2) cv2.waitKey() except Exception as e: print e.message max_pile = maximum(out_pile, np.ones((40, 40))) unique_pile = np.unique(max_pile) max_cell = maximum(out_cell, np.ones((40, 40))) unique_cell = np.unique(max_cell) plt.show()
def run(self, workspace): '''Run the algorithm on one image set''' # # Get the image as a binary image # image_set = workspace.image_set image = image_set.get_image(self.image_name.value, must_be_binary=True) mask = image.pixel_data if image.has_mask: mask = mask & image.mask angle_count = self.angle_count.value # # We collect the i,j and angle of pairs of points that # are 3-d adjacent after erosion. # # i - the i coordinate of each point found after erosion # j - the j coordinate of each point found after erosion # a - the angle of the structuring element for each point found # i = np.zeros(0, int) j = np.zeros(0, int) a = np.zeros(0, int) ig, jg = np.mgrid[0:mask.shape[0], 0:mask.shape[1]] #this_idx = 0 for angle_number in range(angle_count): angle = float(angle_number) * np.pi / float(angle_count) strel = self.get_diamond(angle) erosion = binary_erosion(mask, strel) # # Accumulate the count, i, j and angle for all foreground points # in the erosion # this_count = np.sum(erosion) i = np.hstack((i, ig[erosion])) j = np.hstack((j, jg[erosion])) a = np.hstack((a, np.ones(this_count, float) * angle)) # # Find connections based on distances, not adjacency # first, second = self.find_adjacent_by_distance(i, j, a) # # Do all connected components. # if len(first) > 0: ij_labels = all_connected_components(first, second) + 1 nlabels = np.max(ij_labels) label_indexes = np.arange(1, nlabels + 1) # # Compute the measurements # center_x = fix(mean_of_labels(j, ij_labels, label_indexes)) center_y = fix(mean_of_labels(i, ij_labels, label_indexes)) # # The angles are wierdly complicated because of the wrap-around. # You can imagine some horrible cases, like a circular patch of # "linear object" in which all angles are represented or a gentle "U" # curve. # # For now, I'm going to use the following heuristic: # # Compute two different "angles". The angles of one go # from 0 to 180 and the angles of the other go from -90 to 90. # Take the variance of these from the mean and # choose the representation with the lowest variance. # # An alternative would be to compute the variance at each possible # dividing point. Another alternative would be to actually trace through # the connected components - both overkill for such an inconsequential # measurement I hope. # angles = fix(mean_of_labels(a, ij_labels, label_indexes)) vangles = fix( mean_of_labels((a - angles[ij_labels - 1])**2, ij_labels, label_indexes)) aa = a.copy() aa[a > np.pi / 2] -= np.pi aangles = fix(mean_of_labels(aa, ij_labels, label_indexes)) vaangles = fix( mean_of_labels((aa - aangles[ij_labels - 1])**2, ij_labels, label_indexes)) aangles[aangles < 0] += np.pi angles[vaangles < vangles] = aangles[vaangles < vangles] else: center_x = np.zeros(0, int) center_y = np.zeros(0, int) angles = np.zeros(0) nlabels = 0 label_indexes = np.zeros(0, int) labels = np.zeros(mask.shape, int) ifull = [] jfull = [] ij_labelsfull = [] labeldict = {} for label_id in np.unique(label_indexes): r = np.array(i) * (ij_labels == label_id) r = r[r != 0] c = np.array(j) * (ij_labels == label_id) c = c[c != 0] rect_strel = self.get_rectangle(angles[label_id - 1]) seedmask = np.zeros_like(mask, int) seedmask[r, c] = label_id reconstructedlinearobject = maximum(seedmask, rect_strel) reconstructedlinearobject = reconstructedlinearobject * mask if self.overlap_within_angle == False: itemp, jtemp = np.where(reconstructedlinearobject == label_id) ifull += list(itemp) jfull += list(jtemp) ij_labelsfull += [label_id] * len(itemp) else: itemp, jtemp = np.where(reconstructedlinearobject == label_id) labeldict[label_id] = zip(itemp, jtemp) if self.overlap_within_angle == True: angledict = {} for eachangle in range(len(angles)): angledict[eachangle + 1] = [angles[eachangle]] nmerges = 1 while nmerges != 0: nmerges = sum([ self.mergeduplicates(firstlabel, secondlabel, labeldict, angledict) for firstlabel in label_indexes for secondlabel in label_indexes if firstlabel != secondlabel ]) newlabels = labeldict.keys() newlabels.sort() newangles = angledict.keys() newangles.sort() angles = [] for eachnewlabel in range(len(newlabels)): ifull += [ int(eachloc[0]) for eachloc in labeldict[newlabels[eachnewlabel]] ] jfull += [ int(eachloc[1]) for eachloc in labeldict[newlabels[eachnewlabel]] ] ij_labelsfull += [eachnewlabel + 1] * len( labeldict[newlabels[eachnewlabel]]) angles.append(np.mean(angledict[newlabels[eachnewlabel]])) angles = np.array(angles) ijv = np.zeros([len(ifull), 3], dtype=int) ijv[:, 0] = ifull ijv[:, 1] = jfull ijv[:, 2] = ij_labelsfull # # Make the objects # object_set = workspace.object_set object_name = self.object_name.value assert isinstance(object_set, cpo.ObjectSet) objects = cpo.Objects() objects.ijv = ijv objects.parent_image = image object_set.add_objects(objects, object_name) if self.show_window: workspace.display_data.mask = mask workspace.display_data.overlapping_labels = [ l for l, idx in objects.get_labels() ] if self.overlap_within_angle == True: center_x = np.bincount(ijv[:, 2], ijv[:, 1])[objects.indices] / objects.areas center_y = np.bincount(ijv[:, 2], ijv[:, 0])[objects.indices] / objects.areas m = workspace.measurements assert isinstance(m, cpmeas.Measurements) m.add_measurement(object_name, I.M_LOCATION_CENTER_X, center_x) m.add_measurement(object_name, I.M_LOCATION_CENTER_Y, center_y) m.add_measurement(object_name, M_ANGLE, angles * 180 / np.pi) m.add_measurement(object_name, I.M_NUMBER_OBJECT_NUMBER, label_indexes) m.add_image_measurement(I.FF_COUNT % object_name, nlabels)
probs = sv.predict(td) out_cell = np.reshape(probs,(winds.shape[0],winds.shape[1])) plt.figure() plt.subplot(121) plt.imshow(out_cell) try: io.imsave('C:/users/attialex/Desktop/out_cell_4.png',skimage.img_as_uint(out_cell)) except Exception as e: print e.message try: bg = normalize3Chan(imex*1.) fg_c = normalize3Chan(out_cell) fg_c[:,:,0]=0; fg_c[:,:,2]=0; s1 = cv2.addWeighted(bg,.8,fg_c,.2,0) cv2.imshow('cell',s1) cv2.waitKey() except Exception as e: print e.message max_cell = maximum(out_cell,np.ones((40,40))) unique_cell = np.unique(max_cell) plt.show()
plt.subplot(122) plt.imshow(out_pile) try: io.imsave('C:/users/attialex/Desktop/out_pile_3.png',skimage.img_as_uint(out_pile)) io.imsave('C:/users/attialex/Desktop/out_cell_3.png',skimage.img_as_uint(out_cell)) except Exception as e: print e.message try: bg = normalize3Chan(imex*1.) fg_c = normalize3Chan(out_cell) fg_p = normalize3Chan(out_pile) fg_c[:,:,0]=0; fg_c[:,:,2]=0; s1 = cv2.addWeighted(bg,.8,fg_c,.2,0) cv2.imshow('cell',s1) s2 = cv2.addWeighted(bg,.8,fg_p,.2,0) cv2.imshow('pile',s2) cv2.waitKey() except Exception as e: print e.message max_pile = maximum(out_pile,np.ones((40,40))) unique_pile = np.unique(max_pile) max_cell = maximum(out_cell,np.ones((40,40))) unique_cell = np.unique(max_cell) plt.show()
def cr_max(image, selem): return maximum(image=image, selem=selem)
counter += 1 print 'predicting' probs = sv.predict(td) out_cell = np.reshape(probs, (winds.shape[0], winds.shape[1])) plt.figure() plt.subplot(121) plt.imshow(out_cell) try: io.imsave('C:/users/attialex/Desktop/out_cell_4.png', skimage.img_as_uint(out_cell)) except Exception as e: print e.message try: bg = normalize3Chan(imex * 1.) fg_c = normalize3Chan(out_cell) fg_c[:, :, 0] = 0 fg_c[:, :, 2] = 0 s1 = cv2.addWeighted(bg, .8, fg_c, .2, 0) cv2.imshow('cell', s1) cv2.waitKey() except Exception as e: print e.message max_cell = maximum(out_cell, np.ones((40, 40))) unique_cell = np.unique(max_cell) plt.show()