def trackEnds(imageID, maskID): index = RoiManager.getInstance2().getSelectedIndex() inputIMP = WindowManager.getImage(imageID) maskIMP = WindowManager.getImage(maskID) points1 = inputIMP.getOverlay().get(0).getContainedPoints()[index] points2 = inputIMP.getOverlay().get(1).getContainedPoints()[index] roi = maskIMP.getOverlay().get(index) outerBounds = roi.getBounds() impMT, innerBounds = duplicateMaskInRoi(maskIMP, roi, True) centroid = impMT.getOverlay().get(0).getContourCentroid() nr, endPoint1, endPoint2 = findEndPointsInSkeleton(impMT) track1 = trackEnd(impMT, endPoint1, centroid); track2 = trackEnd(impMT, endPoint2, centroid); impMT.changes=False impMT.close() newTrack1 = [] for point in track1: newTrack1.append((point.x + outerBounds.x + innerBounds.x - 1, point.y + outerBounds.y + innerBounds.y - 1)) newTrack2 = [] for point in track2: newTrack2.append((point.x + outerBounds.x + innerBounds.x - 1, point.y + outerBounds.y + innerBounds.y - 1)) track1X = [point[0] for point in newTrack1] track1Y = [point[1] for point in newTrack1] roiTrack1 = PolygonRoi(track1X, track1Y, Roi.POLYLINE) inputIMP.getOverlay().add(roiTrack1) track2X = [point[0] for point in newTrack2] track2Y = [point[1] for point in newTrack2] roiTrack2 = PolygonRoi(track2X, track2Y, Roi.POLYLINE) inputIMP.getOverlay().add(roiTrack2) inputIMP.repaintWindow()
def prune_branch(self, i): # i >= 1 if i == 0: return temp_min, stemx, stemy, stem_index, branchx, branchy, branch_index = self.get_coord_min_distance( i) poly = self.roi_array[i].getFloatPolygon() poly_npoints = poly.npoints poly_index = branch_index if poly_npoints / 2 >= poly_index: # print 'if', i+1 newx = poly.xpoints[poly_index:] newy = poly.ypoints[poly_index:] new_poly = FloatPolygon(newx, newy) else: # print 'else', i+1 newx = reversed(poly.xpoints[:poly_index + 1]) newy = reversed(poly.ypoints[:poly_index + 1]) new_poly = FloatPolygon(newx, newy) new_roi = PolygonRoi(new_poly, Roi.POLYLINE) new_roi.fitSpline() self.RoiManager.setRoi(new_roi, i)
def do_unwrap(tile_imp, unwrap_axis, imp_title=None): """given an unwrap axis extending from top to bottom of an image, generate an unwrapped image""" ip = tile_imp.getProcessor() ip.setValue(0) unwrap_poly_xs = [x for x, y in unwrap_axis] unwrap_poly_ys = [y for x, y in unwrap_axis] if sum(unwrap_poly_xs) / len(unwrap_poly_xs) > 1.5 * 360: rhs_poly_xs = unwrap_poly_xs else: rhs_poly_xs = [x + 360 for x in unwrap_poly_xs] for _ in range(2): rhs_poly_xs.append(0) unwrap_poly_ys.append(unwrap_poly_ys[-1]) unwrap_poly_ys.append(unwrap_poly_ys[0]) crop_roi = PolygonRoi(rhs_poly_xs, unwrap_poly_ys, Roi.POLYGON) ip.fillOutside(crop_roi) ip.setRoi(crop_roi) ip = ip.crop() ip.setValue(0) lhs_poly_xs = [x - 360 for x in rhs_poly_xs[:-2]] for _ in range(2): lhs_poly_xs.append(ip.getWidth()) crop_roi = PolygonRoi(lhs_poly_xs, unwrap_poly_ys, Roi.POLYGON) ip.fillOutside(crop_roi) ip.setRoi(crop_roi) ip = ip.crop() tile_imp.setProcessor(ip) tile_imp.updateAndRepaintWindow() if imp_title is not None: tile_imp.setTitle("{}, twisted and unwrapped".format(imp_title)) else: tile_imp.setTitle("twisted and unwrapped") return tile_imp
def get_membrane_edge(roi, fixed_anchors, fixed_midpoint): """figure out which edge of the roi is the membrane, since IJ might start the roi from anywhere along the perimeter w.r.t. the user defined anchors""" poly = roi.getInterpolatedPolygon(0.25, False) term_index_1 = [(x, y) for x, y in zip(poly.xpoints, poly.ypoints) ].index(fixed_anchors[0]) term_index_2 = [(x, y) for x, y in zip(poly.xpoints, poly.ypoints) ].index(fixed_anchors[1]) start_idx = min(term_index_1, term_index_2) end_idx = max(term_index_1, term_index_2) xs = [x for x in poly.xpoints] ys = [y for y in poly.ypoints] e1 = FloatPolygon(xs[start_idx:end_idx + 1], ys[start_idx:end_idx + 1]) e2 = FloatPolygon(list(reversed(xs[end_idx:] + xs[:start_idx + 1])), list(reversed(ys[end_idx:] + ys[:start_idx + 1]))) anchors_midpoint = (int( round(0.5 * (fixed_anchors[1][0] + fixed_anchors[0][0]))), int( round( 0.5 * (fixed_anchors[1][1] + fixed_anchors[0][1])))) e1_mean = (sum(e1.xpoints) / e1.npoints, sum(e1.ypoints) / e1.npoints) e2_mean = (sum(e2.xpoints) / e2.npoints, sum(e2.ypoints) / e2.npoints) theta_e1 = angle_between_vecs(fixed_anchors[0], fixed_anchors[1], fixed_anchors[0], e1_mean) #print("Angle between anchor line and anchor0 to e1mean pos = " + str(theta_e1)); theta_e2 = angle_between_vecs(fixed_anchors[0], fixed_anchors[1], fixed_anchors[0], e2_mean) #print("Angle between anchor line and anchor0 to e2mean pos = " + str(theta_e2)); sign = lambda x: (1, -1)[x < 0] if sign(theta_e1) is not sign(theta_e2): #print("using angle to decide on edge ID - vectors linking anchor1 and mean edge positions lie on either side of anchor line"); theta_midpoint = angle_between_vecs(fixed_anchors[0], fixed_anchors[1], fixed_anchors[0], fixed_midpoint) #print("Angle between anchor line and anchor0 to manual midpoint pos = " + str(theta_midpoint)); (use_edge, other_edge) = (e2, e1) if (sign(theta_midpoint) == sign(theta_e2)) else (e1, e2) else: #print("using distance to decide on edge ID - vectors linking anchor1 and mean edge position lie on same side of anchor line"); #print("position anchor midpoint = " + str(anchors_midpoint)); #print("position e1 mean = " + str(e1_mean)); #print("length anchor midpoint to e1 mean = " + str(vector_length(anchors_midpoint, e1_mean))); #print("position e2 mean = " + str(e2_mean)); #print("length anchor midpoint to e2 mean = " + str(vector_length(anchors_midpoint, e2_mean))); #if (vector_length(anchors_midpoint, e1_mean) > vector_length(anchors_midpoint, e2_mean)): # print("Using e1"); #else: # print("Using e2"); (use_edge, other_edge) = (e1, e2) if ( vector_length(anchors_midpoint, e1_mean) > vector_length( anchors_midpoint, e2_mean)) else (e2, e1) use_roi = PolygonRoi(use_edge, Roi.POLYLINE) other_roi = PolygonRoi(other_edge, Roi.POLYLINE) return use_roi, other_roi
def get_distance_from_stem(self, i): if i == 0: return 0 min_len, stemx, stemy, stem_index, _1, _2, _3 = self.get_coord_min_distance( i) stem_x_array = self.roi_array[0].getFloatPolygon().xpoints[:stem_index] stem_y_array = self.roi_array[0].getFloatPolygon().ypoints[:stem_index] new_poly = FloatPolygon(stem_x_array, stem_y_array) new_roi = PolygonRoi(new_poly, Roi.POLYLINE) new_roi.fitSpline() return get_roi_length(new_roi)
def parse_roistr_to_roi(self): """interpret string saved in parameters JSON as IJ ROI""" from ij.gui import PolygonRoi, Roi rect_format_str = "java.awt.Rectangle\[x=(?P<x>\d+)\,y=(?P<y>\d+)\,width=(?P<w>\d+)\,height=(?P<h>\d+)\]" m1 = re.match(rect_format_str, self.spatial_crop) if bool(m1): return Roi(int(m1.groupdict()['x']), int(m1.groupdict()['y']), int(m1.groupdict()['w']), int(m1.groupdict()['h'])) else: # if original ROI wasn't a rectangle... if isinstance(self.spatial_crop, str): str_list = self.spatial_crop[2:-2].split('), (') poly_format_str = '(?P<x>\d+)\, (?P<y>\d+)' xs = [] ys = [] for s in str_list: m2 = re.match(poly_format_str, s) if bool(m2): xs.append(float(m2.groupdict()['x'])) ys.append(float(m2.groupdict()['y'])) else: xs = [x for (x, y) in self.spatial_crop] ys = [y for (x, y) in self.spatial_crop] if len(xs) > 0: return PolygonRoi(xs, ys, Roi.POLYGON) else: return None
def scaleTypeROI(roi): if isinstance(roi,PointRoi): p=roi.getFloatPolygon() x,y=list(p.xpoints),list(p.ypoints) xNew,yNew=map(lambda c:c*scale[0],x),map(lambda c:c*scale[1],y) roiNew=PointRoi(xNew,yNew) elif isinstance(roi,ShapeRoi): roiSels=roi.getRois() roiNews=map(scaleTypeROI,roiSels) roiNew=0 for roi in roiNews: if roiNew==0: roiNew=ShapeRoi(roi) else: roiNew=roiNew.or(ShapeRoi(roi)) else: tp=roi.getType() if tp!=0: p=roi.getPolygon() x,y=list(p.xpoints),list(p.ypoints) posNew=map(lambda pos:(pos[0]*scale[0],pos[1]*scale[1]),zip(x,y)) xNew,yNew=zip(*posNew) roiNew=PolygonRoi(xNew,yNew,tp) else: x,y,w,h=roi.getXBase(),roi.getYBase(),roi.getFloatWidth(),roi.getFloatHeight() xNew,yNew,wNew,hNew=x*scale[0],y*scale[1],w*scale[0],h*scale[1] roiNew=Roi(xNew,yNew,wNew,hNew) return(roiNew)
def generate_cell_shape_results(rois, intensity_channel_imp, cal, file_name, no_nuclei_centroids=None, no_enclosed_nuclei=None): """from list of rois, generate results describing the cell enclosed in each roi""" pixel_width = 1.0 if cal is None else cal.pixelWidth if no_nuclei_centroids is None: no_nuclei_centroids = [0 for _ in rois] if no_enclosed_nuclei is None: no_enclosed_nuclei = [0 for _ in rois] cell_shapes = [] for idx, roi in enumerate(rois): intensity_channel_imp.setRoi(roi) stats = roi.getStatistics() I_mean = stats.mean I_sd = stats.stdDev area = stats.area * (pixel_width**2) perimeter = roi.getLength() aspect_ratio = stats.major / stats.minor cvh_poly = roi.getConvexHull() if cvh_poly is not None: convex_hull_roi = PolygonRoi([x for x in cvh_poly.xpoints], [y for y in cvh_poly.ypoints], PolygonRoi.POLYGON) else: continue print("roi length = {}".format(roi.getLength())) print("convex hull roi length = {}".format( convex_hull_roi.getLength())) cell_spikiness_index = roi.getLength() / (pixel_width * convex_hull_roi.getLength()) cell_shapes.append( CellShapeResults( file_name=file_name, cell_index=idx + 1, cell_area_um2=area, cell_perimeter_um=perimeter, cell_aspect_ratio=aspect_ratio, cell_spikiness_index=cell_spikiness_index, cell_gfp_I_mean=I_mean, cell_gfp_I_sd=I_sd, nuclear_centroids_in_cell=no_nuclei_centroids[idx], nuclei_enclosed_in_cell=no_enclosed_nuclei[idx], roi=roi)) return cell_shapes
def selectionInterpolateAndFitSpline(roi, interval=1.0, smooth=True): """implement IJ.run(imp, "Interpolate", "interval=1.0 smooth adjust");IJ.run(imp, "Fit Spline", "");""" roi = PolygonRoi(roi.getInterpolatedPolygon(-1.0 * interval, smooth), Roi.FREELINE) if roi.subPixelResolution(): roi = selectionTrimFloatPolygon(roi, roi.getUncalibratedLength()) else: roi = selectionTrimPolygon(roi, roi.getUncalibratedLength()) roi.fitSpline() return roi
def __flexAngle(self) : try : p1 = self.__midLine[0] p3 = self.__midLine[-1] except AttributeError : self.__midline() p1 = self.__midLine[0] p3 = self.__midLine[-1] icenter = self.__midCenters[0][1][0][2] p2 = self.__midLine[icenter] #xpoints = (429,472,466) #ypoints = (114,133,99) xpoints = [int(p1[0]), int(p2[0]), int(p3[0])] ypoints = [int(p1[1]), int(p2[1]), int(p3[1])] #print ypoints #return "" r = PolygonRoi(xpoints, ypoints, 3, Roi.ANGLE) return r.getAngle()
def check_edge_order(anchors, edge): """Check that edge runs from first anchor to second as expected""" poly = edge.getPolygon() start = (poly.xpoints[0], poly.ypoints[0]) if vector_length(start, anchors[0]) > vector_length(start, anchors[1]): xs = [x for x in poly.xpoints] ys = [y for y in poly.ypoints] xs.reverse() ys.reverse() edge = PolygonRoi(xs, ys, Roi.POLYLINE) return edge
def get_convexfull_area(self, i, imp=IJ.getImage()): convexfull = self.roi_array[i].getFloatConvexHull() convexfull_roi = PolygonRoi(convexfull, Roi.POLYGON) imp.setRoi(convexfull_roi) moptions = Measurements.MEAN | Measurements.INTEGRATED_DENSITY | Measurements.AREA ip = imp.getProcessor() cal = Calibration(imp) stat = ImageStatistics.getStatistics(ip, moptions, cal) convexfull_are = stat.area return convexfull_are
def bleb_area(membrane_edge, midpoint_anchor): """calculate the area of the drawn bleb, accounting for membrane crossing line joining anchors""" poly = membrane_edge.getFloatPolygon() xs = [x for x in poly.xpoints] ys = [y for y in poly.ypoints] rotangle = membrane_edge.getAngle(int(round(xs[0])), int(round( ys[0])), int(round(xs[-1])), int(round(ys[-1]))) / 180 * math.pi rotY = [(x * math.sin(rotangle) + y * math.cos(rotangle)) for x, y in zip(xs, ys)] rotYmpa = midpoint_anchor[0] * math.sin( rotangle) + midpoint_anchor[1] * math.cos(rotangle) meanRotY = sum(rotY) / len(rotY) seg1 = rotY[:int(round(len(rotY) / 2))] seg1.reverse() seg2 = rotY[int(round(len(rotY) / 2)):] if rotYmpa > rotY[0]: idx1 = len(seg1) - seg1.index(min(seg1)) idx2 = int(round(len(rotY) / 2)) + seg2.index(min(seg2)) else: idx1 = len(seg1) - seg1.index(max(seg1)) idx2 = int(round(len(rotY) / 2)) + seg2.index(max(seg2)) area_poly_xs = xs[idx1:idx2 + 1] area_poly_ys = ys[idx1:idx2 + 1] len_roi = PolygonRoi(area_poly_xs, area_poly_ys, Roi.POLYLINE) length = len_roi.getLength() area_roi = PolygonRoi(area_poly_xs, area_poly_ys, Roi.POLYGON) area = area_roi.getStatistics().area #print(area); return length, area, area_roi
def generate_r_image(imp, ring_rois, centres, unwrap_axis, threshold_val): """for each point in the projection, calculate the distance to the vessel axis and present as an image""" fp = imp.getProcessor() fp.setThreshold(threshold_val, fp.maxValue(), FloatProcessor.NO_LUT_UPDATE) bp = fp.createMask() bp.dilate() bp.erode() mask_imp = ImagePlus("Mask", bp) tile_mask = make_tiled_imp(mask_imp) #tile_mask.show(); #WaitForUserDialog("pasue - generated mask").show(); mask_imp = do_unwrap(tile_mask, unwrap_axis, imp_title=mask_imp.getTitle()) #mask_imp.show(); roi = PolygonRoi([x for (x, y) in unwrap_axis], [y for (x, y) in unwrap_axis], PolygonRoi.POLYLINE) mask_imp.setRoi(roi) #WaitForUserDialog("pasue - unwrapped").show(); IJ.run(mask_imp, "Fill Holes", "") #WaitForUserDialog("pasue - filled holes").show(); IJ.run(mask_imp, "Divide...", "value=255") #WaitForUserDialog("pasue - scaled to 0-1").show(); #mask_imp.show(); r_list = [] for lidx, (roi, centre) in enumerate(zip(ring_rois, centres)): r_sublist = [ math.sqrt((x - centre[0])**2 + (y - centre[1])**2) for x, y in zip(roi.getPolygon().xpoints, roi.getPolygon().ypoints) ] r_list.append(r_sublist) r_imp = ImagePlus("Radii", FloatProcessor([list(x) for x in zip(*r_list)])) tile_r_imp = make_tiled_imp(r_imp) r_imp = do_unwrap(tile_r_imp, unwrap_axis, imp_title=r_imp.getTitle()) r_imp = ImageCalculator().run("Multiply create", r_imp, mask_imp) IJ.run(r_imp, "Cyan Hot", "") return r_imp, mask_imp
def get_angle(self, i): _, _, _, stem_index, _, _, _ = self.get_coord_min_distance(i) stem_x = self.get_xy(0)[0] stem_y = self.get_xy(0)[1] branch_x = self.get_xy(i)[0] branch_y = self.get_xy(i)[1] between_x = stem_x[stem_index] between_y = stem_y[stem_index] start_stem_x = stem_x[stem_index - 10] start_stem_y = stem_y[stem_index - 10] end_branch_x = branch_x[10] end_branch_y = branch_y[10] xpoints = [start_stem_x, between_x, end_branch_x] ypoints = [start_stem_y, between_y, end_branch_y] new_poly_roi = PolygonRoi(xpoints, ypoints, 3, Roi.ANGLE) return new_poly_roi.getAngle()
def load_qcd_edges(input_file_path): """load edges from JSON""" f = open(input_file_path, 'r') try: edges = json.loads(f.read()) finally: f.close() membrane_edges = [] for edge in edges: xs = [pt[0] for pt in edge] ys = [pt[1] for pt in edge] membrane_edges.append(PolygonRoi(xs, ys, Roi.POLYLINE)) return membrane_edges
def read_vl_file(file_path, cal) : coord_col_dict = br.csv_to_col_dict(file_path, cast_type=float) cal_func_dict = {'X' : cal.getRawX, 'Y' : cal.getRawY} for col_name, cal_func in zip(coord_col_dict.keys(), cal_func_dict.values()) : for i in range(len(coord_col_dict[col_name])) : coord_col_dict[col_name][i] = cal_func(coord_col_dict[col_name][i]) vl_roi = PolygonRoi(coord_col_dict['X'], coord_col_dict['Y'],len(coord_col_dict['X']),Roi.POLYGON) return vl_roi
def RoiSelection(index): imp_roi = IJ.getImage() #IJ.run("Invert", "stack"); IJ.run("Fill Holes", "stack"); IJ.run("Create Selection"); rm.runCommand("add") rm.runCommand("split") #number_selected=rm.getCount() IJ.run("Select None"); rm.runCommand("deselect") #rm.select(0) #print number_selected roi_array=rm.getRoisAsArray() max_roi=None max_points=-1 for roi in roi_array: polygon=roi.getPolygon() if polygon is not None: x=[] y=[] for i in range(1,polygon.npoints): x.append(polygon.xpoints[i]) y.append(polygon.ypoints[i]) area=PolyArea(x,y,polygon.npoints) if max_points < area: max_points=area max_roi=roi #print max_points #sorted_roi_array=sorted(roi_array, key=methodcaller('getLength'), reverse=True) #length_array=[] #index=0 #for roi in roi_array: # index=index+1 # length_array.append((index,roi.getLength())) #sorted_length_array=sorted(length_array, key=itemgetter(0)) rm.runCommand("Select All") rm.runCommand("Delete") #for roi in roi_array: interpolated_polygon=max_roi.getInterpolatedPolygon(20,True) roi_polygon=PolygonRoi(interpolated_polygon,Roi.POLYGON) roi_polygon.setName(str(index)) roi_polygon.setImage(imp) roi_polygon.setPosition(index) regions_array.append(roi_polygon)
def read_vl_file(file_path, cal): """open and xy csv file, uncalibrates the values and creates and returns a polygon roi""" roi_csv_headings = ['X', 'Y'] coord_rows = br.csv_to_rows(file_path, cast_type=float) if coord_rows[0] == roi_csv_headings: coord_col_dict = br.csv_to_col_dict(file_path, cast_type=float) else: coord_cols = br.rotate(coord_rows) coord_col_dict = {'X': coord_cols[0], 'Y': coord_cols[1]} cal_func_dict = {'X': cal.getRawX, 'Y': cal.getRawY} for col_name, cal_func in zip(coord_col_dict.keys(), cal_func_dict.values()): for i in range(len(coord_col_dict[col_name])): coord_col_dict[col_name][i] = cal_func(coord_col_dict[col_name][i]) vl_roi = PolygonRoi(coord_col_dict['X'], coord_col_dict['Y'], len(coord_col_dict['X']), Roi.POLYGON) return vl_roi
def selectionTrimPolygon(roi, length): x = roi.getXCoordinates() y = roi.getYCoordinates() n = roi.getNCoordinates() x = selectionSmooth(x, n) y = selectionSmooth(y, n) curvature = selectionGetCurvature(x, y, n) r = roi.getBounds() threshold = selectionRodbard(length) distance = math.sqrt((x[1] - x[0]) * (x[1] - x[0]) + (y[1] - y[0]) * (y[1] - y[0])) x[0] += r.x y[0] += r.y i2 = 1 x2 = 0 y2 = 0 for i in range(1, n - 1): x1 = x[i] y1 = y[i] x2 = x[i + 1] y2 = y[i + 1] distance += math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) + 1 distance += curvature[i] * 2 if (distance >= threshold): x[i2] = x2 + r.x y[i2] = y2 + r.y i2 += 1 distance = 0.0 typ = Roi.POLYLINE if roi.getType() == Roi.FREELIN else Roi.POLYGON if (typ == Roi.POLYLINE and distance > 0.0): x[i2] = x2 + r.x y[i2] = y2 + r.y i2 += 1 p = PolygonRoi(x, y, i2, typ) return p
def selectionTrimFloatPolygon(roi, length): poly = roi.getFloatPolygon() x = poly.xpoints y = poly.ypoints n = poly.npoints x = selectionSmooth(x, n) y = selectionSmooth(y, n) curvature = selectionGetCurvature(x, y, n) threshold = selectionRodbard(length) #IJ.log("trim: "+length+" "+threshold); distance = math.sqrt((x[1] - x[0]) * (x[1] - x[0]) + (y[1] - y[0]) * (y[1] - y[0])) i2 = 1 x2 = 0 y2 = 0 for i in range(1, n - 1): x1 = x[i] y1 = y[i] x2 = x[i + 1] y2 = y[i + 1] distance += math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) + 1 distance += curvature[i] * 2 if (distance >= threshold): x[i2] = float(x2) y[i2] = float(y2) i2 += 1 distance = 0.0 typ = Roi.POLYLINE if roi.getType() == Roi.FREELINE else Roi.POLYGON if (typ == Roi.POLYLINE and distance > 0.0): x[i2] = float(x2) y[i2] = float(y2) i2 += 1 p = PolygonRoi(x, y, i2, typ) return p
pixels = zeros('f', width * height) for i in xrange(len(pixels)): pixels[i] = random() fp = FloatProcessor(width, height, pixels, None) imp = ImagePlus("Random", fp) # Fill a rectangular region of interest # with a value of 2: roi = Roi(400, 200, 400, 300) fp.setRoi(roi) fp.setValue(2.0) fp.fill() # Fill a polygonal region of interest # with a value of -3 xs = [234, 174, 162, 102, 120, 123, 153, 177, 171, 60, 0, 18, 63, 132, 84, 129, 69, 174, 150, 183, 207, 198, 303, 231, 258, 234, 276, 327, 378, 312, 228, 225, 246, 282, 261, 252] ys = [48, 0, 60, 18, 78, 156, 201, 213, 270, 279, 336, 405, 345, 348, 483, 615, 654, 639, 495, 444, 480, 648, 651, 609, 456, 327, 330, 432, 408, 273, 273, 204, 189, 126, 57, 6] proi = PolygonRoi(xs, ys, len(xs), Roi.POLYGON) fp.setRoi(proi) fp.setValue(-3) fp.fill(proi.getMask()) # Attention! imp.show()
def straighten_vessel(imp, smooth_centres, it=1, save_output=False): """use IJ straigtening tool to deal with convoluted vessels""" print("straighten vessel input image dims = " + str(imp.getWidth()) + "x" + str(imp.getHeight())) rot_imp = utils.rot3d(imp, axis='x') if it == 1: roi = PolygonRoi([x for x, y, z in smooth_centres], [z for x, y, z in smooth_centres], Roi.FREELINE) print("len interp polygon = " + str(roi.getInterpolatedPolygon().npoints)) elif it == 2: new_zs = [z for z in range(rot_imp.getWidth())] new_ys = lin_interp_1d([z for x, y, z in smooth_centres], [y for x, y, z in smooth_centres], new_zs) roi = PolygonRoi(new_zs, new_ys, Roi.FREELINE) split_ch = ChannelSplitter().split(rot_imp) mch_imp = split_ch[0] egfp_imp = split_ch[1] roi_imp = split_ch[2] roi_imp.setRoi(roi) for zidx in range(egfp_imp.getNSlices()): for chidx in range(3): split_ch[chidx].setZ(zidx + 1) split_ch[chidx].setRoi(roi) ip = Straightener().straightenLine(split_ch[chidx], 150) if chidx == 1: if zidx == 0: egfp_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) egfp_straight_stack.addSlice(ip) elif chidx == 0: if zidx == 0: mch_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) mch_straight_stack.addSlice(ip) else: if zidx == 0: roi_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) roi_straight_stack.addSlice(ip) egfp_out_imp = ImagePlus("Straightened EGFP", egfp_straight_stack) mch_out_imp = ImagePlus("Straightened mCh", mch_straight_stack) roi_out_imp = ImagePlus("Straightened ROI", roi_straight_stack) if it == 2: egfp_out_imp = utils.rot3d(egfp_out_imp, axis='y') mch_out_imp = utils.rot3d(mch_out_imp, axis='y') roi_out_imp = utils.rot3d(roi_out_imp, axis='y') egfp_out_imp.show() mch_out_imp.show() roi_out_imp.show() IJ.run( "Merge Channels...", "c1=[" + mch_out_imp.getTitle() + "] c2=[" + egfp_out_imp.getTitle() + "] c7=[" + roi_out_imp.getTitle() + "] create keep") # WaitForUserDialog("pause").show(); # if it==1: egfp_out_imp.close() mch_out_imp.close() roi_out_imp.close() new_composite = IJ.getImage() if save_output: FileSaver(new_composite).saveAsTiffStack( os.path.join(output_path, "after rotation " + str(it) + ".tif")) return new_composite
egfp_imp.setRoi(roi) profile = roi.getPixels() projected_im_row.append(max(profile)) try: ring_roi_xs.append(roi.getContainedPoints()[profile.index( max(profile))].x) except IndexError: ring_roi_xs.append(pt2[0]) try: ring_roi_ys.append(roi.getContainedPoints()[profile.index( max(profile))].y) except IndexError: ring_roi_ys.append(pt2[1]) #print("Max val = " + str(max(profile))); egfp_imp.killRoi() ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE) ring_rois.append(ring_roi) roi_stack.setZ(zidx + 1) roi_stack.setRoi(ring_roi) IJ.run(roi_stack, "Line to Area", "") IJ.run(roi_stack, "Set...", "value=" + str(roi_stack.getProcessor().maxValue()) + " slice") min_idx = projected_im_row.index(min(projected_im_row)) # print("min idx = " + str(min_idx)); unzip_axis.append(min_idx) egfp_imp.setRoi(ring_roi) projected_im_pix.append(projected_im_row) # WaitForUserDialog("pause").show(); #print(centres); for ch in split_chs:
fp = FloatProcessor(width, height, pixels, None) roi = Roi(400, 200, 400, 300) # Roi(int x, int y, int width, int height) fp.setRoi(roi) fp.setValue(2.0) fp.fill() imp2 = ImagePlus("Rectangle", fp) imp2.show() # Polygon ROI를 -3으로 채우기 fp = FloatProcessor(width, height, pixels, None) xs = [ 234, 174, 162, 102, 120, 123, 153, 177, 171, 60, 0, 18, 63, 132, 84, 129, 69, 174, 150, 183, 207, 198, 303, 231, 258, 234, 276, 327, 378, 312, 228, 225, 246, 282, 261, 252 ] ys = [ 48, 0, 60, 18, 78, 156, 201, 213, 270, 279, 336, 405, 345, 348, 483, 615, 654, 639, 495, 444, 480, 648, 651, 609, 456, 327, 330, 432, 408, 273, 273, 204, 189, 126, 57, 6 ] proi = PolygonRoi( xs, ys, len(xs), Roi.POLYGON ) # PolygonRoi(float[] xPoints, float[] yPoints, int nPoints, int type) fpp = fp fpp.setRoi(proi) fpp.setValue(-3) fpp.fill(proi.getMask()) imp3 = ImagePlus("Polygon", fpp) imp3.show()
image = IJ.getImage() # Get current ROI roi = image.getRoi() if roi is not None: # Get ROI points polygon = roi.getPolygon() n_points = polygon.npoints x = polygon.xpoints y = polygon.ypoints # Compute center of mass xc = 0 yc = 0 for i in range(n_points): xc = xc + x[i] yc = yc + y[i] xc = xc / n_points yc = yc / n_points # Compute new rotated points new_x = [] new_y = [] for i in range(n_points): new_x.append( int(xc + (x[i] - xc) * math.cos(angle) - (y[i] - yc) * math.sin(angle))) new_y.append( int(yc + (x[i] - xc) * math.sin(angle) + (y[i] - yc) * math.cos(angle))) # Create new ROI new_roi = PolygonRoi(new_x, new_y, n_points, Roi.POLYGON) image.setRoi(new_roi)
#imp.show() roi_manager = RoiManager() for gene in gene_list: roi_manager.reset() with open(csv_path) as csvfile: reader = csv.DictReader(csvfile) for n, row in enumerate(reader): # print(row['cell_n']) poly_name = row['gene_name'] # poly_name = ast.literal_eval(poly_name) if gene == poly_name: print(gene, poly_name) rr = row['row_pixels'] cc = row['col_pixels'] rs = ast.literal_eval(rr) cs = ast.literal_eval(cc) proi = PolygonRoi(cs, rs, len(rs), Roi.POLYGON) roi_manager.addRoi(proi) roi_manager.runCommand("Deselect") roi_save_path = os.path.join(dir.getDirectory(), gene + "_RoiSet.zip") print(roi_save_path) if not os.path.exists(roi_save_path): with zipfile.ZipFile(roi_save_path, "w") as file: pass file.close() roi_manager.runCommand("Save", roi_save_path)
def main(): #print (sys.version_info) # debug #print(sys.path) # debug data_root = r'C:\Users\dougk\Desktop\test' # debug output_root = r'C:\Users\dougk\Desktop\test' #debug #default_directory = r'C:\\Users\\Doug\\Desktop\\test'; #data_root, output_root = file_location_chooser(default_directory); if (data_root is None) or (output_root is None): raise IOError("File location dialogs cancelled!") timestamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H.%M.%S") output_path = os.path.join(output_root, (timestamp + " output")) for file_path in filterByFileType(os.listdir(data_root), '.tif'): subfolder_name = os.path.splitext(file_path)[0] output_subfolder = os.path.join(output_path, subfolder_name) print(output_subfolder) os.makedirs(output_subfolder) imps = bf.openImagePlus(os.path.join(data_root, file_path)) imp = imps[0] imp.show() h = imp.height w = imp.width slices = imp.getNSlices() channels = imp.getNChannels() frames = imp.getNFrames() # rotation step - since using multiples of 90, TransformJ.Turn is more efficient IJ.run("Enhance Contrast", "saturated=0.35") angleZ = 1 while ((angleZ % 90) > 0): gd = GenericDialog("Rotate?") gd.addMessage( "Define rotation angle - increments of 90. Apical at top") gd.addNumericField("Rotation angle", 0, 0) gd.showDialog() angleZ = int(gd.getNextNumber()) if (angleZ > 1): IJ.run("TransformJ Turn", "z-angle=" + str(angleZ) + " y-angle=0 x-angle=0") imp.close() imp = WindowManager.getCurrentImage() imp.setTitle(file_path) # trim time series IJ.run("Enhance Contrast", "saturated=0.35") imp.setDisplayMode(IJ.COLOR) WaitForUserDialog( "Scroll to the first frame of the period of interest and click OK" ).show() start_frame = imp.getT() WaitForUserDialog( "Scroll to the last frame of the period of interest and click OK" ).show() end_frame = imp.getT() trim_imp = Duplicator().run(imp, 1, channels, 1, slices, start_frame, end_frame) imp.close() trim_imp.show() dup_imp = Duplicator().run(trim_imp) # create images to process and find bounds for dup_imps = ChannelSplitter().split(dup_imp) myo_imp = dup_imps[1] mem_imp = dup_imps[0] FileSaver(myo_imp).saveAsTiffStack( os.path.join(output_subfolder, "myosin_channel.tif")) FileSaver(mem_imp).saveAsTiffStack( os.path.join(output_subfolder, "membrane_channel.tif")) # set basal bounds myo_imp.show() ImageConverter(myo_imp).convertToGray8() frames = myo_imp.getNFrames() gb = GaussianBlur() for fridx in range(0, frames): myo_imp.setSliceWithoutUpdate(fridx + 1) ip = myo_imp.getProcessor() gb.blurGaussian(ip, 5.0, 1.0, 0.02) # assymmetrical Gaussian IJ.run(myo_imp, "Convert to Mask", "method=Otsu background=Dark calculate") IJ.run("Despeckle", "stack") title = myo_imp.getTitle() # assume that first frame is good quality image... basal_edges = find_basal_edges(myo_imp) #myo_imp.hide() mem_imp.hide() # draw some edges for checking roim = RoiManager() xs = [x for x in range(1, trim_imp.getWidth() + 1)] trim_imp.show() for fridx in range(0, myo_imp.getNFrames()): trim_imp.setPosition(2, 1, fridx + 1) IJ.run("Enhance Contrast", "saturated=0.35") roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE) trim_imp.setRoi(roi) roim.addRoi(roi)
def create_skeleton(image, name, min_branch_length=10, nuclei_rois=None, sample_width=4): print "Creating skeleton for %s, new name %s" %(image.getTitle(), name) # analyze skeleton skel = AnalyzeSkeleton_() skel.setup("", image) skelResult = skel.run(AnalyzeSkeleton_.NONE, False, True, None, True, False) # create copy of input image pruned_img = image.duplicate() outStack = pruned_img.getStack() # get graphs (one per skeleton in the image) graph = skelResult.getGraph() # list of end-points endPoints = skelResult.getListOfEndPoints() if graph: for i in range(len(graph)): listEdges = graph[i].getEdges() # go through all branches and remove branches < min_branch_length in duplicate image for e in listEdges: p = e.getV1().getPoints(); v1End = endPoints.contains( p.get(0) ) p2 = e.getV2().getPoints(); # print "p=",p, "p2=",p2 v2End = endPoints.contains( p2.get(0) ) # if any of the vertices is end-point if v1End or v2End : if e.getLength() < min_branch_length: if v1End: outStack.setVoxel( p.get(0).x, p.get(0).y, p.get(0).z, 0 ) if v2End: outStack.setVoxel( p2.get(0).x, p2.get(0).y, p2.get(0).z, 0 ) for p in e.getSlabs(): outStack.setVoxel( p.x, p.y, p.z, 0 ) pruned_img.setTitle(image.getTitle()+"-longestpath") sppoints = skel.getShortestPathPoints() if len(sppoints) == 0: return None, None, None, None, None, None ais_skeleton = pruned_img.duplicate() ais_skeleton.setTitle(name); IJ.run(ais_skeleton, "Select All", "") IJ.run(ais_skeleton, "Clear", "slice") points = [] angle = [] b_length = [len(b) for b in sppoints] longest_branch_idx = b_length.index(max(b_length)) points = [p for p in sppoints[longest_branch_idx]] closest_nucleus = None if nuclei_rois is not None: nroi1,dist1 = find_closest_roi(points[0].x, points[0].y, nuclei_rois) nroi2,dist2 = find_closest_roi(points[len(points)-1].x, points[len(points)-1].y, nuclei_rois) if nroi1 != nroi2 and dist2<dist1: # reverse order points = points[::-1] closest_nucleus = nroi2 else: closest_nucleus = nroi1 closest_nucleus.setName('%s-nucleus-ROI' % (name)) poly = Polygon() for p in points: poly.addPoint(int(p.x), int(p.y)) #for branch in sppoints: # print "Branch %s, len=%d" % (branch, len(branch)) # for p in branch: # poly.addPoint(int(p.x), int(p.y)) # points.append(p) angles,orthogonals = local_angles(points, scope=sample_width//2) ais_roi = PolygonRoi(poly, PolygonRoi.POLYLINE) ais_roi.setFillColor(Color(0.0,1.0,1.0,0.5)); ais_roi.setStrokeColor(Color(0.0,1.0,1.0,0.5)); ais_roi.setName('%s-AIS-ROI' % (name)) #ais_roi.setStrokeWidth(sample_width) IJ.run(ais_skeleton, "Analyze Particles...", "size=20-Infinity pixel exclude clear add"); IJ.run(ais_skeleton, "Clear", "slice") ip = ais_skeleton.getProcessor() for n in nuclei_rois: ais_skeleton.setRoi(n) if n == closest_nucleus: ip.setValue(128) else: ip.setValue(255) ip.fill(n.getMask()) ais_skeleton.setRoi(ais_roi) #ip.setValue(200) #ip.fill() #rois = RoiManager.getInstance2().getRoisAsArray() #for roi in rois: # ais_skeleton.setRoi(roi) # ip.setValue(255) # ip.fill(roi.getMask()); for p,a,o in zip(points,angles,orthogonals): # print "p=%s, a=%s, o=%s" % (p,a,o) ip.set(int(p.x), int(p.y), int(33+a/2)) ip.set(int(o[0].x), int(o[0].y),255) ip.set(int(o[1].x), int(o[1].y),255) IJ.run(ais_skeleton, "Fire", "") # pruned_img.setRoi(ais_roi) print "Created ais=%s" % ais_skeleton.getTitle() print len(skel.getShortestPathPoints()), len(points), len(orthogonals) return ais_skeleton, skel.getShortestPathPoints(), points, orthogonals, ais_roi, closest_nucleus
from ij.plugin import ImageCalculator as IC from ij.process import ImageStatistics as IS from ij.io import FileSaver from ij import WindowManager import os xpoints = [954, 708, 3156, 2760] ypoints = [1290, 2112, 1920, 1158] folderds = "F:\\MSc Misis\\4 Semestre\\Tesis 1\\DS Prueba" folderdsf = "F:\\MSc Misis\\4 Semestre\\Tesis 1\\DS Duplicado" i = 0 for filename in os.listdir(folderds): #Establecer Path Pathfile = ("F:\\MSc Misis\\4 Semestre\\Tesis 1\\DS Prueba\\" + filename) #Extraer imagen del Path dsimage = IJ.openImage(Pathfile) #Creación del área de interés roi = PolygonRoi(xpoints, ypoints, 4, Roi.POLYGON) #Creación de la imagen dsimage.setRoi(roi) #Duplicación de la imagen imp2 = dsimage.duplicate() #conversion a recipiente FileSaver fs = FileSaver(imp2) #Nombrar archivo filename = folderdsf + "\\" + str(i) + ".jpg" #Guardar archivo como JPEG fs.saveAsJpeg(filename) #impresion en consola del proceso print "Proccessing FinalFile", filename i = i + 1
def getCells(dicStack): outStack = ImageStack(W,H) cells = [None for t in range(T+1)] for t in range(1,T+1): mapp = dicStack.getProcessor(t).convertToFloatProcessor() mapp.subtract( mapp.getStatistics().mean ) mapp.abs() RankFilters().rank(mapp, 1.0, RankFilters.VARIANCE) mapp.sqrt() mapp.blurGaussian(5) hist = mapp.getHistogram(256) stats = mapp.getStatistics() thresh = AutoThresholder().getThreshold( AutoThresholder.Method.Otsu, hist ) thresh = (thresh/float(255)) * (stats.max-stats.min) + stats.min mask = ByteProcessor(W,H) for i in range(W*H): value = mapp.getf(i) bite = 255 if value>=thresh else 0 mask.set(i, bite) fillHoles(mask) ed = 3 for e in range(ed): mask.erode(1, 0) for d in range(ed): mask.dilate(1, 0) watershed(mask) minA = 5000 #px² mask.setThreshold(255,255, ImageProcessor.NO_LUT_UPDATE) composite = ThresholdToSelection().convert(mask) rois = ShapeRoi(composite).getRois() keep = [] for roi in rois: if roi.getStatistics().area >= minA: if not onEdge(roi): keep.append(roi) else: edgeRoi = ShapeRoi(roi) edgeRoi.setPosition(0,0,t) edgeRoi.setStrokeColor(Color.YELLOW) ol.add(edgeRoi) print("T"+str(t)+" using "+str(len(keep))+"/"+str(len(rois))+" ROIs") rois = keep #rois = [ roi for roi in rois if roi.getStatistics().area >= minA and not onEdge(roi) ] #keep big enough and not on edges # if there is only one Roi, cut it along the fitted ellipse minor axis if len(rois)==1: el = EllipseFitter() mask.setRoi(rois[0]) el.fit(mask, None) el.makeRoi(mask) theta = el.angle * (maths.pi/180.0) length = el.major/2.0 dy = maths.sin(theta)* length dx = maths.cos(theta)* length #major axis lineX0 = el.xCenter - dx lineY0 = el.yCenter + dy lineX1 = el.xCenter + dx lineY1 = el.yCenter - dy line = Line(lineX0, lineY0, lineX1, lineY1) line.setStrokeColor(Color.BLUE) line.setStrokeWidth(1) line.setPosition(0,0,t) ol.add(line) #minor axis scaled length to make sure cut ends are outside Roi cutX0 = el.xCenter + dy*100 cutY0 = el.xCenter + dx*100 cutX1 = el.yCenter - dy*100 cutY1 = el.yCenter - dx*100 cut = Line(cutX0,cutY0, cutX1, cutY1) cut.setStrokeWidth(2) cut = PolygonRoi( cut.getFloatPolygon(), PolygonRoi.POLYGON ) mask.setColor(0) mask.fill(cut) composite = ThresholdToSelection().convert(mask) rois = ShapeRoi(composite).getRois() rois = [ roi for roi in rois if roi.getStatistics().area >= minA ] print(str(t) + ":" + str(len(rois))) rois = [ PolygonRoi(roi.getInterpolatedPolygon(20, True), PolygonRoi.POLYGON) for roi in rois ] rois = [ PolygonRoi(roi.getConvexHull(), PolygonRoi.POLYGON) for roi in rois ] rois = sorted(list(rois), key=lambda roi:roi.getLength() ) #size order rois = rois[-2:] #keep 2 biggest rois = sorted(list(rois), key=lambda roi:roi.getStatistics().xCentroid+roi.getStatistics().yCentroid ) #top left to bottom right order if len(rois)>0: rois[0].setStrokeColor(Color.RED) rois[0].setPosition(0, 0, t) ol.add(rois[0]) if len(rois)>1: rois[1].setStrokeColor(Color.GREEN) rois[1].setPosition(0, 0, t) ol.add(rois[1]) cells[t] = (rois[0], rois[1]) return cells
def do_angular_projection(imp, max_r_pix=60, min_r_pix=10, generate_roi_stack=True): """perform ray-based projection of vessel wall, c.f. ICY TubeSkinner (Lancino 2018)""" Prefs.blackBackground = True print("do angular projection input imp = " + str(imp)) split_chs = ChannelSplitter().split(imp) mch_imp = split_chs[0] IJ.setAutoThreshold(mch_imp, "IsoData dark stack") egfp_imp = split_chs[1] proj_imp = Duplicator().run(egfp_imp) cl_imp = split_chs[2] if generate_roi_stack: egfp_imp_disp = Duplicator().run(egfp_imp) roi_stack = IJ.createImage("rois", egfp_imp.getWidth(), egfp_imp.getHeight(), egfp_imp.getNSlices(), 16) centres = [] projected_im_pix = [] ring_rois = [] for zidx in range(cl_imp.getNSlices()): if ((zidx + 1) % 100) == 0: print("Progress = " + str(round(100 * (float(zidx + 1) / cl_imp.getNSlices())))) projected_im_row = [] proj_imp.setZ(zidx + 1) mch_imp.setZ(zidx + 1) bp = mch_imp.createThresholdMask() bp.dilate() bp.erode() bp.erode() bp.erode() mask_imp = ImagePlus("mask", bp) IJ.run(mask_imp, "Create Selection", "") roi = mask_imp.getRoi() proj_imp.setRoi(roi) IJ.run(proj_imp, "Set...", "value=0 slice") IJ.run(proj_imp, "Make Inverse", "") roi = proj_imp.getRoi() centre = (roi.getStatistics().xCentroid, roi.getStatistics().yCentroid) centres.append(centre) ring_roi_xs = [] ring_roi_ys = [] for theta in range(360): pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)), centre[1] + min_r_pix * math.sin(math.radians(theta))) pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)), centre[1] + max_r_pix * math.sin(math.radians(theta))) roi = Line(pt1[0], pt1[1], pt2[0], pt2[1]) proj_imp.setRoi(roi) profile = roi.getPixels() projected_im_row.append(max(profile)) try: ring_roi_xs.append(roi.getContainedPoints()[profile.index( max(profile))].x) except IndexError: ring_roi_xs.append(pt2[0]) try: ring_roi_ys.append(roi.getContainedPoints()[profile.index( max(profile))].y) except IndexError: ring_roi_ys.append(pt2[1]) proj_imp.killRoi() ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE) ring_rois.append(ring_roi) if generate_roi_stack: roi_stack.setZ(zidx + 1) roi_stack.setRoi(ring_roi) IJ.run(roi_stack, "Line to Area", "") IJ.run( roi_stack, "Set...", "value=" + str(roi_stack.getProcessor().maxValue()) + " slice") #egfp_imp.setRoi(ring_roi); projected_im_pix.append(projected_im_row) # for ch in split_chs: # ch.close(); out_imp = ImagePlus( "projected", FloatProcessor([list(x) for x in zip(*projected_im_pix)])) if generate_roi_stack: roi_stack.show() egfp_imp_disp.show() # merge? else: roi_stack = None return out_imp, roi_stack, ring_rois, centres
def __midline(self): debug=False #print "line 251", self.__boolML if self.__boolML : ordpoints=self.__midLine[:] npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) return polyOrd #if self.getMaxF()<15 : return None #self.__FeretAxis() #return self.__line self.__boolML=True self.__image.killRoi() self.__image.setRoi(self.__contour) boundRect=self.__contour.getBounds() boundRoi=Roi(boundRect) xori=boundRect.x yori=boundRect.y wori=boundRect.width hori=boundRect.height ip2 = ByteProcessor(self.__image.getWidth(), self.__image.getHeight()) ip2.setColor(255) ip2.setRoi(self.__contour) ip2.fill(self.__contour) skmp=ImagePlus("ip2", ip2) skmp.setRoi(xori-1,yori-1,wori+1,hori+1) ip3=ip2.crop() skmp3=ImagePlus("ip3", ip3) skmp3.killRoi() #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l287") #------------------------------------------------------------- IJ.run(skmp3, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l294") #------------------------------------------------------------- IJ.run(skmp3, "BinaryConnectivity ", "white") ip3.setThreshold(3,4, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(skmp3, "Convert to Mask", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l302") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.updateAndDraw() skmp3.show() IJ.showMessage("imp3 l308") #------------------------------------------------------------- rawPoints=[] w=ip3.getWidth() h=ip3.getHeight() rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] tempbouts=[val for val in rawPoints if val[2]==2] if len(tempbouts)!=2 : return None # test #if len(tempbouts)!=2 : # # IJ.run(skmp3, "BinaryConnectivity ", "white") # ip3.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) # IJ.run(skmp3, "Convert to Mask", "") # #------------------------------------------------------------- # if debug==debug : # skmp3.updateAndDraw() # skmp3.show() # IJ.showMessage("if test l 328") ##------------------------------------------------------------- # rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] # tempbouts=[val for val in rawPoints if val[2]==2] ip3.setRoi(boundRect) if rawPoints==[]: return None npoints=len(rawPoints) xpoints=[point[0] for point in rawPoints] ypoints=[point[1] for point in rawPoints] valpoints=[point[2] for point in rawPoints] bouts={} if tempbouts==[]: return None if tempbouts[0][1]>tempbouts[1][1]: bouts["A"]=tempbouts[0] bouts["B"]=tempbouts[1] else: bouts["A"]=tempbouts[1] bouts["B"]=tempbouts[0] rawPoints.remove(bouts["A"]) rawPoints.remove(bouts["B"]) rawPoints.append(bouts["B"]) tempList=[val for val in rawPoints] p=bouts["A"] Dist={} ordPoints=[] for j in range(len(rawPoints)): Dist.clear() for i in range(len(tempList)): dx=p[0]-tempList[i][0] dy=p[1]-tempList[i][1] d=math.sqrt(dx*dx+dy*dy) Dist[d]=tempList[i] distList=Dist.keys() mind=min(distList) nextpoint=Dist[mind] ordPoints.append(nextpoint) tempList.remove(nextpoint) p=nextpoint ordPoints.insert(0, bouts["A"]) npoints=len(ordPoints) if npoints < 4 : return None xpoints=[point[0] for point in ordPoints] ypoints=[point[1] for point in ordPoints] polyOrd1=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) f=min(self.__midParams[0], len(xpoints)//2) angleA1=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[1],ypoints[1]) angleA2=polyOrd1.getAngle(xpoints[1],ypoints[1], xpoints[2],ypoints[3]) angleA = (angleA1+angleA2)/2.00 angleA=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[f],ypoints[f]) angleA=angleA*(math.pi/180) angleB1=polyOrd1.getAngle(xpoints[-2],ypoints[-2], xpoints[-1],ypoints[-1]) angleB2=polyOrd1.getAngle(xpoints[-3],ypoints[-3], xpoints[-2],ypoints[-2]) angleB = (angleB1+angleB2)/2.00 angleB=polyOrd1.getAngle(xpoints[-f],ypoints[-f], xpoints[-1],ypoints[-1]) angleB=angleB*(math.pi/180) coef=self.__midParams[1] xa = xpoints[0]-coef*f*math.cos(angleA) ya = ypoints[0]+coef*f*math.sin(angleA) xb = xpoints[-1]+coef*f*math.cos(angleB) yb = ypoints[-1]-coef*f*math.sin(angleB) lineA=Line(xpoints[0],ypoints[0], xa, ya) lineB=Line(xpoints[-1],ypoints[-1], xb, yb) lineA.setWidth(0) lineB.setWidth(0) lineA.setStrokeWidth(0) lineB.setStrokeWidth(0) ip2.setColor(0) ip2.fill() ip2.setColor(255) ip2.setRoi(lineA) lineA.drawPixels(ip2) ip2.setRoi(lineB) lineB.drawPixels(ip2) ip2.setRoi(self.__contour) ip2.setColor(0) ip2.fillOutside(self.__contour) ip2=ip2.crop() imb=ImagePlus("new-ip2", ip2) #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l416") #------------------------------------------------------------- w2=ip2.getWidth() h2=ip2.getHeight() ip4 = ByteProcessor(w2+2, h2+2) im4=ImagePlus("im4", ip4) for i in range(w2): for j in range(h2): ip4.set(i+1,j+1,max([ip2.getPixel(i,j),ip3.getPixel(i,j)])) #im4.show() #------------------------------------------------------------- if debug : im4.show() IJ.showMessage("im4 l430") #------------------------------------------------------------- im4.killRoi() #IJ.run(im4, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l300") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") ip4=im4.getProcessor() rawPoints2=[] w4=ip4.getWidth() h4=ip4.getHeight() rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] # test if len(self.__MidBouts)!=2 : IJ.run(im4, "BinaryConnectivity ", "white") ip4.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(im4, "Convert to Mask", "") rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] ordpoints=[] p0=self.__MidBouts[0] rawPoints2.remove(p0) c=0 while p0!=self.__MidBouts[1]: if c<len(rawPoints2): point=rawPoints2[c] else: break if abs(point[0]-p0[0])<2 and abs(point[1]-p0[1])<2: p0=point ordpoints.append(point) rawPoints2.remove(point) c=0 else: c=c+1 ordpoints.insert(0, self.__MidBouts[0]) self.__midLine=ordpoints[:] self.__midCenters = self.__Centers(self.__midLine) npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) #print self.__midLine #print self.__MidBouts #print xpoints #print ypoints return polyOrd
def makePolygon(xs, ys): imp = IJ.getImage() imp.setRoi(PolygonRoi(xs, ys, len(xs), Roi.POLYGON))