예제 #1
0
def get_sorted_edge(binary_img):
    # get distance transform
    D = distance_transform_edt(binary_img)
    max_r, max_c = np.where(D == D.max())[0][0], np.where(D == D.max())[1][0]

    # cut to edge
    edge = binary_img - erode(binary_img)

    # get list of edge points
    edge_points = list(zip(np.where(edge == 1)[0], np.where(edge == 1)[1]))

    # sort initially by distance from distance transform maximum
    sorted_edge = [min(edge_points, key=lambda e: np.sqrt((e[0] - max_r) ** 2 + (e[1] - max_c) ** 2))]

    # count through edge points
    index = 0
    while index < len(edge_points) - 1:
        current_edge = sorted_edge[index]
        next_edge = min(
            filter(lambda e: e not in sorted_edge, edge_points),
            key=lambda d: np.sqrt((d[0] - current_edge[0]) ** 2 + (d[1] - current_edge[1]) ** 2),
        )
        sorted_edge.append(next_edge)
        index += 1

    return (max_r, max_c), sorted_edge
예제 #2
0
np.ma.set_fill_value(x_wolimb,np.nan)
#obtaining this array with nan values in place of True
filledx = x_wolimb.filled()

#y is the  binary representation of x. ma.masked_inside places True/1 for values which are masked
# and False/0 for values which are not, that is values that remain post masking. Therefore applying logical not on it, to get true for values
#that remain after masking and false for values that are masked and finally converting them to 0 and 1
###includes pixels that are off the limb
y = np.logical_not(np.ma.masked_inside(smooth,-sig*std_smooth,sig*std_smooth).mask).astype(np.int)



##to make it work on le_wolimb, a masked array, had to fill the masked values
# and extract the filled array

le1 = erode(y,structure=np.ones((3,3))).astype(x.dtype)
le = dilate(le1,structure=[[True,True,True],[True,True,True],[True,True,True]]).astype(le1.dtype)
le_wolimb = np.ma.array(le,mask=limbmask)
np.ma.set_fill_value(le_wolimb,0.0)

#labeling islands leftover from erode and dilate without off limb pixels
island_lab = measurements.label(le_wolimb.filled())
labels = island_lab[0]


indx,indq = [[] for i in range(2)]
for j in range(dim[1]):
	for i in range(dim[2]):
		dum = q[:,j,i]
		dumdum = filledx[j,i]
		temp = np.dot(dum[0],dum[1:-1])
예제 #3
0
파일: util.py 프로젝트: apollo-dev/img-base
def edge_image(array):  # assumed to be binary
    return array - erode(array)
예제 #4
0
#yv = np.ma.masked_greater_equal(np.abs(filledxv),0.02).mask

levels = 1

#plotting masked contours of Q over V
fig3 = plt.figure(figsize=(12, 12))
ax3 = plt.axes()
im3 = plt.imshow(x, vmax=0.01, vmin=-0.01)
#im3 = plt.imshow(combv,vmax=0.08,vmin=-0.08,cmap='gray')
#im3_1 = plt.contour(y.astype(int),levels,origin='lower',colors = 'r')#,cmap=plt.get_cmap('jet'))
fig3.colorbar(im3)
fig3.tight_layout(pad=1.8)
plt.gca().invert_yaxis()
plt.suptitle('Contours of LP over combV')

le1 = erode(y, structure=np.ones((2, 2))).astype(x.dtype)
le = dilate(le1, structure=[[True, True], [True, True]]).astype(le1.dtype)

fig3 = plt.figure(figsize=(12, 12))
ax3 = plt.axes()
im3 = plt.imshow(le, vmax=0.01, vmin=-0.01)
#im3 = plt.imshow(combv,vmax=0.08,vmin=-0.08,cmap='gray')
#im3_1 = plt.contour(y.astype(int),levels,origin='lower',colors = 'r')#,cmap=plt.get_cmap('jet'))
fig3.colorbar(im3)
fig3.tight_layout(pad=1.8)
plt.gca().invert_yaxis()
plt.suptitle('Eroded and dilated')

##plotting masked contours of V over Q
#fig4 = plt.figure(figsize=(12,12))
#ax4 = plt.axes()
예제 #5
0
x = np.ma.greater(smooth, sig * thres)
#removing pixels off limb from array
x_wolimb = np.ma.array(x, mask=limbmask)
#changing the filled value in masked array from True to Nan
np.ma.set_fill_value(x_wolimb, np.nan)
#obtaining this array with nan values in place of True
filledx = x_wolimb.filled()

#masking values lesser than 3 sigma
#y = np.ma.greater(smooth,sig*std_smooth).astype(int)
y = np.logical_not(np.ma.equal(smooth, 90000)).astype(int)

##to make it work on le_wolimb, a masked array, had to fill the masked values
# and extract the filled array

le1 = erode(y, structure=np.ones((fac, fac))).astype(x.dtype)

le = dilate(le1, structure=np.ones((fac, fac)).astype(bool)).astype(le1.dtype)

le_wolimb = np.ma.array(le, mask=limbmask)
np.ma.set_fill_value(le_wolimb, 0.0)

#labeling islands leftover from erode and dilate without off limb pixels
island_lab = measurements.label(le_wolimb.filled())
labels = island_lab[0]

lad = np.copy(labels)
for i in range(1, island_lab[1] + 1):
    mk = np.ma.masked_equal(lad, i).mask
    temp = combq[mk]
    lim = 3.5 * np.mean(thres[mk])
예제 #6
0
def binary_edge(binary):
    return binary - erode(binary)
예제 #7
0
파일: ADD-CD.py 프로젝트: BPHO-Salk/ADD-CD
        
        # Reconstruct the file name
        
        mitoName = mGroup[mGroup['contourType'] == 'mitochondria.tiff'].to_string(header=False,index=False,index_names=False) # make sure we are looking just at mitochondria (not ER) and output the file name
        nameSplit = mitoName.split('  ') # split along spaces 
        mitoName = ' - '.join(nameSplit) # and join back with dases to achieve the original filename
        #print(mitoName) # should print outthe file name (ie., 1 - m1 - mitochondria.tif)
            
        mitoArray = Image.open(filepath+mitoName) # import the mitochondrial profile .tiff
        mitoArray = mitoArray.convert('L') # convert to grayscale
        mitoArray = mitoArray.point(lambda x: 0 if x<128 else 255, '1') # threshold and set mitochondria pixels to '1'
        mitoArray = np.array(mitoArray).astype(int) # convert to an array of integers (not booleans)
        mitoAreaPixelValue = np.sum(mitoArray)
        #print(mitoArray)
        
        erodedMitoArray = erode(mitoArray).astype(int) # create an eroded version of the mitochondria (eroded by 1 pixel by default)
        #print(erodedMitoArray)
        
        mitoPerimeterArray = mitoArray - erodedMitoArray # create a perimeter profile of the mitochondria
        #print(mitoPerimeterArray)
        #plt.imshow(mitoPerimeterArray) 
        #plt.show() # should print out the perimeter of the mitochondria
        
        mitoPerimeterPixelValue = np.sum(mitoPerimeterArray) # total number of pixels in the mitochondrial perimeter
        #print("Total mitochondrial perimeter pixels: ", mitoPerimeterPixelValue)

        ### Generating the array of mitochondrial dilation contours 
        
        dilationFactor = 1  ; # number of pixels to dilate each contour by
        contourNumber  = 100; #number of countours to make
                
예제 #8
0
def edge_image(array):  # assumed to be binary
    return array - erode(array)
예제 #9
0
    def handle(self, *args, **options):

        composite = Composite.objects.get(experiment__name="260714", series__name="15")

        # frames
        previous_frame_index = 0
        target_frame_index = 1
        next_frame_index = 2

        # stacks
        previous_gfp_stack = composite.gons.get(t=previous_frame_index, channel__name="0")
        previous_bf_stack = composite.gons.get(t=previous_frame_index, channel__name="1")

        target_gfp_stack = composite.gons.get(t=target_frame_index, channel__name="0")
        target_bf_stack = composite.gons.get(t=target_frame_index, channel__name="1")
        target_zmean_single = composite.gons.get(t=target_frame_index, channel__name="-zmean")
        target_zbf_single = composite.gons.get(t=target_frame_index, channel__name="-zbf")
        target_zmod_single = composite.gons.get(t=target_frame_index, channel__name="-zmod")

        next_gfp_stack = composite.gons.get(t=next_frame_index, channel__name="0")
        next_bf_stack = composite.gons.get(t=next_frame_index, channel__name="1")

        # images
        # previous_gfp = previous_gfp_stack.load()
        # previous_bf = previous_bf_stack.load()

        # target_gfp = target_gfp_stack.load()
        # target_bf = target_bf_stack.load()
        target_zmean = target_zmean_single.load() / 255.0
        target_zbf = target_zbf_single.load() / 255.0
        target_zbf_canny_s3 = canny(target_zbf, sigma=1).astype(float)
        target_zmod = target_zmod_single.load() / 255.0 * (composite.series.zs - 1)

        # next_gfp = next_gfp_stack.load()
        # next_bf = next_bf_stack.load()

        # 1. find maximum from marker
        # marker = composite.markers.get(pk=124)

        track_image = np.zeros(target_zmod.shape)

        class Traveller:
            movement_cost = 1
            directions = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]
            spawned = False

            def __init__(self, r, c, direction_index, money, cost_function):
                self.r = r
                self.c = c
                self.direction_index = direction_index
                self.drdc()
                self.money = money
                self.cost_function = cost_function

            def drdc(self):
                self.dr, self.dc = self.directions[self.direction_index]

            def move(self):
                # pick one of five directions in the direction of travel, find the one that costs the least money
                # get array of direction indices relative to current
                new_directions = [
                    (abs(i), (i if i < 8 else i - 8) if i >= 0 else i + 7)
                    for i in range(self.direction_index - 2, self.direction_index + 3)
                ]
                costs = []

                for cost_index, direction in new_directions:
                    dr, dc = self.directions[direction]
                    new_r, new_c = self.r + dr, self.c + dc

                    if (
                        0 <= new_r < composite.series.rs
                        and 0 <= new_c < composite.series.cs
                        and 0 <= self.r < composite.series.rs
                        and 0 <= self.c < composite.series.cs
                        and track_image[new_r, new_c] == 0
                    ):  # not out of bounds
                        # print(new_r, new_c, self.r, self.c, dr, dc)
                        # differences
                        delta_z = int(target_zmod[new_r, new_c]) - int(target_zmod[self.r, self.c])
                        delta_zbf = (target_zbf[new_r, new_c] - target_zbf[self.r, self.c]) / target_zbf[self.r, self.c]
                        delta_zmean = (target_zmean[new_r, new_c] - target_zmean[self.r, self.c]) / target_zmean[
                            self.r, self.c
                        ]

                        abs_zbf = target_zbf[new_r, new_c]
                        abs_zmean = target_zmean[new_r, new_c]

                        cost = self.cost_function(delta_z, delta_zbf, delta_zmean, abs_zbf, abs_zmean)
                        costs.append({"cost": cost, "direction": direction})

                if costs:
                    min_direction = min(costs, key=lambda c: c["cost"])
                    track_image[self.r, self.c] = 1
                    self.r, self.c = tuple(
                        np.array(self.directions[min_direction["direction"]]) + np.array((self.r, self.c))
                    )
                    self.money -= min_direction["cost"]
                else:
                    self.money = 0

        # cost functions
        def test_cost_function(delta_z, delta_zbf, delta_zmean, abs_zbf, abs_zmean):
            cost = 0

            cost += np.abs(delta_z) * 8
            cost += -delta_zbf * 4 if delta_zbf < 0 else 0
            # cost += -delta_zmean * 10.0

            return cost

        def dont_go_through_dark_edges(delta_z, delta_zbf, delta_zmean, abs_zbf, abs_zmean):
            cost = 0

            cost += np.abs(delta_z) * 4
            cost += -delta_zbf * 7 if delta_zbf < 0 else 0

            return cost

        def dont_go_to_another_z(delta_z, delta_zbf, delta_zmean, abs_zbf, abs_zmean):
            cost = 0

            cost += np.abs(delta_z) * 8

            return cost

        # set up segmentation - round 1
        travellers = []
        for marker in composite.markers.filter(track_instance__t=target_frame_index):
            for i in range(10):
                travellers.append(Traveller(marker.r, marker.c, np.random.randint(0, 7), 10, dont_go_to_another_z))

        iterations = 0
        while sum([t.money for t in travellers]) > 0:
            iterations += 1
            for traveller in travellers:
                if traveller.money > 0:
                    traveller.move()
                if traveller.money <= 0:
                    travellers.remove(traveller)
                    del traveller

        # spawn travellers from edge of track_image or round 2
        travellers = []
        track_edge = edge_image(track_image)
        for r, c in zip(*np.where(track_edge > 0)):
            travellers.append(Traveller(r, c, np.random.randint(0, 7), 10, dont_go_through_dark_edges))

        iterations = 0
        while sum([t.money for t in travellers]) > 0:
            iterations += 1
            for traveller in travellers:
                if traveller.money > 0:
                    traveller.move()
                if traveller.money <= 0:
                    travellers.remove(traveller)
                    del traveller

            # print(iterations, len(travellers), sum([t.money for t in travellers]))

        # cut = target_zmean[marker.r-10: marker.r+10, marker.c-10: marker.c+10]
        # plt.imshow(cut)
        # plt.show()

        track_image = dilate(erode(erode(dilate(track_image))))

        display_image = target_zbf.copy()
        display_image[track_image == 1] += 0.3
        plt.imshow(display_image)
        plt.show()