def test_object(): image = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) expected_conn_1 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, connectivity=1), expected_conn_1) expected_conn_2 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, connectivity=2), expected_conn_2) with testing.raises(ValueError): convex_hull_object(image, connectivity=3) out = convex_hull_object(image, connectivity=1) assert_array_equal(out, expected_conn_1)
def test_object(): image = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) expected4 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 4), expected4) expected8 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 8), expected8) assert_raises(ValueError, convex_hull_object, image, 7)
def test_object(): image = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) expected4 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 4), expected4) expected8 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 8), expected8) assert_raises(ValueError, convex_hull_object, image, 7) # Test that an error is raised on passing a 3D image: image3d = np.empty((5, 5, 5)) assert_raises(ValueError, convex_hull_object, image3d)
def process(self): # self.open() # self.show() self.mark_white() # self.show() self.open() # self.show() self.altered_image = morphology.convex_hull_object(self.altered_image) self.image = self.image_X_mask(mask=self.altered_image, source=self.image) # self.show() self.mark_colors() self.altered_image = morphology.closing( self.altered_image, morphology.disk(len(self.altered_image) / 35)) self.image = self.image_X_mask(mask=self.altered_image, source=self.image) # self.find_contours() # najpierw znajdź całą kartkę paragonu # potem konkretne plamki (albo od razu plamik) # przejdź po znalezionych plamkach (konturach) i znajdź tą, która może mieć ceny na sobie. # np. (zobaczyć która ma dużo podobnych kolorów + jest otoczona przez biel albo jakkolwiek inaczej.) # lub wziąć tą najbardziej na prawo # spośród pixeli wewnątrz konturu(plamki) stworzyć nowy obrazek // kontur to tylko ramka # wysłać ten obrazek do jakiejś funkcji foo, którą ja będę pisał :) # foo powinna zwracać true jeśli znalazła ceny w plamce, false jeśli nie return self.image
def pictureFindEdge(pic,multiple=0,threshold=0.5): img_gray = pic img_gray_bin=(img_gray<threshold)*1#二值化 chull = morphology.convex_hull_object(img_gray_bin)#框定连通区域 labels=measure.label(chull,connectivity=2) # 8连通区域标记 point_l=np.zeros(labels.max()+1,dtype=np.int16);point_r=np.zeros(labels.max()+1,dtype=np.int16) point_t=np.zeros(labels.max()+1,dtype=np.int16);point_b=np.zeros(labels.max()+1,dtype=np.int16) for i in range(labels.max()+1): point_l[i] = labels.shape[1];point_t[i] = labels.shape[0] for i in range(labels.shape[0]):#宽 for j in range(labels.shape[1]):#长 if labels[i][j] != 0: if point_l[labels[i][j]] > j : point_l[labels[i][j]] = j if point_r[labels[i][j]] < j : point_r[labels[i][j]] = j if point_t[labels[i][j]] > i : point_t[labels[i][j]] = i if point_b[labels[i][j]] < i : point_b[labels[i][j]] = i point_l=point_l.tolist();point_l.pop(0);point_r=point_r.tolist();point_r.pop(0) point_t=point_t.tolist();point_t.pop(0);point_b=point_b.tolist();point_b.pop(0) if(multiple==0): point_l=[min(point_l)];point_r=[max(point_r)];point_t=[min(point_t)];point_b=[max(point_b)]; return point_l,point_r,point_t,point_b,labels
def ImageEffect_ConvexHull(I, obj=False): if obj: I_rgb = cv2.cvtColor(I, cv2.COLOR_RGBA2GRAY) I_filtered = morphology.convex_hull_object(I_rgb) else: I_filtered = morphology.convex_hull_image(I[:, :, :3]) return FilterPostProcess(I, I_filtered)
def process(self): '''Main function that lead's threw the image altering process''' seed = (min(len(self.altered_image), len(self.altered_image[0]))** 2) / 10000 if seed > 70: print("size too big, returning! {}".format(seed)) return self.mark_colors() # puts white wherever it thinks there is a color self.open( 1) # normal opening on those colors to blurr out any letters etc. self.find_contours() # find all contours self.contour = self.get_biggest_contour( ) # if there was a colorfull background # you choose the biggest white contour self.altered_image = morphology.convex_hull_object( self.altered_image, 8) self.image, self.altered_image = self.trim_to_mask( source=self.image, mask=self.convex(self.altered_image)) self.altered_image = self.erase_colors(0.0) ''' go threw some of the possibilities to find all numbers! (10,40) (5,90) etc''' p5, p95 = np.percentile(self.altered_image, (PERCENTILE_0, PERCENTILE_1)) self.altered_image = exposure.rescale_intensity(self.altered_image, in_range=(p5, p95)) '''OTSU ITADAKIMASU!''' threshold = filters.threshold_otsu(self.altered_image) self.altered_image = self.altered_image > threshold self.altered_image = morphology.opening(self.altered_image, morphology.disk(2)) ## label everything and check for numbers self.read_numbers(source=self.altered_image) pass
def binarize(imag, debug=False): """ This function returns a binarized version of the image. """ imag = imag.copy() # We compute an optimal threshold and form a binary image ################## # YOUR CODE HERE # ################## thresh = threshold_otsu(imag) black_white = closing(imag > thresh, square(3)) cleared = clear_border(black_white) binar = convex_hull_object(cleared) if debug: fig, ax = plt.subplots() ax.imshow(imag) ax.imshow(binar, alpha=0.4) fig.suptitle("Binary image") plt.show() return binar
def test_object(): image = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) expected_conn_1 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, connectivity=1), expected_conn_1) expected_conn_2 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, connectivity=2), expected_conn_2) with testing.raises(ValueError): convex_hull_object(image, connectivity=3) with expected_warnings(['`neighbors` is deprecated']): out = convex_hull_object(image, neighbors=4) assert_array_equal(out, expected_conn_1)
def test_object(): image = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) expected4 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 4), expected4) expected8 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 8), expected8) assert_raises(ValueError, convex_hull_object, image, 7) # Test that an error is raised on passing a 3D image: image3d = np.empty((5, 5, 5)) assert_raises(ValueError, convex_hull_object, image3d)
def test_object(): image = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) expected4 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 4), expected4) expected8 = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) assert_array_equal(convex_hull_object(image, 8), expected8) with testing.raises(ValueError): convex_hull_object(image, 7)
def polish_mask(self, binary_mask): "Elije la mejor region y completa huecos" filled = morphology.convex_hull_object(binary_mask) labels = measure.label(filled) rprops = measure.regionprops(labels) if len(rprops) == 0: return binary_mask, np.inf, -1 disparity = self.calculate_disparity(rprops, np.prod(binary_mask.shape)) I = np.argmin(disparity) polished_mask = (labels == (I + 1)) polished_mask = morphology.convex_hull_image(polished_mask) return polished_mask, disparity[I], rprops[I].orientation
def _fill_objects(vol, axis=0): filled_vol = np.copy(vol) del vol if axis != 0: filled_vol = np.moveaxis(filled_vol, axis, 0) for idx, slc in enumerate(filled_vol): slc = convex_hull_object(slc, neighbors=4) filled_vol[idx, ...] = slc if axis != 0: filled_vol = np.moveaxis(filled_vol, 0, axis) return filled_vol
def fill(lung): struct = disk(5) test = lung.copy() for i in range(lung.shape[2]): test[..., i] = binary_fill_holes(lung[..., i]) label_test, num = label(test[..., i], return_num=True) if num != 2: continue chull = convex_hull_object(test[..., i]) coords = [] for contour in find_contours(chull, 0): coords.append(approximate_polygon(contour, tolerance=0)) if len(coords) < 2: continue inverted = np.invert(test[..., i]) distance = ndi.distance_transform_edt(inverted) peaks = peak_local_max(distance, labels=inverted) left_peaks = points_in_poly(peaks, coords[0]) right_peaks = points_in_poly(peaks, coords[1]) peaks_mask = left_peaks | right_peaks peaks = peaks[peaks_mask] peak_image = np.zeros(lung[..., i].shape) peak_image[peaks[:, 0], peaks[:, 1]] = 1 if len(peaks == 1): peak_image[0, 0] = 1 markers = ndi.label(peak_image)[0] labels = watershed(-distance, markers, mask=inverted) labels[labels == 1] = 0 for region in regionprops(labels): centroid = np.asarray([int(x) for x in region.centroid]).reshape(1, 2) if ((np.sum(points_in_poly(region.coords, coords[0])) < region.area and np.sum(points_in_poly(region.coords, coords[1])) < region.area) or (not points_in_poly(centroid, coords[1]) and not points_in_poly(centroid, coords[1]))): centroid = tuple(int(x) for x in region.centroid) labels = flood_fill(labels, centroid, 0) labels[labels > 0] = 255 test[..., i][labels > 0] = 255 return test
def get_glass_mask(thumbnail_gray: np.ndarray): """ 获取玻璃盖板的mask, 用于判断相似组织是否被标记 注:比赛中相似组织可能只标记一份 :param thumbnail_gray: :return: """ # print(thumbnail_gray.shape) # assert thumbnail_gray.shape[-1] == 1 mask = thumbnail_gray != 1 # background is 1, samples was splited by background glass mask = morphology.binary_dilation(mask) mask = morphology.binary_erosion(mask) convex = morphology.convex_hull_object(mask) # convex = morphology.remove_small_holes(convex) convex = morphology.remove_small_objects(convex) return convex
def threshold(self): """ Thresholds by first finding the Otsu threshold. Holes are removed from Otsu thresholded image and convex hulls are created for foreground objects. Foreground objects are expanded to fill the convex hulls. """ thresh_val = self.thresh_otsu(self.im_smooth) # convex hull threshold result thresh_mask = self.im_smooth > thresh_val thresh_mask = ndi.binary_fill_holes(thresh_mask) thresh_mask = morphology.convex_hull_object(thresh_mask) self.im_thresh = self.im_smooth self.im_thresh[~thresh_mask] = 0 return thresh_val
def binarize(image, debug=False): """ This function returns a binarized version of the image. """ # We make sure that we work on a local copy of the image img = image.copy() thresh = threshold_otsu(img) img = img > thresh img = closing(img, square(3)) # remove artifacts connected to image border img = clear_border(img) # take only the frame of the cubes, not the inside img = convex_hull_object(img) if debug: show_image(img, "Binary image") return img
def threshold(self): """ Thresholds by first finding the Otsu threshold. Holes are removed from Otsu thresholded image and convex hulls are created for foreground objects. Foreground objects are expanded to fill the convex hulls. """ otsu_thresh = self.thresh_otsu(self.im_smooth) thresh_val = self.bounded_thresh(otsu_thresh) # convex hull threshold result thresh_mask = self.im_smooth > thresh_val thresh_mask = ndi.binary_fill_holes(thresh_mask) thresh_mask = morphology.convex_hull_object(thresh_mask) self.im_thresh = morphology.closing(self.im_smooth, selem=morphology.disk( self.C['CLOSING_FILTER_SZ'])) self.im_thresh[~thresh_mask] = 0 return otsu_thresh, thresh_val
def esqueletoFechoConvexoVermelho(img): axs[1].set_title('Esqueleto do fecho convexo da imagem de cor vermelha') axs[1].set_axis_off() #tira o eixo x e y das imagem que fica na coluna 1 fechamento = morphology.area_closing(img, 64, 1) #retira todos os pontos linha, coluna = fechamento.shape for i in range(linha): for j in range(coluna): if ( fechamento[i][j] != 72 ): #seta os pixels da fig de cor não vermelha(na escala de cinza) para branco fechamento[i][j] = 255 thresh = threshold_otsu( fechamento ) #auxilia na transformação da img na escola de cinza para binária(0-ausencia de cor 1-presença de cor) binary = invert( fechamento > thresh ) #tranforma a imagem em binaria em seguida faz a troca das cor dos pixels fechoConvexo = morphology.convex_hull_object( binary) #retorna o fecho convexo de cada objeto esqueleto = morphology.skeletonize(fechoConvexo) axs[1].imshow(esqueleto, cmap='gray')
def split_space_content(): for root, dirs, files in os.walk('data'): for fname in files: bg_name = "data/" + fname img = io.imread(bg_name, as_grey=True) # 检测canny边缘,得到二值图片 edgs = feature.canny(img, sigma=3) chull = morphology.convex_hull_object(edgs) # # fig, axes = plt.subplots(1, 2, figsize=(8, 8)) # ax0, ax1 = axes.ravel() # ax0.imshow(edgs, plt.cm.gray) # ax0.set_title('many objects') # ax1.imshow(chull, plt.cm.gray) # ax1.set_title('convex_hull image') # # plt.show() plt.imsave("data2/" + fname, chull)
def make_mask(image, t=1, s=1, hardImageThreshold=None, hardSizeThreshold=None, local=False, convexhull=False): ''' Identifies suitable morphological components from image by thresholding. ''' if local: mask = image > t * threshold_local(image, 151) else: if hardImageThreshold: thresh = hardImageThreshold else: thresh = t * threshold_otsu(image) mask = image > thresh #Fill holes. Warning: takes a long time if convexhull: mask = convex_hull_object(mask) #Filter small components. The default threshold is 0.00005 of the image area if hardSizeThreshold: size_thresh = hardSizeThreshold else: size_thresh = s * np.prod(image.shape) * 0.00005 mask = remove_small_objects(mask, min_size=size_thresh) #Clear border mask = clear_border(mask) #Label connected components mask = label(mask) return mask
def binarize(imag, debug=False): """ This function returns a binarized version of the image. """ imag = imag.copy() # We compute an optimal threshold and form a binary image th_value = threshold_otsu(imag) binar = imag > th_value binar = closing(binar, square(20)) clear_border(binar) binar = convex_hull_object(binar) if debug: fig, ax = plt.subplots() #ax.imshow(imag, cmap='gray') ax.imshow(binar, alpha=0.4, cmap='gray') fig.suptitle("Binary image") plt.show() return binar
def fechoConvexo(img): axs[1].set_title('Imagem com fecho convexo dos objetos') axs[1].set_axis_off() #tira o eixo x e y das imagem que fica na coluna 1 fechamento = morphology.area_closing( img, 64, 1) #retira os pontos para fazer o fecho apenas das figuras restantes linha, coluna = fechamento.shape for i in range(linha): for j in range(coluna): if ( fechamento[i][j] == 88 ): #seta os pixels da fig de cor magenta(na escala de cinza) para branco fechamento[i][j] = 255 thresh = threshold_otsu( fechamento ) #auxilia na transformação da img na escola de cinza para binária(0-ausencia de cor 1-presença de cor) binary = invert( fechamento > thresh ) #tranforma a imagem em binaria em seguida faz a troca das cor dos pixels fechoConvexo = morphology.convex_hull_object( binary) #retorna o fecho convexo de cada objeto axs[1].imshow(fechoConvexo, cmap='gray')
import matplotlib.pyplot as plt from skimage import data, color, morphology, feature # 生成二值测试图像 img = color.rgb2gray(data.coins()) # 检测canny边缘,得到二值图片 edgs = feature.canny(img, sigma=3, low_threshold=10, high_threshold=50) chull = morphology.convex_hull_object(edgs) # 绘制轮廓 fig, axes = plt.subplots(1, 2, figsize=(8, 8)) ax0, ax1 = axes.ravel() ax0.imshow(edgs, plt.cm.gray) ax0.set_title('many objects') ax1.imshow(chull, plt.cm.gray) ax1.set_title('convex_hull image') plt.show()
def transform_rois( roi_file, source_image_filename, destination_image_filename, control_point_file, output_filename, temp_output_filename, log_file_path, error_file_path, roi_reference_image=None, selem_size=15, nii_scale=None, transformation_matrix=None, debug=False, print_value_round_decimals=2, z_filter_padding=2, ): """ Using a source image (e.g. downsampled stack), transform an ImageJ zipped collection of ROIs into the coordinate space of a destination image (e.g. an atlas), using the inverse control point file from an existing niftyreg registration :param roi_file: .zip collection of ImageJ ROIs :param source_image_filename: Image that the ROIs are defined in :param destination_image_filename: Image in the destination coordinate space :param control_point_file: Transformation from source to destination :param output_filename: output filename for the resulting nifti file :param temp_output_filename: Temporary file for registration :param log_file_path: Path to save niftyreg logs :param error_file_path: Path to save niftyreg errors :param roi_reference_image: Image on which the ROIs are defined (if not the downsampled image in the registration directory) :param selem_size: Structure element size for closing :param nii_scale: Scaling to correctly save the temporary nifti image :param transformation_matrix: Affine transform for the temporary nifti image :param print_value_round_decimals: How many decimal places to round values printed to console. :param z_filter_padding: Size of the filter in z when correcting for unlabled slices. :param debug: If True, don't delete temporary files """ print("Loading ROIs") rois = read_roi_zip(roi_file) number_rois = len(rois) print(f"{number_rois} rois found") x = [] y = [] z = [] for key in rois: for position in range(0, len(rois[key]["x"])): x.append(rois[key]["x"][position]) y.append(rois[key]["y"][position]) z.append(rois[key]["position"]) print("Loading downsampled image image") downsampled_source_image = brainio.load_any(str(source_image_filename)) print(f"Source image size: " f"x:{downsampled_source_image.shape[0]}, " f"y:{downsampled_source_image.shape[1]}, " f"y:{downsampled_source_image.shape[2]}") downsampled_source_image[:] = 0 if roi_reference_image is not None: print("Reference image flag used. Loading reference image") reference_image_shape = brainio.get_size_image_from_file_paths( roi_reference_image) print(f"Reference image shape is " f"x:{reference_image_shape['x']}, " f"y:{reference_image_shape['y']}, " f"z:{reference_image_shape['z']}") x_downsample_factor = (reference_image_shape["x"] / downsampled_source_image.shape[0]) y_downsample_factor = (reference_image_shape["y"] / downsampled_source_image.shape[1]) z_downsample_factor = (reference_image_shape["z"] / downsampled_source_image.shape[2]) print(f"ROIs will be downsampled by a factor of " f"x:{round(x_downsample_factor, print_value_round_decimals)}, " f"y:{round(y_downsample_factor, print_value_round_decimals)}, " f"z:{round(z_downsample_factor, print_value_round_decimals)}") # TODO: optimise this print("Creating temporary ROI image") for position in range(0, len(x)): if roi_reference_image is None: downsampled_source_image[x[position], y[position], z[position]] = 1 else: x_scale = int(round(x[position] / x_downsample_factor)) y_scale = int(round(y[position] / y_downsample_factor)) z_scale = int(round(z[position] / z_downsample_factor)) downsampled_source_image[x_scale, y_scale, z_scale] = 1 print("Cleaning up ROI image") # TODO speed this up - parallelise? selem = morphology.selem.square(selem_size) for plane in tqdm(range(0, downsampled_source_image.shape[2])): tmp = morphology.binary.binary_closing(downsampled_source_image[:, :, plane], selem=selem) tmp = morphology.convex_hull_object(tmp) downsampled_source_image[:, :, plane] = morphology.binary.binary_closing( tmp, selem=selem) if roi_reference_image is not None: if z_downsample_factor < 1: print("ROI was defined at a lower z-resolution than the atlas. " "Correcting with a maximum filter") z_filter_size = int(round(1 / z_scale)) + z_filter_padding downsampled_source_image = maximum_filter1d( downsampled_source_image, z_filter_size, axis=2) print(f"Saving temporary ROI image at: {temp_output_filename}") brainio.to_nii( downsampled_source_image, str(temp_output_filename), scale=nii_scale, affine_transform=transformation_matrix, ) print("Preparing ROI registration") nifty_reg_binaries_folder = get_niftyreg_binaries() program_path = get_binary(nifty_reg_binaries_folder, PROGRAM_NAME) reg_cmd = prepare_segmentation_cmd( program_path, temp_output_filename, output_filename, destination_image_filename, control_point_file, ) print("Running ROI registration") try: safe_execute_command(reg_cmd, log_file_path, error_file_path) except SafeExecuteCommandError as err: raise RegistrationError("ROI registration failed; {}".format(err)) print(f"Registered ROI image can be found at {output_filename}") if not debug: print("Deleting temporary files") remove(temp_output_filename) remove(log_file_path) remove(error_file_path)
def run(self, ips, snap, img, para=None): img[convex_hull_object(snap)] = 255
def immune_cell_identi(path, filename, plot=False, convex=False, Low_thre=100, High_thre=170): img = cv.imread(path + '\\' + filename) # RGB to Gray GRAY = cv.cvtColor(img, cv.COLOR_BGR2GRAY) mask = cv.inRange(GRAY, Low_thre, High_thre) # through convex hull if convex: mask = morphology.convex_hull_object(mask, neighbors=4) _, label_c = cv.connectedComponents(mask, connectivity=4) label_c = np.array(label_c, dtype='bool') area1 = 17 chull3 = morphology.remove_small_objects(label_c, area1, connectivity=1, in_place=False) mask2 = np.array(chull3, dtype='uint8') mask3 = np.where(mask2 == 0, mask2, 255) area2 = 4 chull5 = morphology.remove_small_objects(label_c, area2, connectivity=1, in_place=False) mask4 = np.array(chull5, dtype='uint8') mask5 = np.where(mask4 == 0, mask4, 255) # mask6 is the region of interest, where the immune cells are located. mask6 = mask5 - mask3 _, label_connect = cv.connectedComponents(mask6, connectivity=4) # the label_num is the number of connectivity domains label_num = label_connect.max() if plot: cv.imshow('original image', img) cv.imshow('grayscale image', mask) cv.imshow('final image', mask6) cv.waitKey(0) if convex: number = 0 contours, hireachy = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) for i, contour in enumerate(contours): hull = cv.convexHull(contour) ishull = cv.isContourConvex(hull) cv.drawContours(img, list(hull), -1, (0, 0, 255), 2) if ishull: hull = cv.convexHull(contour, returnPoints=False) defects = cv.convexityDefects(contour, hull) if defects is not None: for j in range(defects.shape[0]): s, e, f, d = defects[j, 0] start = tuple(contour[s][0]) end = tuple(contour[e][0]) far = tuple(contour[f][0]) cv.line(img, start, end, (0, 255, 0), 2) cv.circle(img, far, 5, (0, 0, 255), -1) print(j) number = number + len(defects) - 1 label_num = label_num + number return label_num
def convex(in_img): in_img[convex_hull_object(in_img)] = 255 return in_img
def getGapDistances(chunk, edgeThresh=0.1, sizeThresh=10, plotIt=False): chunkBi, _ = binarizeImg(chunk, threshFn=skimfilt.threshold_otsu, greater=False, plotIt=plotIt) # get convex hulls of connected components chunk_hull = convex_hull_object(chunkBi, neighbors=4) nrow, ncol = chunk.shape # Label convex hulls chunk_hull_labels, nrObj = ndimage.label(chunk_hull) # Remove all objects touching the top and bottom that have a # center of mass also close to the top or bottom. centers = center_of_mass(chunk_hull, chunk_hull_labels, range(1, nrObj + 1)) thresh_top = nrow * edgeThresh thresh_bot = nrow - nrow * edgeThresh # top edge for j in range(ncol): if chunk_hull_labels[0, j] != 0: lab = chunk_hull_labels[0, j] if centers[lab - 1][0] < thresh_top: chunk_hull_labels[chunk_hull_labels == lab] = 0 # bottom edge for j in range(ncol): if chunk_hull_labels[nrow - 1, j] != 0: lab = chunk_hull_labels[nrow - 1, j] if centers[lab - 1][0] > thresh_bot: chunk_hull_labels[chunk_hull_labels == lab] = 0 # Remove all objects that are just absolutely tiny labs = np.unique(chunk_hull_labels) for lab in labs: size = np.sum(chunk_hull_labels == lab) if size < sizeThresh: chunk_hull_labels[chunk_hull_labels == lab] = 0 # Relabel convex hulls after previous removal chunk_hull = chunk_hull_labels > 0 chunk_hull_labels, nrObj = ndimage.label(chunk_hull) # Sort labels by means x values osli = ndimage.find_objects(chunk_hull_labels) mean_x = [np.mean(x[1].indices(10**10)[:2]) for x in osli] order = np.argsort(mean_x) for j in range(len(order)): chunk_hull_labels[chunk_hull_labels == order[j] + 1] = -(j + 1) chunk_hull_labels *= -1 # Get centers of mass for convex hulls centers = center_of_mass(chunk_hull, chunk_hull_labels, range(1, nrObj + 1)) # Find contours of objects and use these with lines between # centers of mass to get distance between objects contours = find_contours(chunk_hull, 0.5) contours = [contours[o] for o in order] distances = [] break_centers = [] for j in range(len(contours) - 1): obj1 = LineString(contours[j]) obj2 = LineString(contours[j + 1]) center_dist = LineString([centers[j], centers[j + 1]]) edge1 = obj1.intersection(center_dist) edge2 = obj2.intersection(center_dist) distances.append(edge1.distance(edge2)) try: break_centers.append( LineString([edge1, edge2]).centroid.coords[0][1]) except: break_centers.append(0) distances = np.array(distances, ndmin=2).T if plotIt: plt.imshow(chunk_hull, cmap="gray") plt.show() plt.imshow(chunk_hull_labels, cmap="nipy_spectral") plt.plot([x[1] for x in centers], [y[0] for y in centers], "ro") plt.show() return distances, chunk_hull_labels, break_centers
from skimage.filters import gaussian from skimage.segmentation import active_contour from skimage.segmentation import (morphological_chan_vese, morphological_geodesic_active_contour, inverse_gaussian_gradient, checkerboard_level_set) from skimage import measure from skimage.morphology import convex_hull_image, convex_hull_object from skimage.morphology import square, dilation import cv2 as cv img = io.imread('lesao.png') img_gray = rgb2gray(img) hull = convex_hull_object(img) #hull_dilated = dilation(hull, square(28 )) contours = measure.find_contours(hull, 0.5) #order the contours in decrescent order and get the biggest one biggest_contour = sorted(contours, key=lambda x: len(x), reverse=True)[0] #s = np.linspace(0, 2*np.pi, 400) #r = 100 + 100*np.sin(s) #c = 220 + 100*np.cos(s) #init = np.array([r, c]).T smoothed_img = gaussian(img_gray, 4) snake = active_contour(smoothed_img, biggest_contour, alpha=0.001,
def FindBars(self, bands, close=True, remove_small=True): ''' BarFinder.FindBars(bands) - Uses Otsu's global thresholding with both MNDWI and NDVI indexes in order to find channel bars. A convex hull is applied to the unwrapper bar objects. Args ==== bands: dictionary - must contain R, G, B, NIR, MIR bands Kwargs ====== close: boolean - perform binary closing on bar mask Returns ======= FindBars: Labeled Channel Bars ''' Wbands = {} # Water bands Vbands = {} # Vegetation bands for nband in ['R', 'G', 'B', 'NIR', 'MIR', 'SWIR']: Wbands[nband] = ndimage.interpolation.map_coordinates( bands[nband][::-1, :], [self.unwrapper.Yc, self.unwrapper.Xc]) Idx, Bars, otsu_glob = SegmentationIndex( R=Wbands['R'], G=Wbands['G'], B=Wbands['B'], NIR=Wbands['NIR'], MIR=Wbands['MIR'], SWIR=Wbands['SWIR'], index='BAR', method='global' ) ## This must be made locally, otherwise we dont see bars eventually # Apply a Convex Hull to Channel Bars #Bars = mm.convex_hull_object( Bars ) if close: # 1/8 of the total average channel width is used ( 1/4*mean(b) ) rad = 1 #max( 0, self.unwrapper.b.mean()/self.unwrapper.GeoTransf['PixelSize'] ) Bars = mm.binary_closing(Bars, mm.disk(rad)) if remove_small: Amin = 0.1 * self.unwrapper.N.size / 2 * ( self.unwrapper.b.mean() / (self.unwrapper.s[1] - self.unwrapper.s[0])) mm.remove_small_objects(Bars, 1, in_place=True) # Remove small Bars mm.remove_small_holes(Bars, Amin, in_place=True) # Remove Internal Spots # Apply a Convex Hull to Channel Bars Bars = mm.convex_hull_object(Bars) # Identify the Largest Bar on the Bend labeled_array, num_features = ndimage.measurements.label(Bars) self.Bars = labeled_array self.BarIdx = np.arange(num_features, dtype=int) + 1 return self.Bars
def AnalyzeMergedZones(diretorio, ImgRefRoot='/Binarized', XYField=[319.45, 319.45], RawImageDefinition=[1024, 1024], ZStep=1, ImportstackRootName='/Binarized', importFormat='.png', MergedRegion=1, FirstStack=1, LastStack=2, FirstSlice=1, LastSlice=2, initialTimePoint=30, timeinterval=30, BACVol_ylim=800, BACVel_ylim=800, EPSVol_ylim=800, EPSVel_ylim=800): StackList = list(range(FirstStack, LastStack + 1)) SliceRange = list(range(FirstSlice, LastSlice + 1)) print('\n Encontrando as regioes para calcular \n') LengthPixelRatio = XYField[0] / RawImageDefinition[0] VoxelVal = ZStep * (XYField[0] / RawImageDefinition[0]) * ( XYField[1] / RawImageDefinition[1]) ImgZProj1 = io.imread(diretorio + ImgRefRoot + '/bac' + '/ZProjection_t18' + importFormat, dtype='i4') ImgZProj2 = io.imread(diretorio + ImgRefRoot + '/bac' + '/ZProjection_t15' + importFormat, dtype='i4') ImgZProj3 = io.imread(diretorio + ImgRefRoot + '/bac' + '/ZProjection_t10' + importFormat, dtype='i4') ImgZProj4 = io.imread(diretorio + ImgRefRoot + '/bac' + '/ZProjection_t5' + importFormat, dtype='i4') ImgZProj5 = io.imread(diretorio + ImgRefRoot + '/bac' + '/ZProjection_t2' + importFormat, dtype='i4') ImgZProjF1 = ImgZProj1 + ImgZProj2 + ImgZProj3 + ImgZProj4 + ImgZProj5 ImgZProjF2 = (ImgZProjF1 / ImgZProjF1.max()) * 255 # Plot Imagens #Figura 1 - Grid fig1 = plt.figure(figsize=(12, 7), facecolor='w', edgecolor='k') plt.subplots_adjust(wspace=1.5, hspace=0.6) #Mapa 1 map1 = plt.subplot2grid((2, 3), (0, 0), rowspan=1, colspan=1) map1axi = map1.imshow(ImgZProjF2, alpha=0.8, cmap='jet') map1.set_title('Colony merging', fontsize=11) map1.tick_params(which='both', bottom='off', labelbottom='on', top='off', labeltop='off', left='off', labelleft='on', right='off', labelright='off', labelsize=11) map1.set_xlabel('$\\mu$m', fontsize=11) map1.set_xticks([0, int(ImgZProjF2.shape[1] / 2), ImgZProjF2.shape[1]]) map1.set_xticklabels([ str(0), str(int((ImgZProjF2.shape[1] / 2) * LengthPixelRatio)), str(int(ImgZProjF2.shape[1] * LengthPixelRatio)) ]) map1.set_yticks([0, int(ImgZProjF2.shape[0] / 2), ImgZProjF2.shape[0]]) map1.set_yticklabels([ str(int(ImgZProjF2.shape[0] * LengthPixelRatio)), str(int((ImgZProjF2.shape[0] / 2) * LengthPixelRatio)), str(0) ]) Colbar1 = fig1.colorbar(map1axi, fraction=0.04, pad=0.08, orientation='vertical', ticks=list( np.arange(0, ImgZProjF2.max() + 1, int(ImgZProjF2.max() / 5)))) Colbar1.set_label('time (min)', fontsize=11) Colbar1.set_ticklabels(['B'] + [str(i) for i in [510, 420, 270, 120, 30]]) Colbar1.ax.tick_params(labelsize=11) #Mapa 2 ImgRef1a = io.imread(diretorio + ImgRefRoot + '/bac' + '/ConvexHull1' + importFormat) ImgRef1b = morphology.label(ImgRef1a, connectivity=1) ImgRef1Props = measure.regionprops(ImgRef1b) CentroidList = [] for elementN in list(range(ImgRef1b.max())): CentroidList.append([ ImgRef1Props[elementN].centroid[0], ImgRef1Props[elementN].centroid[1] ]) ImgConvex1a = io.imread(diretorio + ImgRefRoot + '/bac' + '/ConvexHull2' + importFormat) ImgConvex1b = morphology.convex_hull_object(ImgConvex1a) ImgConvex2 = np.where(ImgConvex1b == True, 1, 0) ImgConvex3 = morphology.label(ImgConvex2, connectivity=1) HexColors = [] openHexColors = open(diretorio + '/HexColors.txt', 'r') for line in openHexColors: HexColors.append(str(line)[:-1]) colorlist = [] for labels in list(range(0, ImgConvex3.max() + 1)): colorlist.append(HexColors[labels + 47]) ColorBounds = list(range(0, ImgConvex3.max() + 1)) Colormap2 = colors.ListedColormap(colorlist) ColorNormalization = colors.BoundaryNorm(ColorBounds, Colormap2.N) map2 = plt.subplot2grid((2, 3), (1, 0), rowspan=1, colspan=1) map2final = map2.imshow(ImgConvex3, alpha=0.9, cmap=Colormap2) map2.set_title('Convex hull regions', fontsize=11) map2.tick_params(which='both', bottom='off', labelbottom='on', top='off', labeltop='off', left='off', labelleft='on', right='off', labelright='off', labelsize=11) map2.set_xlabel('$\\mu$m', fontsize=11) map2.set_xticks([0, int(ImgConvex3.shape[1] / 2), ImgConvex3.shape[1] - 1]) map2.set_xticklabels([ str(0), str(int((ImgConvex3.shape[1] / 2) * LengthPixelRatio)), str(int(ImgConvex3.shape[1] * LengthPixelRatio)) ]) map2.set_yticks([0, int(ImgConvex3.shape[0] / 2), ImgConvex3.shape[0] - 1]) map2.set_yticklabels([ str(int(ImgConvex3.shape[0] * LengthPixelRatio)), str(int((ImgConvex3.shape[0] / 2) * LengthPixelRatio)), str(0) ]) Colbar2 = fig1.colorbar(map2final, cmap=Colormap2, norm=ColorNormalization, ticks=list( np.arange(0, ColorBounds[-1], ColorBounds[-1] / len(ColorBounds))), fraction=0.04, pad=0.08, orientation='vertical') Colbar2.set_label('Regions', fontsize=11) Colbar2.set_ticklabels(['B'] + [str(i) for i in ColorBounds[1:]]) Colbar2.ax.tick_params(labelsize=11) #Adicionando os centroides e img referencia map2.imshow(ImgRef1a, alpha=0.5, cmap='Greens') map2.scatter(np.array(CentroidList)[:, 1], np.array(CentroidList)[:, 0], color='k', s=5) # Grafico 1. Growth BAC g1 = plt.subplot2grid((2, 3), (0, 1), rowspan=1, colspan=1) g1.set_title('Bacteria growth', fontsize=11) g1.set_ylabel('Growth ($\\mu$$m^3$)', labelpad=5, fontsize=11) g1.set_xlabel('Time (min)', labelpad=5, fontsize=11) g1.tick_params(axis="y", labelleft='on', left='on', labelright='off', right='off', colors='k', width=1.5, length=3.5, labelsize=11) g1.tick_params(axis="x", labelbottom='on', bottom='on', labeltop='off', top='off', colors='k', width=1.5, length=3.5, labelsize=11) g1.grid(True, color='k', linestyle='-', linewidth=0.4, alpha=0.1) # Grafico 2. Growth EPS g2 = plt.subplot2grid((2, 3), (1, 1), rowspan=1, colspan=1) g2.set_title('EPS growth', fontsize=11) g2.set_ylabel('Growth ($\\mu$$m^3$)', labelpad=5, fontsize=11) g2.set_xlabel('Time (min)', labelpad=5, fontsize=11) g2.tick_params(axis="y", labelleft='on', left='on', labelright='off', right='off', colors='k', width=1.5, length=3.5, labelsize=11) g2.tick_params(axis="x", labelbottom='on', bottom='on', labeltop='off', top='off', colors='k', width=1.5, length=3.5, labelsize=11) g2.grid(True, color='k', linestyle='-', linewidth=0.4, alpha=0.1) # Grafico 3. Growth rate BAC g3 = plt.subplot2grid((2, 3), (0, 2), rowspan=1, colspan=1) g3.set_title('Bacteria growth rate', fontsize=11) g3.set_ylabel('Growth rate ($\\mu$$m^3$/min)', labelpad=5, fontsize=11) g3.set_xlabel('Time (min)', labelpad=5, fontsize=11) g3.tick_params(axis="y", labelleft='on', left='on', labelright='off', right='off', colors='k', width=1.5, length=3.5, labelsize=11) g3.tick_params(axis="x", labelbottom='on', bottom='on', labeltop='off', top='off', colors='k', width=1.5, length=3.5, labelsize=11) g3.grid(True, color='k', linestyle='-', linewidth=0.4, alpha=0.1) # Grafico 4. Growth rate EPS g4 = plt.subplot2grid((2, 3), (1, 2), rowspan=1, colspan=1) g4.set_title('EPS growth rate', fontsize=11) g4.set_ylabel('Growth rate ($\\mu$$m^3$/min)', labelpad=5, fontsize=11) g4.set_xlabel('Time (min)', labelpad=5, fontsize=11) g4.tick_params(axis="y", labelleft='on', left='on', labelright='off', right='off', colors='k', width=1.5, length=3.5, labelsize=11) g4.tick_params(axis="x", labelbottom='on', bottom='on', labeltop='off', top='off', colors='k', width=1.5, length=3.5, labelsize=11) g4.grid(True, color='k', linestyle='-', linewidth=0.4, alpha=0.1) #Figura 2 - Campo escalar #fig2=plt.figure(figsize=(6, 6), facecolor='w', edgecolor='k') #plotPositions=plt.subplot2grid((1,1),(0,0),rowspan=1,colspan=1) g1_YboundMAX = 0 g2_YboundMAX = 0 g3_YboundMAX = 0 g4_YboundMAX = 0 for elementN in list(range(1, ImgConvex3.max() + 1)): YXPosList = [] for Ypos in list(range(ImgConvex3.shape[0])): for Xpos in list(range(ImgConvex3.shape[1])): if ImgConvex3[Ypos, Xpos] == elementN: YXPosList.append([Ypos, Xpos]) ElementPlotListBAC = [] ElementPlotListEPS = [] time = initialTimePoint for stackNumber in StackList: print('\n Encontrando os volume para o stack ', str(stackNumber), ' \n') ImgListBAC = [] ImgListEPS = [] for x in SliceRange: aa = io.imread(diretorio + ImportstackRootName + '/bac' + '/t' + str(stackNumber) + '/Slice' + str(x) + importFormat) bb = io.imread(diretorio + ImportstackRootName + '/EPS' + '/t' + str(stackNumber) + '/Slice' + str(x) + importFormat) ImgListBAC.append(aa) ImgListEPS.append(bb) Img3DarrayBAC = np.array(ImgListBAC) Img3DarrayBACF = np.where(Img3DarrayBAC > 0, 1, 0) Img3DarrayEPS = np.array(ImgListEPS) Img3DarrayEPSF = np.where(Img3DarrayEPS > 0, 1, 0) VolElemCountListBAC = [] VolElemCountListEPS = [] for sliceN in list(range(Img3DarrayBACF.shape[0])): for Position in YXPosList: VolElemCountListBAC.append(Img3DarrayBACF[sliceN, Position[0], Position[1]]) VolElemCountListEPS.append(Img3DarrayEPSF[sliceN, Position[0], Position[1]]) ElementPlotListBAC.append( [elementN, time, sum(VolElemCountListBAC) * VoxelVal]) ElementPlotListEPS.append( [elementN, time, sum(VolElemCountListEPS) * VoxelVal]) time += timeinterval with open(diretorio + '/Images/MergedRegion.txt', 'a') as textfile: for val in ElementPlotListBAC: textfile.write(str(val) + '\n') textfile.close() # Calculando as velocidades VelListBAC = AvgVelocity( np.array(ElementPlotListBAC)[:, 2], initialTimePoint, timeinterval, elementN) VelListEPS = AvgVelocity( np.array(ElementPlotListEPS)[:, 2], initialTimePoint, timeinterval, elementN) #Acertando os limites do gráfico if g1_YboundMAX < np.array(ElementPlotListBAC)[:, 2].max(): g1_YboundMAX = np.array(ElementPlotListBAC)[:, 2].max() if g2_YboundMAX < np.array(ElementPlotListEPS)[:, 2].max(): g2_YboundMAX = np.array(ElementPlotListEPS)[:, 2].max() if g3_YboundMAX < np.array(VelListBAC)[:, 2].max(): g3_YboundMAX = np.array(VelListBAC)[:, 2].max() if g4_YboundMAX < np.array(VelListEPS)[:, 2].max(): g4_YboundMAX = np.array(VelListEPS)[:, 2].max() #Plot graficos Growth g1.plot(np.array(ElementPlotListBAC)[:, 1], np.array(ElementPlotListBAC)[:, 2], color=colorlist[elementN], alpha=0.5) g1.scatter(np.array(ElementPlotListBAC)[:, 1], np.array(ElementPlotListBAC)[:, 2], color=colorlist[elementN], label='Element' + str(elementN), alpha=0.5, s=20) g1.axvline(x=(10 * 30) - 30, color="r", linewidth=1.5, alpha=0.1) g1.axvline(x=(11 * 30) - 30, color="b", linewidth=1.5, alpha=0.1) g1.axvline(x=(15 * 30) - 30, color="y", linewidth=1.5, alpha=0.1) g2.plot(np.array(ElementPlotListEPS)[:, 1], np.array(ElementPlotListEPS)[:, 2], color=colorlist[elementN], alpha=0.5) g2.scatter(np.array(ElementPlotListEPS)[:, 1], np.array(ElementPlotListEPS)[:, 2], color=colorlist[elementN], label='Element' + str(elementN), alpha=0.5, s=20) g2.axvline(x=(10 * 30) - 30, color="r", linewidth=1.5, alpha=0.1) g2.axvline(x=(11 * 30) - 30, color="b", linewidth=1.5, alpha=0.1) g2.axvline(x=(15 * 30) - 30, color="y", linewidth=1.5, alpha=0.1) #Plot graficos Growth rate g3.plot(np.array(VelListBAC)[:, 1], np.array(VelListBAC)[:, 2], color=colorlist[elementN], alpha=0.5) g3.scatter(np.array(VelListBAC)[:, 1], np.array(VelListBAC)[:, 2], color=colorlist[elementN], label='Element' + str(elementN), alpha=0.5, s=20) g3.axvline(x=(10 * 30) - 30, color="r", linewidth=1.5, alpha=0.1) g3.axvline(x=(11 * 30) - 30, color="b", linewidth=1.5, alpha=0.1) g3.axvline(x=(15 * 30) - 30, color="y", linewidth=1.5, alpha=0.1) g4.plot(np.array(VelListEPS)[:, 1], np.array(VelListEPS)[:, 2], color=colorlist[elementN], alpha=0.5) g4.scatter(np.array(VelListEPS)[:, 1], np.array(VelListEPS)[:, 2], color=colorlist[elementN], label='Element' + str(elementN), alpha=0.5, s=20) g4.axvline(x=(10 * 30) - 30, color="r", linewidth=1.5, alpha=0.1) g4.axvline(x=(11 * 30) - 30, color="b", linewidth=1.5, alpha=0.1) g4.axvline(x=(15 * 30) - 30, color="y", linewidth=1.5, alpha=0.1) #Plotar as posicoes usadas no campo escalar #plotPositions.scatter(np.array(YXPosList)[:,1], np.array(YXPosList)[:,0], color=colorlist[elementN]) # Definindo os eixos do gráfico g1.set_ylim(-40, BACVol_ylim) g1.spines["left"].set_visible(True) g1.spines["left"].set_linewidth(1.0) g1.spines["right"].set_visible(False) g1.spines["top"].set_visible(False) g1.spines["bottom"].set_visible(True) g1.spines["bottom"].set_linewidth(1.0) g1.set_aspect('auto') g2.set_ylim(-40, EPSVol_ylim) g2.spines["left"].set_visible(True) g2.spines["left"].set_linewidth(1.0) g2.spines["right"].set_visible(False) g2.spines["top"].set_visible(False) g2.spines["bottom"].set_visible(True) g2.spines["bottom"].set_linewidth(1.0) g2.set_aspect('auto') g3.set_ylim(-5, BACVel_ylim) g3.spines["left"].set_visible(True) g3.spines["left"].set_linewidth(1.0) g3.spines["right"].set_visible(False) g3.spines["top"].set_visible(False) g3.spines["bottom"].set_visible(True) g3.spines["bottom"].set_linewidth(1.0) g3.set_aspect('auto') g4.set_ylim(-5, EPSVel_ylim) g4.spines["left"].set_visible(True) g4.spines["left"].set_linewidth(1.0) g4.spines["right"].set_visible(False) g4.spines["top"].set_visible(False) g4.spines["bottom"].set_visible(True) g4.spines["bottom"].set_linewidth(1.0) g4.set_aspect('auto') plt.tight_layout() fig1.savefig(diretorio + '/Images/MergedRegion' + str(MergedRegion) + '.png', dpi=300) #fig2.savefig(diretorio + '/Images/MergedRegion' + str(MergedRegion) + '_PLOT.png') plt.show()