def subsample(self, vertices): xiyi = np.vstack((self.traj_lon[0, :], self.traj_lat[0, :])).T mpath = MplPath(vertices) outside_area = ~mpath.contains_points(xiyi) self.init_x, self.init_y, self.init_z, self.init_s, \ self.traj_lon, self.traj_lat, self.traj_depth, self.traj_time, self.final_z = \ [x.compress(outside_area,axis=-1) for x in (self.init_x, self.init_y, self.init_z, self.init_s, self.traj_lon, self.traj_lat, self.traj_depth, self.traj_time, self.final_z)]
def draw_bezier_curve(self, verts): self.cr.init(transform=None) self.cr.update_patch(self.pen, None) codes = [ MplPath.MOVETO, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, ] path = MplPath(verts, codes) p = patches.PathPatch(path, **self.cr.kwdargs) self.cr.axes.add_patch(p)
def get_mask(self, current_image): ny, nx = np.shape(current_image) poly_verts = ([(self.x[0], self.y[0])] + list(zip(reversed(self.x), reversed(self.y)))) # Create vertex coordinates for each grid cell... # (<0,0> is at the top left of the grid in this system) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T roi_path = MplPath(poly_verts) grid = roi_path.contains_points(points).reshape((ny, nx)) return grid
def getMask(self, roiLineCoords): ny, nx = np.shape(self.pixelArray) #print("roiLineCoords ={}".format(roiLineCoords)) # Create vertex coordinates for each grid cell... # (<0,0> is at the top left of the grid in this system) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack( (x, y)).T #points = every [x,y] pair within the original image #print("roiLineCoords={}".format(roiLineCoords)) roiPath = MplPath(roiLineCoords) #print("roiPath={}".format(roiPath)) self.mask = roiPath.contains_points(points).reshape((ny, nx))
def draw_ellipse_bezier(self, verts): self.cr.init(transform=None) self.cr.update_patch(self.pen, self.brush) # draw 4 bezier curves to make the ellipse codes = [ MplPath.MOVETO, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4, ] path = MplPath(verts, codes) p = patches.PathPatch(path, **self.cr.kwdargs) self.cr.axes.add_patch(p)
def to_array(roi_value, framesize: tuple = DEFAULT_FRAME_SIZE) -> np.ndarray: """Convert ImageJ roi to numpy array mask. Args: roi_value (ImageJ ROI): ImageJ Roi framesize (tuple, optional): Defaults to DEFAULT_FRAME_SIZE. Frame size to use (y,x) should be type int. Returns: numpy.ndarray: [description] """ x, y = np.meshgrid(np.arange(framesize[0]), np.arange(framesize[1])) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T pth = MplPath(list(zip(roi_value['x'], roi_value['y']))) grid = pth.contains_points(points) mask = grid.reshape(framesize[1], framesize[0]) return mask
def get_mask(self, current_image): print("get_mask") ny, nx = np.shape(current_image) print("ny ={} nx={}".format(ny, nx)) poly_verts = ([(self.x[0], self.y[0])] + list(zip(reversed(self.x), reversed(self.y)))) print("poly_verts ={}".format(poly_verts)) # Create vertex coordinates for each grid cell... # (<0,0> is at the top left of the grid in this system) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T #points = every [x,y] pair within the original image print("poly_verts={}".format(poly_verts)) roi_path = MplPath(poly_verts) print("roi_path={}".format(roi_path)) grid = roi_path.contains_points(points).reshape((ny, nx)) print("grid ={}".format(grid)) return grid
def saveMask(self): ny, nx = np.shape(self.img) poly_verts = ([(self.x[0], self.y[0])] + list(zip(reversed(self.x), reversed(self.y)))) # Create vertex coordinates for each grid cell... # (<0,0> is at the top left of the grid in this system) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T roi_path = MplPath(poly_verts) mask = 1 * roi_path.contains_points(points).reshape((ny, nx)) folder, filename = os.path.split(self.file_in) filename, extension = os.path.splitext(filename) if self.fn == None: self.fn = filename + '_manual' + extension imsave(os.path.join(folder, self.subfolder, self.fn), mask.astype(np.uint16)) self.close()
def grid_from_roi(im, vertices, single=False): """Return drawn ROI as grid. Args: im (Series): Series object as template vertices: The polygon vertices, as a dictionary of tags of (x,y) single (bool): Draw ROI in single slice per tag Returns: Numpy ndarray with shape (nz,ny,nx) from original image, dtype ubyte. Voxels inside ROI is 1, 0 outside. """ def _roi_in_any_slice(tag): """Check whether there is a ROI in any slice""" t, i = tag for idx in range(im.slices): # if (t, idx) in vertices and vertices[t, idx] is None: # print('Check {} None'.format((t, idx))) # elif (t, idx) in vertices: # print('Check {} {}'.format((t, idx), len(vertices[t, idx]))) # else: # print('Check {} not found'.format((t, idx))) if (t, idx) in vertices and vertices[t, idx] is not None: return True return False keys = list(vertices.keys())[0] # print('grid_from_roi: keys: {}'.format(keys)) # print('grid_from_roi: vertices: {}'.format(vertices)) follow = issubclass(type(keys), tuple) nt, nz, ny, nx = len(im.tags[0]), im.slices, im.rows, im.columns if follow and not single: grid = np.zeros_like(im, dtype=np.ubyte) skipped = [] copied = [] for idx in range(nz): last_used_tag = None for t in range(nt): tag = t, idx if tag not in vertices or vertices[tag] is None: if last_used_tag is None: # Most probably a slice with no ROIs skipped.append(tag) continue elif _roi_in_any_slice(tag): # print('Found in some slice for', tag) skipped.append(tag) continue # Propagate last drawn ROI to unfilled tags vertices[tag] = copy.copy(vertices[last_used_tag]) copied.append((tag, last_used_tag)) else: last_used_tag = tag path = MplPath(vertices[tag]) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T grid[t, idx] = path.contains_points(points).reshape((ny, nx)) elif follow and single: grid = np.zeros_like(im, dtype=np.ubyte) skipped = [] copied = [] last_used_tag = None for t in range(nt): for idx in range(nz): tag = t, idx if tag not in vertices or vertices[tag] is None: if last_used_tag is None: # Most probably a slice with no ROIs skipped.append(tag) continue elif last_used_tag[1] != idx: continue elif _roi_in_any_slice(tag): # print('Found in some slice for', tag) skipped.append(tag) continue # Propagate last drawn ROI to unfilled tags vertices[tag] = copy.copy(vertices[last_used_tag]) copied.append((tag, last_used_tag)) else: last_used_tag = tag path = MplPath(vertices[tag]) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T grid[t, idx] = path.contains_points(points).reshape((ny, nx)) # if len(skipped) > 0: # print('Skipped: {}'.format(skipped)) # if len(copied) > 0: # print('Copied: {}'.format(copied)) else: grid = np.zeros((nz, ny, nx), dtype=np.ubyte) for idx in range(nz): if idx not in vertices or vertices[idx] is None: continue path = MplPath(vertices[idx]) x, y = np.meshgrid(np.arange(nx), np.arange(ny)) x, y = x.flatten(), y.flatten() points = np.vstack((x, y)).T grid[idx] = path.contains_points(points).reshape((ny, nx)) return Series(grid, input_order=im.input_order, template=im, geometry=im)