def connect_extrema(im_pos, target, markers, visualize=False): ''' im_pos : XYZ positions of each point in image formation (n x m x 3) ''' height, width,_ = im_pos.shape centroid = np.array(target) im_pos = np.ascontiguousarray(im_pos.astype(np.int16)) cost_map = np.ascontiguousarray(np.zeros([height, width], dtype=np.uint16)) extrema = dgn.geodesic_map_MPI(cost_map, im_pos, np.array(centroid, dtype=np.int16), 1, 1) cost_map = extrema[-1] trails = [] for m in markers: trail = dgn.geodesic_trail(cost_map.copy()+(32000*(im_pos[:,:,2]==0)).astype(np.uint16), np.array(m, dtype=np.int16)) trails += [trail.copy()] if visualize: cost_map = deepcopy(cost_map) circ = circle(markers[0][0],markers[0][1], 5) circ = np.array([np.minimum(circ[0], height-1), np.minimum(circ[1], width-1)]) circ = np.array([np.maximum(circ[0], 0), np.maximum(circ[1], 0)]) cost_map[circ[0], circ[1]] = 0 for i,t in enumerate(trails[1:]): # embed() cost_map[t[:,0], t[:,1]] = 0 circ = circle(markers[i+1][0],markers[i+1][1], 5) circ = np.array([np.minimum(circ[0], height-1), np.minimum(circ[1], width-1)]) circ = np.array([np.maximum(circ[0], 0), np.maximum(circ[1], 0)]) cost_map[circ[0], circ[1]] = 0 return trails, cost_map else: return trails
def test_blob_dog(): r2 = math.sqrt(2) img = np.ones((512, 512)) img3 = np.ones((5, 5, 5)) xs, ys = circle(400, 130, 5) img[xs, ys] = 255 xs, ys = circle(100, 300, 25) img[xs, ys] = 255 xs, ys = circle(200, 350, 45) img[xs, ys] = 255 blobs = blob_dog(img, min_sigma=5, max_sigma=50) radius = lambda x: r2 * x[2] s = sorted(blobs, key=radius) thresh = 5 b = s[0] assert abs(b[0] - 400) <= thresh assert abs(b[1] - 130) <= thresh assert abs(radius(b) - 5) <= thresh b = s[1] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 300) <= thresh assert abs(radius(b) - 25) <= thresh b = s[2] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 350) <= thresh assert abs(radius(b) - 45) <= thresh assert_raises(ValueError, blob_dog, img3)
def create_mask(img, num_circles, lo_thickness, hi_thickness, patch_size): im = rgb2gray(img) m = np.ones_like(im) np.random.seed(31415926) for i in range(num_circles): im_tmp = np.ones_like(m) yy = np.random.randint(0, m.shape[0]) xx = np.random.randint(0, m.shape[1]) r = np.random.randint(20, m.shape[0] / 2) t = np.random.randint(lo_thickness, hi_thickness) rro, cco = circle(yy, xx, r, shape=m.shape) rri, cci = circle(yy, xx, r - t, shape=m.shape) im_tmp[rro, cco] = 0 im_tmp[rri, cci] = 1 m[im_tmp == 0] = 0 # Fix mask border. d = patch_size + 1 m[:d, :] = 1 m[-d:, :] = 1 m[:, :d] = 1 m[:, -d:] = 1 return m
def test_blob_dog(): img = np.ones((512, 512)) xs, ys = circle(400, 130, 5) img[xs, ys] = 255 xs, ys = circle(100, 300, 25) img[xs, ys] = 255 xs, ys = circle(200, 350, 45) img[xs, ys] = 255 blobs = blob_dog(img, min_sigma=5, max_sigma=50) area = lambda x: x[2] radius = lambda x: math.sqrt(x / math.pi) s = sorted(blobs, key=area) thresh = 5 b = s[0] assert abs(b[0] - 400) <= thresh assert abs(b[1] - 130) <= thresh assert abs(radius(b[2]) - 5) <= thresh b = s[1] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 300) <= thresh assert abs(radius(b[2]) - 25) <= thresh b = s[2] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 350) <= thresh assert abs(radius(b[2]) - 45) <= thresh
def get_snr(cube, angle_list, y, x, mode, svd_mode, fwhm, ncomp, fmerit): if mode=='full': frame = pca(cube, angle_list, ncomp=ncomp, full_output=False, verbose=False, mask_center_px=mask_center_px, svd_mode=svd_mode) elif mode=='annular': y_cent, x_cent = frame_center(cube[0]) annulus_radius = dist(y_cent, x_cent, y, x) frame = pca_annulus(cube, angle_list, ncomp, annulus_width, annulus_radius) else: raise RuntimeError('Wrong mode.') if fmerit=='max': yy, xx = draw.circle(y, x, fwhm/2.) snr_pixels = [phot.snr_ss(frame, y_, x_, fwhm, plot=False, verbose=False) for y_, x_ in zip(yy, xx)] return np.max(snr_pixels) elif fmerit=='px': return phot.snr_ss(frame, y, x, fwhm, plot=False, verbose=False) elif fmerit=='mean': yy, xx = draw.circle(y, x, fwhm/2.) snr_pixels = [phot.snr_ss(frame, y_, x_, fwhm, plot=False, verbose=False) for y_, x_ in zip(yy, xx)] return np.mean(snr_pixels)
def get_snr(frame, y, x, fwhm, fmerit): """ """ if fmerit == 'max': yy, xx = draw.circle(y, x, fwhm / 2.) res = [snr(frame, (x_, y_), fwhm, plot=False, verbose=False, full_output=True) for y_, x_ in zip(yy, xx)] snr_pixels = np.array(res)[:, -1] fluxes = np.array(res)[:, 2] argm = np.argmax(snr_pixels) # integrated fluxes for the max snr return np.max(snr_pixels), fluxes[argm] elif fmerit == 'px': res = snr(frame, (x, y), fwhm, plot=False, verbose=False, full_output=True) snrpx = res[-1] fluxpx = np.array(res)[2] # integrated fluxes for the given px return snrpx, fluxpx elif fmerit == 'mean': yy, xx = draw.circle(y, x, fwhm / 2.) res = [snr(frame, (x_, y_), fwhm, plot=False, verbose=False, full_output=True) for y_, x_ in zip(yy, xx)] snr_pixels = np.array(res)[:, -1] fluxes = np.array(res)[:, 2] # mean of the integrated fluxes (shifting the aperture) return np.mean(snr_pixels), np.mean(fluxes)
def test_get_largest_region(self): test_img = np.zeros((1000,1000), dtype=np.uint8) rr, cc = circle(100,100,50) test_img[rr,cc] = 1 rr, cc = circle(500,500,100) test_img[rr, cc] = 1 largest_region = gzapi.get_largest_region(test_img) self.assertTupleEqual(largest_region.centroid, (500,500))
def create_ringed_spider_mask(im_shape, ann_out, ann_in=0, sp_width=10, sp_angle=0): """ Mask out information is outside the annulus and inside the spiders (zeros). Parameters ---------- im_shape : tuple of int Tuple of length two with 2d array shape (Y,X). ann_out : int Outer radius of the annulus. ann_in : int Inner radius of the annulus. sp_width : int Width of the spider arms (3 branches). sp_angle : int angle of the first spider arm (on the positive horizontal axis) in counter-clockwise sense. Returns ------- mask : numpy ndarray 2d array of zeros and ones. """ mask = np.zeros(im_shape) s = im_shape[0] r = s/2 theta = np.arctan2(sp_width/2, r) t0 = np.array([theta, np.pi-theta, np.pi+theta, np.pi*2 - theta]) t1 = t0 + sp_angle/180 * np.pi t2 = t1 + np.pi/3 t3 = t2 + np.pi/3 x1 = r * np.cos(t1) + s/2 y1 = r * np.sin(t1) + s/2 x2 = r * np.cos(t2) + s/2 y2 = r * np.sin(t2) + s/2 x3 = r * np.cos(t3) + s/2 y3 = r * np.sin(t3) + s/2 rr1, cc1 = polygon(y1, x1) rr2, cc2 = polygon(y2, x2) rr3, cc3 = polygon(y3, x3) cy, cx = frame_center(mask) rr0, cc0 = circle(cy, cx, min(ann_out, cy)) rr4, cc4 = circle(cy, cx, ann_in) mask[rr0, cc0] = 1 mask[rr1, cc1] = 0 mask[rr2, cc2] = 0 mask[rr3, cc3] = 0 mask[rr4, cc4] = 0 return mask
def ring_mask(i,dim=_DIM): # ring masks are a series of 50 concentric rings, each dim/100 # pixels thick, around the center of the dim x dim array s = dim/100. rmin = (i * s) + _eps rmax = (i+1) * s c = (dim//2)+1 mask = np.zeros((dim,dim),dtype=np.bool) mask[circle(c,c,rmax)]=True mask[circle(c,c,rmin)]=False return mask
def add_circles(image, circles, cmap=plt.cm.cool): output = gray2rgb(image) for r, x, y, accum in circles: shape = list(reversed(image.shape)) xs_outer, ys_outer = circle(y, x, r, shape=shape) xs_inner, ys_inner = circle(y, x, r - 3, shape=shape) c_img = zeros(image.shape, dtype=bool) c_img[ys_outer, xs_outer] = 1 c_img[ys_inner, xs_inner] = 0 color_value = cmap(accum, bytes=True)[:-1] output[c_img] = color_value return output
def test_blob_dog(): r2 = math.sqrt(2) img = np.ones((512, 512)) xs, ys = circle(400, 130, 5) img[xs, ys] = 255 xs, ys = circle(100, 300, 25) img[xs, ys] = 255 xs, ys = circle(200, 350, 45) img[xs, ys] = 255 blobs = blob_dog(img, min_sigma=5, max_sigma=50) radius = lambda x: r2 * x[2] s = sorted(blobs, key=radius) thresh = 5 b = s[0] assert abs(b[0] - 400) <= thresh assert abs(b[1] - 130) <= thresh assert abs(radius(b) - 5) <= thresh b = s[1] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 300) <= thresh assert abs(radius(b) - 25) <= thresh b = s[2] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 350) <= thresh assert abs(radius(b) - 45) <= thresh # Testing no peaks img_empty = np.zeros((100,100)) assert blob_dog(img_empty).size == 0 # Testing 3D r = 10 pad = 10 im3 = ellipsoid(r, r, r) im3 = util.pad(im3, pad, mode='constant') blobs = blob_dog(im3, min_sigma=3, max_sigma=10, sigma_ratio=1.2, threshold=0.1) b = blobs[0] assert b[0] == r + pad + 1 assert b[1] == r + pad + 1 assert b[2] == r + pad + 1 assert abs(math.sqrt(3) * b[3] - r) < 1
def find_circle(self, image, frame, dim, **kw): dx, dy = None, None pframe = self._preprocess(frame, blur=0) edges = canny(pframe, sigma=3) hough_radii = arange(dim * 0.9, dim * 1.1, 2) hough_res = hough_circle(edges, hough_radii) centers = [] accums = [] radii = [] for radius, h in zip(hough_radii, hough_res): # For each radius, extract two circles num_peaks = 2 peaks = peak_local_max(h, num_peaks=num_peaks) centers.extend(peaks) accums.extend(h[peaks[:, 0], peaks[:, 1]]) radii.extend([radius] * num_peaks) # for idx in argsort(accums)[::-1][:1]: try: idx = argsort(accums)[::-1][0] except IndexError: return dx,dy center_y, center_x = centers[idx] radius = radii[idx] cx, cy = circle_perimeter(int(center_x), int(center_y), int(radius)) # draw perimeter try: frame[cy, cx] = (220, 20, 20) except IndexError: pass # draw center cx, cy = circle(int(center_x), int(center_y), int(2)) frame[cy, cx] = (220, 20, 20) h, w = frame.shape[:2] ox, oy = w / 2, h / 2 dx = center_x - ox dy = center_y - oy cx, cy = circle(int(ox), int(oy), int(2)) frame[cy, cx] = (20, 220, 20) image.set_frame(frame) return float(dx), -float(dy)
def add_LV(self, scale, drift=10): radius = self.lv_radius = self.base_lv_radius * scale thick = self.lv_thick = self.base_lv_thick * (4+scale)/5 # get center shift = np.array([np.random.randn()*drift, radius]) # print shift center = np.array([self.v/2, 10]) + shift self.lv_center = center self.lv_radius_vec = np.array([0,radius]) # get points self.lv_big = d.circle(center[0], center[1], radius) self.lv_small = d.circle(center[0], center[1], radius-thick)
def pick_foreground(im_rgb): points = [] im = im_rgb.copy() im_display = im_rgb.copy() # Have user specify region cv2.namedWindow("pick_region") cv2.setMouseCallback("pick_region", mouse_event, points) while len(points) < 1: # Display instructions txt = "Click background point." cv2.putText(im_display, txt, (10, 25), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255)) cv2.imshow("pick_region", im_display) ret = cv2.waitKey(30) im_display = im_rgb.copy() while len(points) < 2: # Display instructions txt = "Click foregorund point." cv2.putText(im_display, txt, (10, 25), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255)) # Display circles on corners for pt in points: circ = circle(pt[0], pt[1], 5) im_display[circ[0], circ[1]] = 255 cv2.imshow("pick_region", im_display) ret = cv2.waitKey(30) cv2.destroyWindow("pick_region") return np.array(points)
def test_circle(): img = np.zeros((15, 15), 'uint8') rr, cc = circle(7, 7, 6) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_)
def getMask(self, world, rad): '''Get a mask for the robot's world''' # Get the center of the robot pose x, y = self.rect.center # Draw a circle around that location xx, yy = draw.circle(x, y, rad, world.shape) # Set the index bounds of the world xMin = 0 xMax = world.shape[0]-1 yMin = 0 yMax = world.shape[1]-1 # Find the points of the circle that exced the index bounds xxMin = np.asarray(np.where(xx<xMin))[0] xxMax = np.asarray(np.where(xx>xMax))[0] yyMin = np.asarray(np.where(yy<yMin))[0] yyMax = np.asarray(np.where(yy>yMax))[0] # Clip the shape of the circle to the bounds of the world xyd = np.concatenate((xxMin,xxMax,yyMin,yyMax)) xx = np.delete(xx,xyd) yy = np.delete(yy,xyd) # Make an empty mask same size as the world mask = np.zeros(world.shape) # Apply the circle to mask of the world mask[xx, yy] = 1 return mask
def count_with_edge(dot): r, c = dot mask = np.zeros((height, width), dtype=np.uint8) rr, cc = draw.circle(r, c, radius) # min_r = np.where(rr >= 0)[0][0] # min_c = np.where(cc >= 0)[0][0] # min_i = max(min_r, min_c) # print(r, c) # print(height, width) # print(rr) # print(cc) # max_r = np.where(rr < height)[0][-1] # max_c = np.where(cc < width)[0][-1] # max_i = min(max_r, max_c) # # print(width, height) # # print(rr.shape) # # print(cc.shape) # # print(rr[min_i: max_i]) # # print(cc[min_i: max_i]) # rr = rr[min_i: max_i] # cc = cc[min_i: max_i] # print(rr) # print(cc) for _r, _c in zip(rr, cc): if 0 <= _r < height and 0 <= _c < width: mask[_r, _c] = 1 # mask[rr, cc] = 1 binary_for_cal = np.where(mask == 1, binary, False) return np.count_nonzero(binary_for_cal)
def label_blobs(self, diameter=None): ''' This function will create a labeled image from blobs essentially it will be circles at each location with diameter of 4 sigma ''' tolabel = np.zeros_like(self.data) try: blobs = self.blobs except AttributeError: # try to find blobs blobs = self.find_blobs() # if blobs is still none, exit if blobs is None: warnings.warn('Labels could not be generated', UserWarning) return None # Need to make this an ellipse using both sigmas and angle for blob in blobs: if diameter is None: radius = blob[2] * 4 else: radius = diameter rr, cc = circle(blob[0], blob[1], radius, self._data.shape) tolabel[rr, cc] = 1 labels, num_labels = label(tolabel) if num_labels != len(blobs): warnings.warn('Blobs have melded, fitting may be difficult', UserWarning) self._labels = labels return labels
def blackout_outside(self, img, sigma=3): img_g = skic.rgb2gray(img) edges = skif.canny(img_g, sigma=sigma) hough_radii = np.arange(180, 210, 2) hough_res = skit.hough_circle(edges, hough_radii) centers = [] accums = [] radii = [] for radius, h in zip(hough_radii, hough_res): # For each radius, extract two circles num_peaks = 1 peaks = skif.peak_local_max(h, min_distance=40, num_peaks=num_peaks) if peaks != []: centers.extend(peaks) accums.extend(h[peaks[:, 0], peaks[:, 1]]) radii.extend([radius] * num_peaks) # print radius, np.max(h.ravel()), len(peaks) if accums == [] and sigma==3: return self.blackout_outside(img, sigma=3) # Draw the most prominent 5 circles image = (img.copy() / 4.0).astype(np.uint8) cx, cy = skid.circle(*self.average_hough_detections(hough_radii, hough_res)) image[cy, cx] = img[cy, cx] return image
def display_edges(image, g, threshold): """Draw edges of a RAG on its image Returns a modified image with the edges drawn.Edges are drawn in green and nodes are drawn in yellow. Parameters ---------- image : ndarray The image to be drawn on. g : RAG The Region Adjacency Graph. threshold : float Only edges in `g` below `threshold` are drawn. Returns: out: ndarray Image with the edges drawn. """ image = image.copy() for edge in g.edges_iter(): n1, n2 = edge r1, c1 = map(int, rag.node[n1]['centroid']) r2, c2 = map(int, rag.node[n2]['centroid']) line = draw.line(r1, c1, r2, c2) circle = draw.circle(r1,c1,2) if g[n1][n2]['weight'] < threshold : image[line] = 0,1,0 image[circle] = 1,1,0 return image
def draw_reference_frame(x, y, z, h, theta): frame = np.ones((2 * y + 1, x + 1)) frame.fill(0) red_x = np.array([0, x // 2, x, 0]) red_y = np.array([0, y, 0, 0]) rr, cc = draw.polygon(red_y, red_x) frame[rr, cc] = 2 m = h * x // (2 * y) white_x = np.array([m, x - m, z, m]) white_y = np.array([h, h, 0, h]) rr, cc = draw.polygon(white_y, white_x) frame[rr, cc] = 3 cy = y cx = x // 2 - 1 radius = cx rr, cc = draw.circle(cy, cx, radius) zeros = np.ones_like(frame) zeros[rr, cc] = 0 frame[zeros == 1] = 1 c_in = np.array(frame.shape) // 2 c_out = np.array(frame.shape) // 2 transform = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) offset = c_in - c_out.dot(transform) frame = ndimage.interpolation.affine_transform(frame, transform.T, order=0, cval=1, offset=offset).astype(int) return frame.astype("uint8")
def test_sets_all(labels_all, x_center, y_center, radius, feature_filename, testindex, rot=False):# n_rot=1, x_center=0, y_center=0): #returns (X_test, y_test) #labels_all: labels [img, x, y] c: class labels c=0 no label # x_center, y_center, radius: parameters for interesting region trainingspxls are used from #feature_filename: filename of hdf5 file with dataset 'data' containing feature_array [x,y,img/imgRot,f] #testindex: between 0 and k indicate fold used for testing all others are used for training #rot: True if featuresarray with imgRot is used #open feature file featuresF = h5py.File(feature_filename,'r') #global parameters n_features = featuresF['data'].shape[3] xDim = featuresF['data'].shape[0] yDim = featuresF['data'].shape[1] #array for features of one frame features = np.zeros((xDim, yDim, n_features), dtype=np.float32) x, y = circle(y_center, x_center, radius) X_test = np.zeros((len(x), n_features)) y_test = np.zeros((len(x),)) if rot==False: features[:,:,:] = featuresF['data'][:,:,testindex,:] X_test[:, :] = features[x,y,:] else: features[:,:,:] = featuresF['data'][:,:,testindex*n_rot,:] X_test[:, :] = features[x,y,:] y_test[:] = labels_all[testindex, x, y] featuresF.close() return (X_test, y_test)
def animate(i): plt.title('Frame %d' % i) slice_data = preprocess_data(data[i + 100]) if np.count_nonzero(slice_data): labeled_data, num_features = segment_data(slice_data) stats = slice_stats(labeled_data) stats = stats[(stats.area > 20) & ((stats.major_axis_length < frame_shape[0]) | (stats.major_axis_length < frame_shape[1]))] stats = stats[stats.circularity > 0.5] for index, row in stats.iterrows(): print 'Frame# %d, Circle# %d [circularity = %f]' % (i, row.label, row.circularity) yc, xc = [int(round(x)) for x in row.centroid] orientation = row.orientation major_axis = int(round(row.major_axis_length/2.)) minor_axis = int(round(row.minor_axis_length/2.)) slice_data = ski.color.gray2rgb(slice_data) cy, cx = ellipse_perimeter(yc, xc, minor_axis, major_axis, orientation) slice_data[cy, cx] = (220, 20, 20) rr, cc = circle(yc, xc, 2) slice_data[rr, cc] = (220, 20, 20) im.set_data(slice_data) return im,
def add_cm(image, centers, color): return_image = image.copy() for center in centers: rr, cc = circle(center[0], center[1], 10) return_image[rr, cc, 0] = 1 return_image[rr, cc, color] = 1 return return_image
def pick_bounding_box(im_rgb): # global bounding_box bounding_box = [] im = im_rgb.copy() im_display = im_rgb.copy() # Display instructions txt = "Click on 4 points." cv2.putText(im_display, txt, (10, 25), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255)) # Have user specify region cv2.namedWindow("pick_region") cv2.setMouseCallback("pick_region", mouse_event, bounding_box) while len(bounding_box) < 4: # Display circles on corners for pt in bounding_box: circ = circle(pt[0], pt[1], 5) im_display[circ[0], circ[1]] = 255 # Display lines between points # if len(bounding_box) > 1: # for i in range(len(bounding_box)-1): # pt1 = boundin_box[i] # pt2 = boundin_box[i+1] cv2.imshow("pick_region", im_display) ret = cv2.waitKey(30) cv2.destroyWindow("pick_region") return np.array(bounding_box)
def draw(self,img, color=red): line = draw.line(self.y1, self.x1, self.y2, self.x2) draw.set_color(img, line, color) if self.cx and self.cy: centre = draw.circle(self.cy, self.cx, 3) draw.set_color(img, centre, color)
def _mask(self, src): radius = self.mask_radius h, w = src.shape c = circle(h / 2., w / 2., radius) mask = zeros_like(src, dtype=bool) mask[c] = True src[invert(mask)] = 0 return mask
def get_indices(self): """Returns a set of points that lie inside the picked polygon.""" if not self.center or not self.radius: raise ValueError("cannot get circle indicies before its dimensions are defined") x, y = self.center r = self.radius return circle(y, x, r, self.im)
def remove_sphere(image, center_x, center_y, radius): cx, cy = draw.circle(center_x, center_y, radius) masked = np.copy(image) masked[cy, cx] = 0 return masked
def test_blob_overlap(): img = np.ones((512, 512), dtype=np.uint8) xs, ys = circle(100, 100, 20) img[xs, ys] = 255 xs, ys = circle(120, 100, 30) img[xs, ys] = 255 blobs = blob_doh( img, min_sigma=1, max_sigma=60, num_sigma=10, threshold=.05) assert len(blobs) == 1
def visualize(folder, imagenames, mesh_2d, joints_2d, root=None): i = 0 for name, mesh, joints in zip(imagenames, mesh_2d, joints_2d): print(name) shutil.copyfile(root + name, '/im_gt_{}.png'.format(folder, i)) im = imread(name) shape = im.shape[0:2] height = im.shape[0] for p2d in mesh: im[height - p2d[1], p2d[0]] = [127, 127, 127] for j2d in joints: rr, cc = circle(height - j2d[1], j2d[0], 2, shape) im[rr, cc] = [255, 0, 0] imwrite('{}/im_mask_{}.png'.format(folder, i), im) i += 1
def build_ground_truth(img3d, blobs, ellipsoid=False, labels=None, spacing=None): """Build ground truth volumetric image from blobs. Attributes: img3d: Image as 3D Numpy array in which to store results blobs: Numpy array of segments to display, given as an (n, 4) dimension array, where each segment is in (z, y, x, radius). ellipsoid: True to draw blobs as ellipsoids; defaults to False. labels: Array of labels the same length as ``blobs`` to assign as the values for each ground truth; defaults to None to assign a default value of 1 instead. spacing: Spacing by which to multiply blobs` radii; defaults to None, in which case each blob's radius will be used for all dimensions. Returns: ``img3d`` with ground drawn as circles or ellipsoids. """ if ellipsoid: # draw blobs as ellipses for i, blob in enumerate(blobs): if spacing is None: centroid = np.repeat(blob[3], 3) else: # multiply spacing directly rather than using in ellipsoid # function since the fn does not appear to place the # ellipsoide in the center of the array centroid = np.multiply(blob[3], spacing) ellip = draw.ellipsoid(*centroid) label = True if labels is None else labels[i] replace_vol(img3d, ellip, blob[:3], vol_as_mask=label) else: # draw blobs as circles only in given z-planes if labels is None: labels = np.ones(len(blobs), dtype=int) for i in range(img3d.shape[0]): mask = blobs[:, 0] == i blobs_in = blobs[mask] labels_in = labels[mask] for blob, label in zip(blobs_in, labels_in): rr, cc = draw.circle(*blob[1:4], img3d[i].shape) #print("drawing circle of {} x {}".format(rr, cc)) img3d[i, rr, cc] = label return img3d
def is_entrance(self, loc_2d, idx=None): # idx is row index of gaze file, and also entrance masks i_gaze, j_gaze = csv.coord2Pixel(loc_2d['x'], loc_2d['y'], self.shape[1], self.shape[0]) if (self.mask_path is not None): return self.masks[idx].astype(bool)[i_gaze, j_gaze] else: mask = np.zeros(self.shape, dtype=bool) rr, cc = circle(i_gaze, j_gaze, self.shape[0] * self.entrance_radius, shape=self.shape) mask[rr, cc] = True return mask[i_gaze, j_gaze]
def GeneratePupilTemplates(self): """ Generates templates for the pupil @return: """ self.radii = range(self.minRadius, self.maxRadius + 1) self.pupilTemplates = numpy.ones( [2 * self.maxRadius + 5, 2 * self.maxRadius + 5, len(self.radii)], numpy.uint8) * 255 for i in range(len(self.radii)): y, x = circle(self.maxRadius + 2, self.maxRadius + 2, self.radii[i]) self.pupilTemplates[x, y, i] = 0 self.staleTemplates = False
def crop_circle(image, circle): cropped_image = rgb2gray(image) center_y, center_x, radius, _ = circle x1 = center_x - radius x2 = center_x + radius y1 = center_y - radius y2 = center_y + radius circy, circx = draw.circle(center_y, center_x, radius, shape=image.shape) mask = np.ones(cropped_image.shape, dtype=bool) mask[circy, circx] = False cropped_image[mask] = 0 cropped_image = cropped_image[y1:y2, x1:x2] return cropped_image
def transform(position_vector): relative_position_vector = (position_vector[0], position_vector[1] + 30 * 0.263) r = np.linalg.norm(relative_position_vector) phi = np.arccos((l1**2 + l2**2 - r**2) / (2 * l1 * l2)) beta = np.arccos((l1**2 + r**2 - l2**2) / (2 * l1 * r)) alpha = np.arctan2(relative_position_vector[1], relative_position_vector[0]) theta = beta + alpha # left handed solution return np.degrees((theta, phi)) starting_pos = (width / 2, height / 2) arm_starting_pos = (width / 2, height / 2 + 30) img = np.zeros((height, width), dtype=np.uint8) rr, cc = draw_line((0, 0), (int(l1 * np.cos(theta)), int(l1 * np.sin(theta))), arm_starting_pos) img[rr, cc] = 255 rr, cc = draw_line( (int(l1 * np.cos(theta)), int(l1 * np.sin(theta))), (int(l1 * np.cos(theta) + l2 * np.cos(phi + theta - np.pi)), int(l1 * np.sin(theta) + l2 * np.sin(phi + theta - np.pi))), arm_starting_pos) img[rr, cc] = 255 rr, cc = polygon_perimeter([ starting_pos[1] - b_height, starting_pos[1], starting_pos[1], starting_pos[1] - b_height ], [ starting_pos[0] - b_width / 2, starting_pos[0] - b_width / 2, starting_pos[0] + b_width / 2, starting_pos[0] + b_width / 2 ]) img[rr, cc] = 255 rr, cc = circle(starting_pos[1] - position_vector[1], starting_pos[0] + position_vector[0], 3) img[rr, cc] = 255 scipy.misc.imsave("out.png", img) return np.degrees((theta, phi))
def draw_pix(img, coord, r, g, b): rows = img.shape[0] cols = img.shape[1] for row in range(0, rows): for col in range(0, cols): if [col, row] in coord: if img[row, col, 0] != r and img[row, col, 1] != g and img[row, col, 2] != b: # draw circle in interesting point img[row, col, :] = (r, g, b) rr, cc = draw.circle(row, col, 7, img.shape) img[rr, cc, :] = (r, g, b) return img
def draw_pose_from_cords(pose_joints, pose_dim, img_size, radius=2, draw_joints=True, img=np.zeros([224, 224, 3])): colors = np.zeros(shape=img_size + (3, ), dtype=np.uint8) # interesting case of numpy array assignment semantics here . . the below ass is a view, hence the overliad poses error that destroyed the precious time of an incomporable specimen on this overpopulated information craving filth obsessed world # colors = img mask = np.zeros(shape=img_size, dtype=bool) if draw_joints: if (pose_dim == 16): for f, t in LIMB_SEQ: from_missing = pose_joints[f][ 0] == MISSING_VALUE or pose_joints[f][1] == MISSING_VALUE to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[ t][1] == MISSING_VALUE if from_missing or to_missing: continue yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1]) colors[yy, xx] = np.expand_dims(val, 1) * 255 mask[yy, xx] = True else: for f, t in LIMB_SEQ_PAF: from_missing = pose_joints[f][ 0] == MISSING_VALUE or pose_joints[f][1] == MISSING_VALUE to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[ t][1] == MISSING_VALUE if from_missing or to_missing: continue yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1]) colors[yy, xx] = np.expand_dims(val, 1) * 255 mask[yy, xx] = True for i, joint in enumerate(pose_joints): if pose_joints[i][0] == MISSING_VALUE or pose_joints[i][ 1] == MISSING_VALUE: continue yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size) colors[yy, xx] = COLORS[i] mask[yy, xx] = True return colors, mask
def addPoints(self, points, edges, h, w, s, color): """ """ def getGridCoord(xw, yw, h, w, s): """ Given a world coordinate, it returns it index on the grid """ row = int(h / (2 * s) - m.floor(yw / s)) col = int(m.ceil(xw / s) + w / (2 * s)) return row, col # for i in range(len(points)): row, col = getGridCoord(points[i][0], points[i][1], h, w, s) rr, cc = skd.circle(row, col, 2) self.occGrid[rr, cc] = color for e in edges[i]: row1, col1 = getGridCoord(points[e][0], points[e][1], h, w, s) rr, cc = skd.line(row, col, row1, col1) self.occGrid[rr, cc] = color
def zoom_in(get_frame, t, dotsize=2, rectangle_size=rectangle_size): # get frame a time t in seconds image = get_frame(t) # copy frame [ny x ny x N] # N is the number of 3 color channels frame = image.copy() # convert t from secs to samples index = int(np.round(t * 1.0 * fps)) #print('index {}, time {}'.format(index, t)) if index % 1000 == 0: print("Time frame @ {} [sec] is {} [idx]\n".format(t, index)) # get centers of window: x_mean, y_mean xc = x[index] yc = y[index] # get window around centers # x: xc - r : xc + r xi = slice(max(xc - rectangle_size, 0), min(xc + rectangle_size, nx - 1)) yi = slice(max(yc - rectangle_size, 0), min(yc + rectangle_size, ny - 1)) # re-calculate center xc = xc - max(xc - rectangle_size, 0) yc = yc - max(yc - rectangle_size, 0) # build a frame with 3 color channels frame_region = np.zeros((2 * rectangle_size, 2 * rectangle_size, 3)) # fill frame right corner matches right corner yi1, yi2 = int(yi.start), int(yi.stop) xi1, xi2 = int(xi.start), int(xi.stop) frame_region[:yi2 - yi1, :xi2 - xi1, :] = frame[yi1:yi2, xi1:xi2, :] rr, cc = circle(yc, xc, dotsize, shape=(2 * rectangle_size, 2 * rectangle_size)) frame_region[rr, cc, :] = (1, 1, 0) return frame_region
def render(self, mode='human'): """ Class that renders the position of the walker on the plane :param mode: :return: """ if mode == 'human': return None else: array = np.zeros(self.resolution + [3]) pixel_coord = (self.pose * self.center) + self.center rr, cc = draw.circle(pixel_coord[0], pixel_coord[1], radius=5, shape=array.shape) array[rr, cc] = np.array([1, 0, 0]) # Paint circle in red return array
def pixel_intensity(sample_location, frames, x_name, y_name, plate_name): ''' Function to find pixel intensity at all sample locations and plate locations in each frame. Parameters ----------- sample_location : Dataframe A dataframe containing sample and plate locations. frames : Array An array of arrays containing all the frames of a video. x_name : String Name of the column in sample_location containing the row values of the samples. y_name : String Name of the column in sample_location containing the column values of the samples. plate_name : String Name of the column in sample_location containing the column values of the plate location. Returns -------- temp : List Temperature of all the samples in every frame of the video. plate_temp : List Temperature of the plate next to every sample in every frame of the video. ''' temp = [] plate_temp = [] # Row values of the peaks x = sample_location[x_name] # Column values of the peaks y = sample_location[y_name] # Row value of the plate location p = sample_location[plate_name] for i in range(len(sample_location)): temp_well = [] plate_well_temp = [] for frame in frames: rr, cc = circle(x[i], y[i], radius=1) sample_intensity = np.mean(frame[rr, cc]) temp_well.append(centikelvin_to_celsius(frame[x[i]][y[i]])) plate_well_temp.append(centikelvin_to_celsius(frame[p[i]][y[i]])) temp.append(temp_well) plate_temp.append(plate_well_temp) return temp, plate_temp
def DiskKernel(dim): kernelwidth = dim dim=kernelwidth=kernelwidth.astype(np.int) kernel = np.zeros((kernelwidth, kernelwidth), dtype=np.float32) if dim%2==0: circleCenterCoord = (dim-1) / 2 circleRadius = dim / 2 else: circleCenterCoord = (dim) // 2 circleRadius = (dim) / 2 rr, cc = circle(circleCenterCoord, circleCenterCoord, circleRadius) kernel[rr,cc]=1 #print(kernel) normalizationFactor = np.count_nonzero(kernel) kernel = kernel / normalizationFactor return kernel
def build_target(craters): """Takes a list of craters and returns a mask image, 1700x1700 with binary pixels; 0 is non-crater, 1 is crater. """ size = (1700, 1700) image = np.zeros(size, dtype='uint8') for i, crater in craters.iterrows(): x = crater['x'] y = crater['y'] r = crater['d'] / 2 if r < 80: rr, cc = circle(y, x, r) try: image[rr, cc] = 255 except: pass return image
def produce_ma_mask(self, kp_array, img_size, point_radius=15): MISSING_VALUE = 0 mask = np.zeros(shape=img_size, dtype=np.uint8) limbs = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [9, 10], [10, 11], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], [1, 16], [16, 18], [2, 17], [2, 18], [9, 12], [17, 18]] #[12,6], [9,3],[6,9],[3,12] limbs = np.array(limbs) - 1 #pdb.set_trace() for f, t in limbs: from_missing = kp_array[f][0] == MISSING_VALUE or kp_array[f][ 1] == MISSING_VALUE to_missing = kp_array[t][0] == MISSING_VALUE or kp_array[t][ 1] == MISSING_VALUE #from_missing = kp_array[f][2] == MISSING_VALUE #to_missing = kp_array[t][2] == MISSING_VALUE if from_missing or to_missing: continue norm_vec = kp_array[f] - kp_array[t] norm_vec = np.array([-norm_vec[1], norm_vec[0]]) norm_vec = point_radius * norm_vec / np.linalg.norm(norm_vec) vetexes = np.array([ kp_array[f] + norm_vec, kp_array[f] - norm_vec, kp_array[t] - norm_vec, kp_array[t] + norm_vec ]) #pdb.set_trace() yy, xx = polygon(vetexes[:, 1], vetexes[:, 0], shape=img_size) mask[yy, xx] = 255 for i, joint in enumerate(kp_array): if kp_array[i][0] == MISSING_VALUE or kp_array[i][ 1] == MISSING_VALUE: #if kp_array[i][2] == MISSING_VALUE: continue yy, xx = circle(joint[1], joint[0], radius=point_radius, shape=img_size) mask[yy, xx] = 255 #mask[:,:] = np.where(mask[:,:] == True, 255, 0) #cv2.imshow('s',mask.astype(np.uint8)) return np.uint8(mask)
def CreateVideo(clip, Dataframe, pcutoff, dotsize, colormap, DLCscorer, bodyparts2plot, cropping, x1, x2, y1, y2): ''' Creating individual frames with labeled body parts and making a video''' colorclass = plt.cm.ScalarMappable(cmap=colormap) C = colorclass.to_rgba(np.linspace(0, 1, len(bodyparts2plot))) colors = (C[:, :3] * 255).astype(np.uint8) if cropping: ny, nx = y2 - y1, x2 - x1 else: ny, nx = clip.height(), clip.width() fps = clip.fps() nframes = len(Dataframe.index) duration = nframes / fps print("Duration of video [s]: ", round(duration, 2), ", recorded with ", round(fps, 2), "fps!") print("Overall # of frames: ", nframes, "with cropped frame dimensions: ", nx, ny) print("Generating frames and creating video.") df_likelihood = np.empty((len(bodyparts2plot), nframes)) df_x = np.empty((len(bodyparts2plot), nframes)) df_y = np.empty((len(bodyparts2plot), nframes)) for bpindex, bp in enumerate(bodyparts2plot): df_likelihood[ bpindex, :] = Dataframe[DLCscorer][bp]['likelihood'].values df_x[bpindex, :] = Dataframe[DLCscorer][bp]['x'].values df_y[bpindex, :] = Dataframe[DLCscorer][bp]['y'].values for index in tqdm(range(nframes)): image = clip.load_frame() if cropping: image = image[y1:y2, x1:x2] else: pass for bpindex in range(len(bodyparts2plot)): if df_likelihood[bpindex, index] > pcutoff: xc = int(df_x[bpindex, index]) yc = int(df_y[bpindex, index]) #rr, cc = circle_perimeter(yc,xc,radius) rr, cc = circle(yc, xc, dotsize, shape=(ny, nx)) image[rr, cc, :] = colors[bpindex] frame = image clip.save_frame(frame) clip.close()
def generateLabelImagesText(fp, imgDir, fontScale=1, size=1, rank=0, scale=1): [row, col, numFrames, frameList] = misc.getVitals(fp) particleList = fp.attrs['particleList'] zfillVal = fp.attrs['zfillVal'] procFrameList = numpy.array_split(frameList, size) trackingData = numpy.loadtxt(fp.attrs['outputDir'] + '/tracking.dat') for frame in tqdm(procFrameList[rank]): gImg = fp['/dataProcessing/gImgRawStack/' + str(frame).zfill(zfillVal)].value gImgNormScaled = imageProcess.normalize(cv2.resize( gImg, (int(col * scale), int(row * scale)), interpolation=cv2.INTER_CUBIC), min=0, max=230) bImg = gImgNormScaled.copy() bImg[:] = 0 tracking = trackingData[trackingData[:, 0] == frame] for f, particle, r, c, rad, area, label in tracking: if (label != 0): rr, cc = circle_perimeter(int(r * scale), int(c * scale), int(rad * scale)) if ((rr < 0).any() == True or (cc < 0).any() == True): pass elif ((rr > row * scale - 1).any() == True or (cc > col * scale - 1).any() == True): pass else: gImgNormScaled[rr, cc] = 255 rr, cc = circle(int(r * scale), int(c * scale), int(rad * scale)) bImg[rr, cc] = 255 for f, particle, r, c, rad, area, label in tracking: if (label != 0): bImg = imageProcess.textOnGrayImage( bImg, str(int(label)), (int(r * scale), int(c * scale)), fontScale=fontScale, color=127, thickness=1) finalImage = numpy.column_stack((gImgNormScaled, bImg)) cv2.imwrite(imgDir + '/' + str(frame).zfill(zfillVal) + '.png', finalImage) return 0
def process_results(apt_data, cell_data, exp_cond_fields, cell_marker_color): keys = ['acq_id', 'apt_id'] # Of all the apt/st images, choose the one with best focus (regardless of raw file it came from) apt_data = apt_data.groupby(exp_cond_fields + ['st_num', 'apt_num', 'acq_datetime', 'elapsed_hours_group']) \ .apply(lambda g: g[['apt_image', 'focus_score', 'acq_id', 'apt_id']].sort_values('focus_score').iloc[0]) \ .reset_index().set_index(keys) if not apt_data.index.is_unique: apt_data_dupe = apt_data[apt_data.index.duplicated()] raise AssertionError( 'Apartment data index should be unique; Duplicate rows:\n{}'. format(apt_data_dupe)) # Set index on cell data to make it searchable if len(cell_data) > 0: cell_data = cell_data.set_index(keys).sort_index() df = [] for i, r in apt_data.iterrows(): img = r['apt_image'].copy() # Get cell data for this apartment (if it exists, which it may not if there # really are 0 cells present) cdf = cell_data.loc[[i]] if i in cell_data.index else pd.DataFrame() if len(cdf) > 0 and cdf[['centroid_x', 'centroid_y' ]].isnull().any().any(): raise AssertionError( 'Apartment with index (acq_id, apt_id) = "{}" has cell data w/ null coordinates' .format(i)) # Draw centroids of cells on image if cell_marker_color is not None: for _, cr in cdf.iterrows(): cx, cy = cr['centroid_x'], cr['centroid_y'] rr, cc = draw.circle(cy, cx, 2, shape=img.shape) img[rr, cc] = np.array(cell_marker_color, dtype=np.uint8) row = r.rename({'apt_image': 'original_image'}).to_dict() row['image'] = img row['cell_count'] = len(cdf) df.append(row) return pd.DataFrame(df)
def gen_polys(points, ppoints): #generates a circular mask side_len = 500 rad = 235 mask = np.zeros(shape=(side_len, side_len)) rr, cc = draw.circle(side_len / 2, side_len / 2 + 5, radius=rad, shape=mask.shape) mask[rr, cc] = 1 mask[:int(side_len / 2) - 1, :] = 0 #makes a polygon from the mask perimeter #se = get_circular_se(radius=1) #contour = mask - binary_erosion(mask, structure=se) contour = mask - binary_erosion(mask) pixels_mask = np.array(np.where(contour == 1)[::-1]).T polygon = polygonize_by_nearest_neighbor(pixels_mask) polygon = Polygon(polygon) new_points, new_ppoints = [], [] for i, point in enumerate(points): if polygon.contains(Point(point)): new_points.append( [p * (1 + np.random.uniform(-0.00, 0.00)) for p in point]) new_ppoints.append(ppoints[i]) new_points = np.array(new_points) new_ppoints = np.array(new_ppoints) #performs voronoi tesselation #if len(points) > 3: #otherwise the tesselation won't work vor = Voronoi(new_points) regions, vertices = voronoi_finite_polygons_2d(vor) #clips tesselation to the mask new_vertices = [] for region in regions: poly_reg = vertices[region] shape = list(poly_reg.shape) shape[0] += 1 p = Polygon(np.append( poly_reg, poly_reg[0]).reshape(*shape)).intersection(polygon) poly = (np.array(p.exterior.coords)).tolist() new_vertices.append(poly) return new_vertices
def build_halo_mask(fixed_depth=30, margin=21, min_fragment=10): """ Function builds a configuration for halo region building :param fixed_depth: Maximum object on an image :param margin: The size of halo region :param min_fragment: Minimal size of an object on the image :return: a function for generation labels, masks and object_lists used by halo loss """ assert margin % 2 is not 0, "Margin should be odd" rr, cc = circle(margin / 2, margin / 2, margin / 2 + 1, shape=(margin, margin)) structure_element = numpy.zeros((margin, margin)) structure_element[rr, cc] = 1 structure_element = numpy.repeat(numpy.expand_dims(numpy.expand_dims(structure_element, 0), 0), fixed_depth, 0) sel = torch.from_numpy(structure_element).float().to(device) def f(label): """ :param label: batch of instance levels each instance must have unique id :return: labels, masks and object_lists used by halo loss """ back = numpy.zeros((label.shape[0], fixed_depth, label.shape[1], label.shape[2])) object_list = [] for i in range(label.shape[0]): bincount = numpy.bincount(label[i].flatten()) pixels = numpy.where(bincount > min_fragment)[0] if len(pixels) > fixed_depth: pixels = pixels[:fixed_depth] warnings.warn("Not all objects fits in fixed depth", RuntimeWarning) for l, v in enumerate(pixels): back[i, l, label[i] == v] = 1. object_list.append(numpy.array(range(l + 1))) labels = torch.from_numpy(back).float().to(device) masks = F.conv2d(labels, sel, groups=fixed_depth, padding=margin / 2) masks[masks > 0] = 1. #masks += labels masks[:, 0, :, :] = 1. return labels, masks, object_list return f
def cover_circle(self, excel_file): ''' Function removes a specified region of the data. Use to remove the bright suns. ''' sun_data = pd.read_excel(excel_file) counter = 0 while counter != len(sun_data['x-pos']): x_pos = sun_data['x-pos'][counter] y_pos = sun_data['y-pos'][counter] #Imposes a circular apperture over the data to be removed circ = sun_data['circumference'][counter] rr, cc = circle(y_pos, x_pos, circ) self.astro_flux[rr, cc] = 1 counter += 1
def show_landmarks(image, landmarks): print "show landmarks" max_value = np.max(image) print image.shape, np.array(landmarks.shape) for i in range(len(landmarks)): for j in range(len(landmarks[i])): #print landmark a, b = int(landmarks[i][j][0]), int(landmarks[i][j][1]) c, d = int(landmarks[i][(j + 1) % len(landmarks[i])][0]), int( landmarks[i][(j + 1) % len(landmarks[i])][1]) print a, b, c, d rr, cc = circle(a, b, 3) #rr, cc, val = circle_perimeter_aa(a, b, 3) #image[rr, cc] = (1-val) * max_value #rr, cc = line(a, b, c, d) image[rr, cc] = 0 imshow('Image with mask', np.array(image))
def onclick(event): if event.xdata is None or event.ydata is None: return ix, iy = int(round(event.xdata)), int(round(event.ydata)) if ix < 0: ix = 0 if iy < 0: iy = 0 input.append((ix, iy)) rr, cc = circle(iy, ix, 3.5, img_marked.shape[0:2]) img_marked[rr, cc] = (1, 1, 0) implot.set_data(img_marked) fig.canvas.draw()
def test_blob_log_exclude_border(): # image where blob is 5 px from borders, radius 5 img = np.ones((512, 512)) xs, ys = circle(5, 5, 5) img[xs, ys] = 255 blobs = blob_log( img, min_sigma=1.5, max_sigma=5, ) assert blobs.shape[0] == 1 b = blobs[0] assert b[0] == b[1] == 5, "blob should be 5 px from x and y borders" blobs = blob_dog(img, min_sigma=1.5, max_sigma=5, exclude_border=5) msg = "zero blobs should be detected, as only blob is 5 px from border" assert blobs.shape[0] == 0, msg
def get_head_tail(image, radius=12, sigma=4, min_distance=10): """ Make a head tail mask of a worm :param image: binary worm image :param radius: radius used around point :param sigma: harris detector radius :param min_distance: distance between head and tail :return: mask of head and tail """ hc = corner_harris(image, sigma=sigma) cp = corner_peaks(hc, min_distance=min_distance, num_peaks=2) mask = np.zeros_like(image) for c in cp: rr, cc = circle(c[0], c[1], radius, shape=mask.shape) mask[rr, cc] = 1 return image & mask
def _snr_approx(array, source_xy, fwhm, centery, centerx): """ array - frame convolved with top hat kernel """ sourcex, sourcey = source_xy rad = dist(centery, centerx, sourcey, sourcex) ind_aper = draw.circle(sourcey, sourcex, fwhm / 2.) # noise : STDDEV in convolved array of 1px wide annulus (while # masking the flux aperture) * correction of # of resolution elements ind_ann = draw.circle_perimeter(int(centery), int(centerx), int(rad)) array2 = array.copy() array2[ind_aper] = array[ind_ann].mean() # quick-n-dirty mask n2 = (2 * np.pi * rad) / fwhm - 1 noise = array2[ind_ann].std() * np.sqrt(1 + (1 / n2)) # signal : central px minus the mean of the pxs (masked) in 1px annulus signal = array[sourcey, sourcex] - array2[ind_ann].mean() snr = signal / noise return sourcey, sourcex, snr
def labels_image(X, Y, lats, lons, buffer_size): n_scale = 0.15 min_x, max_y = np.min(X), np.max(Y) rows, columns = (1 / n_scale) * (max_y - lats - 0.5 * n_scale), ( 1 / n_scale) * (lons - min_x - 0.5 * n_scale) X = np.array((1 / n_scale) * (X - min_x), dtype=np.int) Y = np.array((1 / n_scale) * (max_y - Y), dtype=np.int) labels = np.full((int(np.max(Y) + 1), int(np.max(X) + 1)), 0, dtype=np.int) for index in range(0, len(rows)): circy, circx = circle(rows[index], columns[index], int(buffer_size / n_scale), shape=labels.shape) labels[circy, circx] = index + 1 return labels, X, Y
def create_circle_center(img_shape, centers, radius=10): """ create initialisation from centres as small circles :param img_shape: :param [[int, int]] centers: :param int radius: :return: """ mask_circle = np.zeros(img_shape, dtype=int) mask_perimeter = np.zeros(img_shape, dtype=int) center_circles = [] for i, pos in enumerate(centers): rr, cc = draw.circle(int(pos[0]), int(pos[1]), radius, shape=img_shape[:2]) mask_circle[rr, cc] = i + 1 rr, cc = draw.circle_perimeter(int(pos[0]), int(pos[1]), radius, shape=img_shape[:2]) mask_perimeter[rr, cc] = i + 1 center_circles.append(np.array([rr, cc]).transpose()) return center_circles, mask_circle, mask_perimeter
def __call__(self, sample): n = np.random.rand() if n < 0.7: return sample img_center = sample['image'].size[0] // 2 r, c = img_center + img_center / 3 * np.random.randn(2) if r < 0 or r > 255 or c < 0 or c > 255: return sample rad = img_center // 8 + img_center // 8 * np.random.rand() [rr, cc] = circle(r, c, rad, shape=sample['image'].size[::-1]) occlusion_mask = 255 * np.ones( shape=sample['image'].size[::-1]).astype(np.uint8) occlusion_mask[rr, cc] = 0 occluded_mask = Image.fromarray(np.zeros_like(occlusion_mask)) occlusion_mask = Image.fromarray(occlusion_mask).convert(mode='L') sample['in_mask'] = Image.composite(sample['in_mask'], occluded_mask, occlusion_mask).convert(mode='L') return sample
def setup_geometry(shape="rectangle", im_shape=(300, 300), shape_size=100): if shape == "rectangle": start = ((im_shape[0] - shape_size) / 2, (im_shape[1] - shape_size) / 2) end = ((im_shape[0] + shape_size) / 2, (im_shape[1] + shape_size) / 2) if any([s < 0 for s in start]) or any( [end[0] > im_shape[0], end[1] > im_shape[1]]): raise Exception("shape is larger the image boundaries") x_coords, y_coords = draw.rectangle(start, end, shape=im_shape) matrix = np.zeros(im_shape, dtype=int) matrix[x_coords.astype(int), y_coords.astype(int)] = 1 if shape == "circle": matrix = np.zeros(im_shape, dtype=int) center = regionprops(matrix + 1)[0].centroid circ = circle(center[0], center[1], shape_size) matrix[circ] = 1 return matrix