def blob_detection(data, min_sigma=1, max_sigma=50, num_sigma=10, threshold=0.2, overlap=0.5): """Finds blobs in the given image. See also http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_log Args: data (ndarray): An image data. min_sigma (float, optional): The minimum standard deviation. Keep this low to detect smaller blobs. Defaults to 1. max_sigma (float, optional): The maximum standard deviation. Keep this high to detect larger blobs. Defaults to 50. num_sigma (int, optional): The number of intermediate values between `min_sigma` and `max_sigma`. Defaults to 10. threshold (float, optional): The absolute lower bound for scale space maxima. Reduce this to detect blobs with less intensities. overlap (float, optional): A value between 0 and 1. Returns: ndarray: Blobs detected. Each row represents coordinates and the standard deviation, `(x, y, r)`. """ try: from skimage.feature import blob_log except ImportError: raise ImportError("No module named 'skimage'. 'spot_detection' requires 'scikit-image'") ## Laplacian of Gaussian blobs = blob_log( data, min_sigma=min_sigma, max_sigma=max_sigma, num_sigma=num_sigma, threshold=threshold, overlap=overlap) blobs[: , 2] = blobs[: , 2] * numpy.sqrt(2) _log.info('{} blob(s) were detected'.format(len(blobs))) return blobs
def circles(self, filename): image = cv2.imread(filename, 0) image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) blobs_list = [blobs_log, blobs_doh] colors = ['yellow', 'red'] titles = ['Laplacian of Gaussian', 'Determinant of Hessian'] sequence = zip(blobs_list, colors, titles) fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) axes = axes.ravel() for blobs, color, title in sequence: ax = axes[0] axes = axes[1:] ax.set_title(title) ax.imshow(image, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False) ax.add_patch(c) plt.savefig('output.png') plt.show()
def psf_finder(stack, dominant_z, px = 100, wl = 700, patch_size = 48): ''' find psfs and their centers from a stack. patch_size: the size of each psf small stack. ''' hps = int(patch_size //2) NY, NX = stack[0].shape dominant_slice = stack[dominant_z] min_sig = 0.61*wl/px #theoretical diffraction-limited psf size at focus max_sig = 1.5* min_sig # this is kinda random blobs = blob_log(dominant_slice, min_sigma = min_sig, max_sigma = max_sig, threshold = 40 ) centers = blobs[:,:2] # blob_centers lower_rest = np.logical_and(centers[:,0] > hps, centers[:,1] > hps) upper_rest = np.logical_and(centers[:,0] < NY - hps, centers[:,1] < NX-hps) total_rest = np.logical_and(lower_rest, upper_rest) centers = centers[total_rest] ind_accept = psf_isolation(centers, 30) centers = centers[ind_accept] print(centers) psf_collection = [] for cc in centers: psf_patch = stack[:, cc[0]-hps:cc[0]+hps, cc[1]-hps:cc[1]+hps] psf_collection.append(psf_patch) return psf_collection, centers
def label_colonies(gray, min_foci_radius = 50, max_foci_radius = 200, \ overlap=0, log_thres = 0.04, scale = 4): '''Label colonies on the image''' binary = (1 - binarize(gray))*255. min_sigma = ((min_foci_radius/3.)*2)/scale max_sigma = ((max_foci_radius/3.)*2)/scale # num_sigma = np.floor(max_sigma - min_sigma).astype(int)/10 + 1 num_sigma = 10 if scale != 1: new_shape = np.floor(np.array(gray.shape)/np.float(scale)).astype(np.int) # print new_shape, min_sigma, max_sigma small_im = imresize(binary, new_shape) else: small_im = binary blobs_log = blob_log(small_im, min_sigma=min_sigma, max_sigma=max_sigma,\ num_sigma=num_sigma, threshold=log_thres, overlap = overlap/100.) markers_num = blobs_log.shape[0] blobs_log = np.floor(blobs_log*np.float(scale)).astype(np.int) markers_fin = circle_markers(blobs_log, gray.shape) circles = np.copy(gray) circles[markers_fin] = 255 return [markers_num, circles, blobs_log]
def detect_cells(image): image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) blobs_list = [blobs_log, blobs_dog, blobs_doh] colors = ['yellow', 'lime', 'red'] titles = ['Laplacian of Gaussian', 'Difference of Gaussian', 'Determinant of Hessian'] sequence = zip(blobs_list, colors, titles) for blobs, color, title in sequence: fig, ax = plt.subplots(1, 1) ax.set_title(title) ax.imshow(image, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False) ax.add_patch(c) plt.show()
def view_U_matrix(self,distance2=4,row_normalized='Yes',show_data='Yes',contooor='Yes',blob = 'Yes',save='Yes',save_dir = ''): import scipy from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show umat = self.U_matrix(distance=distance2,row_normalized=row_normalized) data = getattr(self, 'data_raw') proj = self.project_data(data) msz = getattr(self, 'mapsize') coord = self.ind_to_xy(proj) # freq = plt.hist2d(coord[:,1], coord[:,0], bins=(msz[1],msz[0]),alpha=1.0,cmap=cm.jet)[0] # plt.close() # fig, ax = plt.figure() fig, ax= plt.subplots(1, 1) im = imshow(umat,cmap=cm.RdYlBu_r,alpha=1) # drawing the function # adding the Contour lines with labels` # imshow(freq[0].T,cmap=cm.jet_r,alpha=1) if contooor=='Yes': mn = np.min(umat.flatten()) mx = np.max(umat.flatten()) std = np.std(umat.flatten()) md = np.median(umat.flatten()) mx = md + 0*std # mn = md # umat[umat<=mn]=mn cset = contour(umat,np.linspace(mn,mx,15),linewidths=0.7,cmap=cm.Blues) if show_data=='Yes': plt.scatter(coord[:,1], coord[:,0], s=2, alpha=1.,c='Gray',marker='o',cmap='jet',linewidths=3, edgecolor = 'Gray') plt.axis('off') ratio = float(msz[0])/(msz[0]+msz[1]) fig.set_size_inches((1-ratio)*15,ratio*15) plt.tight_layout() plt.subplots_adjust(hspace = .00,wspace=.000) sel_points = list() if blob=='Yes': from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray image = 1/umat image_gray = rgb2gray(image) #'Laplacian of Gaussian' blobs = blob_log(image, max_sigma=5, num_sigma=4, threshold=.152) blobs[:, 2] = blobs[:, 2] * sqrt(2) imshow(umat,cmap=cm.RdYlBu_r,alpha=1) sel_points = list() for blob in blobs: row, col, r = blob c = plt.Circle((col, row), r, color='red', linewidth=2, fill=False) ax.add_patch(c) dist = scipy.spatial.distance_matrix(coord[:,:2],np.array([row,col])[np.newaxis,:]) sel_point = dist <= r plt.plot(coord[:,1][sel_point[:,0]], coord[:,0][sel_point[:,0]],'.r') sel_points.append(sel_point[:,0]) if save=='Yes': fig.savefig(save_dir, transparent=False, dpi=400) return sel_points,umat
def log(self): """Laplacian of Gaussian.""" # skimage.feature.blob_log(image, min_sigma=1, max_sigma=50, # num_sigma=10, threshold=0.2, overlap=0.5, log_scale=False) blobs = feature.blob_log(self.image, **self.blob_ka, **self.log_ka) blobs[:, 2] = blobs[:, 2] * sqrt(2) # Compute radii in 3rd column. return blobs
def get_number_of_blobs(image): from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1) return blobs_log.size
def get_blobs(self, image, **kwargs): ''' Use Laplacian of Gaussian to find blobs in passed grayscale image. ''' blobs = blob_log(image, **kwargs) # Compute radii in the 3rd column. blobs[:, 2] = blobs[:, 2] * sqrt(2) return blobs
def blob_image_multiscale2(image, type=0,scale=2): # function that return a list of blob_coordinates, 0 = dog, 1 = doh, 2 = log list = [] image = norm.normalize(image) for z, slice in tqdm(enumerate(image)): # init list of different sigma/zoom blobs featureblobs = [] # x = 0,1,2,3,4 if scale == 2: # for x in xrange(0,6): # if type == 0: # featureblobs.append(feature.blob_dog(slice, 2**x, 2**x)) # if type == 1: # featureblobs.append(feature.blob_doh(slice, 2**x, 2**x)) # if type == 2: # featureblobs.append(feature.blob_log(slice, 2**x, 2**x)) for x in xrange(0,5): if type == 0: featureblobs.append(feature.blob_dog(slice, 2**x, 2**(x+1))) if type == 1: featureblobs.append(feature.blob_doh(slice, 2**x, 2**(x+1))) if type == 2: featureblobs.append(feature.blob_log(slice, 2**x, 2**(x+1),16,.1)) else: for x in xrange(0,4): if type == 0: featureblobs.append(feature.blob_dog(slice, 3**x, 3**x)) if type == 1: featureblobs.append(feature.blob_doh(slice, 3**x, 3**x)) if type == 2: featureblobs.append(feature.blob_log(slice, 3**x, 3**x)) # init list of blob coords blob_coords = [] #print featureblobs # start at biggest blob size for featureblob in reversed(featureblobs): # for every blob found of a blobsize for blob in enumerate(featureblob): # if that blob is not within range of another blob, add it blob = blob[1] if not within_range(blob, blob_coords): blob_coords.append([z, blob[0], blob[1], blob[2]]) list.append(blob_coords) return list
def _detect_spots_blob_log(image, minSpotSize): maxSpotSize = minSpotSize spotSizeSteps = 1 # find blobs starting from min_sigma to max_sigma in num_sigma steps blobs = blob_log(image, min_sigma=minSpotSize, max_sigma=maxSpotSize, num_sigma=spotSizeSteps, threshold=.005) # blobs_log = (y, x, r) return blobs
def show(self, som, distance2=1, row_normalized=False, show_data=True, contooor=True, blob=False, labels = False): umat = self.build_u_matrix(som, distance=distance2, row_normalized=row_normalized) msz = som.codebook.mapsize proj = som.project_data(som.data_raw) coord = som.bmu_ind_to_xy(proj) fig, ax = plt.subplots(1, 1) im = imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) if contooor: mn = np.min(umat.flatten()) mx = np.max(umat.flatten()) std = np.std(umat.flatten()) md = np.median(umat.flatten()) mx = md + 0*std cset = contour(umat, np.linspace(mn, mx, 15), linewidths=0.7, cmap=plt.cm.get_cmap('Blues')) if show_data: plt.scatter(coord[:, 1], coord[:, 0], s=2, alpha=1., c='Gray', marker='o', cmap='jet', linewidths=3, edgecolor='Gray') plt.axis('off') if labels: if labels == True: labels = som.build_data_labels() for label, x, y in zip(labels, coord[:, 1], coord[:, 0]): plt.annotate(str(label), xy = (x, y), horizontalalignment = 'center', verticalalignment = 'center') ratio = float(msz[0])/(msz[0]+msz[1]) fig.set_size_inches((1-ratio)*15, ratio*15) plt.tight_layout() plt.subplots_adjust(hspace=.00, wspace=.000) sel_points = list() if blob: from skimage.color import rgb2gray from skimage.feature import blob_log image = 1/umat image_gray = rgb2gray(image) #'Laplacian of Gaussian' blobs = blob_log(image, max_sigma=5, num_sigma=4, threshold=.152) blobs[:, 2] = blobs[:, 2] * sqrt(2) imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) sel_points = list() for blob in blobs: row, col, r = blob c = plt.Circle((col, row), r, color='red', linewidth=2, fill=False) ax.add_patch(c) dist = scipy.spatial.distance_matrix(coord[:, :2], np.array([row, col])[np.newaxis, :]) sel_point = dist <= r plt.plot(coord[:, 1][sel_point[:, 0]], coord[:, 0][sel_point[:, 0]], '.r') sel_points.append(sel_point[:, 0]) plt.show() return sel_points, umat
def get_blobs(self, image): blobs_log = blob_log(image, max_sigma=30, num_sigma=10, threshold=.1) blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image, max_sigma=30, threshold=.1) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(image, max_sigma=30, threshold=.01) all_blobs = np.vstack([blobs_log, blobs_doh, blobs_dog]) all_blobs = filter(lambda b: b[2] > 4, all_blobs) all_blobs = list(filter(lambda b: b[2] < 60, all_blobs)) return all_blobs
def skimage_blob(frame): # gray_frm = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) detected_dogs = feature.blob_log(frame) for blob in detected_dogs: sigma = blob[-1] blob_rad = (2 ** 1 / 2) * sigma cv2.circle(frame, (blob[1], blob[0]), blob_rad, (255, 0, 0)) return frame
def predict_test(self, test_folder, destination_folder): test_image_file = self.get_image_names(test_folder) for i, im in enumerate(test_image_file): print 'Processing Test Image:', i file_name = os.path.join(test_folder, im) image = imread(file_name) im_final = self.apply_gaussian_filter(image) image_gray = rgb2gray(im_final) blobs = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.55) blob_list = self.process_blobs(image, blobs) self.create_mask(image, im, blob_list, destination_folder)
def temblob(image,ind): """ Laplacian of gaussian blob detection for TEM images """ org = image[4:-256,4:-4] with warnings.catch_warnings(): warnings.simplefilter("ignore") warnings.warn("user", UserWarning) igray = img_as_ubyte(rgb2gray(org)) iinv = np.invert(igray) igaus = img_as_float(iinv) igaus = gaussian_filter(igaus, 1) h = 0.5 sd = igaus - h msk = igaus dilat = reconstruction(sd, msk, method='dilation') hdome = igaus - dilat if ind == 'AgNP': kwargs = {} kwargs['threshold'] = 0.01 kwargs['overlap'] = 0.4 kwargs['min_sigma'] = 25 kwargs['max_sigma'] = 50 kwargs['num_sigma'] = 25 calib = 500/(969-26) elif ind == 'AuNP': kwargs = {} kwargs['threshold'] = 0.01 kwargs['overlap'] = 0.4 kwargs['min_sigma'] = 18 kwargs['max_sigma'] = 23 kwargs['num_sigma'] = 5 calib = 200/(777-23) else: warnmsg='Unable to identify keyword: {:}'.format(ind) warnings.warn(warnmsg, UserWarning) blobs = blob_log(hdome, **kwargs) diam = 2*sqrt(2)*blobs[:,-1] npdiam = [ind] npdiam.extend(calib*diam) return(npdiam)
def image_blobs(self, n_frame): """ input: number of frame """ im0 = self.stack[n_frame] mx_sig = self.blobset[0] mi_sig = self.blobset[1] nsig = self.blobset[2] # th = (np.max(im0)-np.min(im0))/10. # threshold th = (np.mean(im0)-np.min(im0))/12. print("threshold:", th) self.c_list[n_frame] = blob_log(im0, max_sigma = mx_sig, min_sigma = mi_sig, num_sigma=nsig, threshold = th, overlap = OL_blob) self.bl_flag[n_frame] = self.c_list[n_frame].shape[0]
def blob_feature(image, method='log'): if method == 'log': blobs = blob_log(image, ) else: blobs = blob_doh(image, ) blob_image = np.zeros(image.shape) #Draw the blobs to an image for blob in blobs: y,x,sigma = blob color = sigma size = int(np.sqrt(2*sigma)) if method == 'log' else sigma cv2.circle(blob_image, (x, y), size, sigma/1,-1) #dataset.show_image(blob_image) return blob_image
def run(min_s, max_s, sigma): # Run Blob Detection by Laplacian of Gaussian (LoG) blobs_log = blob_log(image, max_s, threshold=.01) # Compute radii in the 3rd column blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) # Configure the graph fig, ax = pyplot.subplots(1, 1) ax.set_title("Laplacian of Gaussian, min_s=" + str(min_s) + ", max_s=" + str(max_s) + ", sigma=" + str(sigma)) ax.imshow(image, vmin=0, vmax=255, cmap=pyplot.cm.gray) # Load graph for blob in blobs_log: y, x, r = blob c = pyplot.Circle((x, y), r, color='yellow', linewidth=2, fill=False) ax.add_patch(c)
def Blobing(image, min_sigma, max_sigma, threshold): #image = mpimg.imread('stepping.png')[0:500, 0:500] image_gray = rgb2gray(image) image_fltrd = canny(image_gray, sigma=1.0, low_threshold=None, high_threshold=None, mask=None) blobs_log = blob_log(image_fltrd, min_sigma=min_sigma, # set to10 max_sigma=max_sigma, # set to 40 num_sigma=10, threshold=threshold) #----------------------------------------------------- #----- Calculating the average of all blobs # This will issue the location of each step lngth = len(blobs_log[0:]) x_avg = sum(blobs_log[:,0])/lngth y_avg = sum(blobs_log[:,1])/lngth #print 'Step coordinates: (x,y):''(',x_avg,',', y_avg,')' # Compute belowradii in the 3rd column, this is just the radial of each circle blobs_log[:, 2] = blobs_log[:, 2]*sqrt(2) #----------------------------------------------------- #----- Ploting fig, ax = plt.subplots(1, 1) ax.imshow(image, interpolation='gaussian') #time.sleep(0.5) plt.close(fig) # save time by closing figure for circles in blobs_log: y, x, r = circles c = plt.Circle((x, y), r, color='blue', linewidth=2, fill=False) ax.add_patch(c) #print x, y plt.show() #time.sleep(0.5) plt.close(fig) # close figure return x_avg, y_avg # The Blobing returns the coordinates to be used for move command isuers
def test_blob_log(): r2 = math.sqrt(2) img = np.ones((512, 512)) xs, ys = circle(400, 130, 5) img[xs, ys] = 255 xs, ys = circle(160, 50, 15) img[xs, ys] = 255 xs, ys = circle(100, 300, 25) img[xs, ys] = 255 xs, ys = circle(200, 350, 30) img[xs, ys] = 255 blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1) radius = lambda x: r2*x[2] s = sorted(blobs, key=radius) thresh = 3 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] - 160) <= thresh assert abs(b[1] - 50) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 300) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 350) <= thresh assert abs(radius(b) - 30) <= thresh
def detect_blobs(self, min_sigma, max_sigma, num_sigma, threshold): blobs = [] image_gray = rgb2gray(self.original_image) r, c = np.shape(image_gray) image_gray = image_gray[5:r-5,5:c-5] image_gray[1,1] = 1 if self.method == 'log': blobs = blob_log(image_gray, min_sigma=min_sigma, max_sigma=max_sigma, num_sigma=num_sigma, threshold=threshold) a = len(blobs[:]) if a != 0: blobs[:, 2] = blobs[:, 2] * sqrt(2) elif self.method == 'dog': blobs = blobs_dog = blob_dog(image_gray, max_sigma=max_sigma, threshold=threshold) a = len(blobs[:]) if a != 0: blobs[:, 2] = blobs[:, 2] * sqrt(2) else: blobs = blob_doh(image_gray, max_sigma=max_sigma, threshold=threshold) return blobs
def DoOneBlobLog1232Pilates(LogNormImage, Threshold=0.07): ''' In the future we may support multiple detectors and beamlines. In such case, we will want to do the peak finding in a fashion that suits each detector. This is the routine for ALS Beamline 12.3.2, Pilatus detector.''' # Locate all the diffraction peaks. blobs = blob_log(LogNormImage, threshold=Threshold, max_sigma=3) # The Pilatus detector on 12.3.2 has a 4 vertical and one horizontal stripe down the middle which are the locations that the detector segments join. # The blob function finds the corners of the detector segments which is incorrect. So we'll exclude any peaks within a certain x or y distance of the corners. peaks = [] for b in blobs: # exclude anything within 15 pixels of the horizontal line down the middle. if abs(b[0] - 490) < 15: continue # exclude anything within 25 pixels of any of the 4 fat vertical lines. d = abs(b[1] % (1043 / 5)) if (d > ((1043 / 5) - 25)) or (d < 25): continue # It's a good peak, save it. peaks.append(b) return peaks
def autemblob(image): """ Laplacian of gaussian blob detection for TEM images """ org = image[4:-256,4:-4] with warnings.catch_warnings(): warnings.simplefilter("ignore") warnings.warn("user", UserWarning) igray = img_as_ubyte(rgb2gray(org)) iinv = np.invert(igray) igaus = img_as_float(iinv) igaus = gaussian_filter(igaus, 1) h = 0.5 sd = igaus - h msk = igaus dilat = reconstruction(sd, msk, method='dilation') hdome = igaus - dilat kwargs = {} kwargs['threshold'] = 0.01 kwargs['overlap'] = 0.4 kwargs['min_sigma'] = 18 kwargs['max_sigma'] = 30 kwargs['num_sigma'] = 12 calib = 200/(777-23) blobs = blob_log(hdome, **kwargs) diam = 2*sqrt(2)*blobs[:,-1] npdiam = calib*diam return(npdiam)
def frame_blobs(filled_frame, bsize = 9, btolerance = 3, bsteps =7, verbose = True, edge_ratio = 0., thresh = 5.0): ''' extract blobs from a single frame. Added on 06/10/2017 cblob: a 3-column array, (y, x, sigma), the blob radius is sqrt(2)*sigma ''' # now, let's calculate threshold NY, NX = filled_frame.shape #th = (np.mean(filled_frame) - np.std(filled_frame))/7. # This is not quite reliable th = thresh mx_sig = bsize + btolerance mi_sig = bsize - btolerance cblobs = blob_log(filled_frame,max_sigma = mx_sig, min_sigma = mi_sig, num_sigma=bsteps, threshold = th, overlap = OL_blob) # clean blobs that is at the edge by, bx = cblobs[:,0], cblobs[:,1] valid_indY = np.logical_and(by > edge_ratio*bsize, by< (NY-edge_ratio*bsize)) valid_indX = np.logical_and(bx > edge_ratio*bsize, bx< (NX-edge_ratio*bsize)) valid_ind = np.logical_and(valid_indY, valid_indX) cblobs = cblobs[valid_ind] # remove those edge blobs --- added by Dan on 08/11/2018. if verbose: #print("threshold:", th) print("# of blobs:", cblobs.shape[0]) return cblobs
def test_blob_overlap(): img = np.ones((256, 256), 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 r1, r2 = 7, 6 pad1, pad2 = 11, 12 blob1 = ellipsoid(r1, r1, r1) blob1 = util.pad(blob1, pad1, mode='constant') blob2 = ellipsoid(r2, r2, r2) blob2 = util.pad(blob2, [(pad2, pad2), (pad2 - 9, pad2 + 9), (pad2, pad2)], mode='constant') im3 = np.logical_or(blob1, blob2) blobs = blob_log(im3, min_sigma=2, max_sigma=10, overlap=0.1) assert len(blobs) == 1 # Two circles with distance between centers equal to radius overlap = _blob_overlap(np.array([0, 0, 10 / math.sqrt(2)]), np.array([0, 10, 10 / math.sqrt(2)])) assert_almost_equal(overlap, 1./math.pi * (2 * math.acos(1./2) - math.sqrt(3)/2.))
def foci_log(foci_pic, nucleus, foci_det_sens = 70, foci_fill_perc = 30,\ min_foci_radius = 3, max_foci_radius = 12, overlap=100,\ return_circles = True): '''Find foci using Laplacian of Gaussian''' min_sigma = (min_foci_radius/3.)*2 max_sigma = (max_foci_radius/3.)*2 num_sigma = max_sigma - min_sigma + 1 log_thres = (100 - foci_det_sens)/200. if foci_det_sens == 0.: log_thres = 1. blobs_log = blob_log(foci_pic, min_sigma=min_sigma, max_sigma=max_sigma,\ num_sigma=num_sigma, threshold=log_thres, overlap = overlap/100.) markers_num = blobs_log.shape[0] if return_circles: markers_fin = circle_markers(blobs_log, foci_pic.shape) else: markers_fin = foci_markers(blobs_log, foci_pic.shape) foci_bin = get_foci_bin(blobs_log, foci_pic, nucleus, 3, foci_fill_perc) foci_area = np.sum(foci_bin) foci_soid = np.sum(foci_bin*foci_pic) if foci_area != 0: foci_intensity = foci_soid/(1.*foci_area) else: foci_intensity = 0. return [markers_num,foci_soid,foci_area,markers_fin, foci_bin,\ foci_intensity]
# specified sigma. #remove the noise gfp = denoise_wavelet(gfp, sigma=1.2 * sigma_est) #Histgram Equalization #gfp = exposure.equalize_adapthist(gfp, clip_limit=0.03) #Contrast Stretching (image rescale) p1, p2 = np.percentile(gfp, (50, 98)) gfp = exposure.rescale_intensity(gfp, in_range=(p1, p2)) print 'done' #%% DETECT BRIGHT SPOTS print 'detecting blobs...', blobs = blob_log( gfp, min_sigma=1, max_sigma=10) # have to be adjusted accroding to the enhancement y, x, sigma = blobs.T #sigma provides the size of the blob in units of standard deviation valid = mask[y.astype(int), x.astype(int)] #blobs that are not in blurred region are valid print 'done' #%% DEFINE CELLS bsigma = sigma < 4 ncells = len(sigma[bsigma & valid]) density = ncells / area print 'cell density [#/m-2] = ', density #%% CALCULATE DISTANCE TO k-NEAREST NEIGHBOR print 'calculate distances to neighbors...', #FIXME: This just calculates distances, including distances across blurred regions
def create_blobs(url, opt='all'): image = imread(url) return_dict = dict() print 'Image read: {}'.format(url) image_gray = rgb2gray(image) print 'Greyscale applied' if opt=='all': blobs_log = blob_log(image_gray, min_sigma=15, max_sigma=50, num_sigma=10, threshold=.1, overlap=0.8) print 'Laplacian of Gaussian computed' # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) return_dict['LoG'] = blobs_log blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1) print 'Difference of Gaussian computed' blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) return_dict['DoG'] = blobs_dog blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) print 'Determinant of Hessian computed' return_dict['DoH'] = blobs_doh blobs_list = [blobs_log, blobs_dog, blobs_doh] colors = ['yellow', 'lime', 'red'] titles = ['LoG', 'DoG', 'DoH'] sequence = zip(blobs_list, colors, titles) print 'Sequence created' elif opt=='doh': print 'DoH only' blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) return_dict['DoH'] = blobs_doh sequence = zip([blobs_doh], ['red'], ['DoH']) elif opt=='log': print 'LoG only' blobs_log = blob_log(image_gray, min_sigma=15, max_sigma=50, num_sigma=10, threshold=.1, overlap=0.8) print 'Laplacian of Gaussian computed' # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) return_dict['LoG'] = blobs_log sequence = zip([blobs_log], ['yellow'], ['LoG']) print sequence fig,axes = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'}) axes = axes.ravel() print 'Matplot initialized' print sequence for blobs, color, title in sequence: ax = axes[0] axes = axes[1:] ax.set_title(title) ax.imshow(image, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False) ax.add_patch(c) plt.show() return return_dict
def whiteFilter(image, radius): selem = disk(radius) image = white_tophat(image,selem) return image def detectSpotsLoG(image, min_sigma=1, max_sigma=10, num_sigma=10, threshold=0.2, overlap=0.5): image = image.astype('uint8') blobs = blob_log(image, min_sigma, max_sigma, num_sigma, threshold, overlap) return blobs filtered_image = whiteFilter(image, tophat_filter_radius) blobs = blob_log(image, min_sigma=min_sigma, max_sigma= max_sigma, num_sigma=num_sigma, threshold=threshold, overlap=overlap) initial_number = len(blobs) # QC based on sigma's average_sigma = np.mean(blobs[:,2]) stdev_sigma = np.std(blobs[:,2]) upper_bound =math.ceil(average_sigma +(2*stdev_sigma)) lower_bound =math.floor(average_sigma -(2*stdev_sigma)) mask = np.where(np.logical_or(blobs[:,2] > upper_bound, blobs[:,2] < lower_bound), False, True) blobs = blobs[mask] after_filtering = len(blobs) print(f"Number of blobs found: {len(blobs)}, {initial_number - after_filtering} blobs were left out due to sigma filtering")
queueSize = queue.size() print("- Dequeuing from queue, %i element(s) left" % queueSize) try: pix = io.imread(imagename)[0:1280][0:1280] print("- Image found and read") # grab the image (must be same folder) into the .py image = np.array(pix, dtype=np.uint8) # make the image into an array image_gray = rgb2gray(image) print("- Image grayscaled") # grayscale the image # was min_sigma=0.25, overlap=0.5, threshold=1.56 print("- Processing using LOG") blobs_log = blob_log(image_gray, min_sigma=0.25, overlap=0.5, threshold=1) print("- Array from LOG processed") # this is the magical algo that return an array of y, x, sigma to blobs_log # array is in y, x, radius print("- Element in array LOG:" + str(len(blobs_log))) ''' # This is for debug, it'll draw a red circle for i in range(len(blobs_log)): plt.scatter(blobs_log[i][1], blobs_log[i][0], c='r', s=1) # this draw red dots on the image for us to check plt.imshow(pix) # add image to plot so the graph is not just red dots plt.show()
def find_blobs(image, min_sigma=3, max_sigma=6, num_sigma=3, threshold=0.9, radial_thresh=0.5, overlap=0.5, Plot=False): """ Detects blobs in an image file using blob_log, then filters according to height and circularity via a guassian fit. Hyper paramters: min,max sigma: bounds on blob_log threshold The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect blobs with less intensities overlap A value between 0 and 1. If the area of two blobs overlaps by a fraction greater than threshold, the smaller blob is eliminated.A value between 0 and 1. If the area of two blobs overlaps by a fraction greater than threshold, the smaller blob is eliminated. Plot: Plots the remaining blobs for a visual inspection. """ if isinstance(image, str): image = np.load(image) windowsize = 7 print("looking for blobs") blobs = feature.blob_log(image, min_sigma=min_sigma, max_sigma=max_sigma, num_sigma=num_sigma, threshold=threshold, overlap=0.5) print(len(blobs), "blobs found") atoms = [] meshx, meshy = np.meshgrid(np.arange(windowsize * 2), np.arange(windowsize * 2)) #print(meshx) #print(meshy) R = np.sqrt((meshx - windowsize)**2 + (meshy - windowsize)**2) for blob in blobs: y, x, r = blob if image[int(y), int(x)] > 100: #filter weak blobs blobimage = image[int(y) - windowsize:int(y) + windowsize, int(x) - windowsize:int(x) + windowsize] if blobimage.shape == (windowsize * 2, windowsize * 2): #filter blobs on edge of image #try: #mostlikely a value error on fit2D try: # R = np.sqrt((meshx-x)**2+(meshy-y)**2) radial = blobimage[(R >= 4 - 0.5) & (R >= 4 + 0.5)] std = radial.std() diff = (np.max(blobimage) - radial.max()) / np.max(blobimage) #print(std,diff) #print(x,y) #print(fit[1],fit[2]) if diff > radial_thresh: #Filter oblong blobs TODO this seems very image dependant... atoms.append((x, y)) # fit, err = imu.fit2D(blobimage,imu.gaussian2D) # if abs(fit[3]<windowsize*0.7): # print("blob plotting") # c = plt.Circle((x,y),fit[3],color = "red",linewidth = "2", fill = False) # axes.add_patch(c) #print(x,y) #print(fit[1],fit[2]) # atoms.append((x-(windowsize-fit[1]),y-(windowsize-fit[2]))) #print(x,y) except: #print('Fail on blob fitting') pass atoms = np.array(atoms) if Plot: fig, axes = plt.subplots(1, 1) axes.imshow(image) axes.scatter(atoms[:, 0], atoms[:, 1], s=2, color='red') return atoms
def test_no_blob(): im = np.zeros((10, 10)) blobs = blob_log(im, min_sigma=2, max_sigma=5, num_sigma=4) assert len(blobs) == 0
# for u in range(0, 49): # for v in range(0, 38): # for u in range(0, 49): # for v in range(0, 38): u = 13 v = 11 print("detecting blobs in: u{}-v{}".format(u, v)) image = imread( "/Users/elliott/projects/rti-panoramic-webapp/raphael-2018/mipmap-normals_jpeg/mipmap-00-u{}-v{}.jpg" .format("{:02d}".format(u), "{:02d}".format(v))) # image = data.hubble_deep_field()[0:500, 0:500] image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, min_sigma=1, max_sigma=5, num_sigma=5, threshold=0.060) blobs_log_curr_u_v = np.zeros([1, 2]) blobs_log_curr_u_v[0][0] = u blobs_log_curr_u_v[0][1] = v blobs_log_curr_u_v = np.tile(blobs_log_curr_u_v, [blobs_log.shape[0], 1]) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_log = np.concatenate((blobs_log, blobs_log_curr_u_v), axis=1) # blobs = np.concatenate((blobs, blobs_log), axis=0) blobs = np.vstack([blobs, blobs_log]) if blobs.size else blobs_log
from matplotlib import pyplot as plt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray import glob from skimage.io import imread #Convert to grey_scale example_file = glob.glob(r"C:\Users\Kavin\Downloads\crowd.jpg")[0] im = imread(example_file, as_grey=True) plt.imshow(im, cmap='gray') plt.show() #blobs identification blobs_log = blob_log(im, max_sigma=30, num_sigma=100, threshold=.3) blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) numpeople = len(blobs_log) print("number of people: ", numpeople) #shows the detected blobs fig, ax = plt.subplots(1, 1) plt.imshow(im, cmap='gray') for blob in blobs_log: y, x, r = blob c = plt.Circle((x, y), r + 5, color='lime', linewidth=2, fill=True) ax.add_patch(c)
def findCellPositionsBlob(img, maxRadius=3, sizeIters=30, threshold=1.5, overlap=0, minIntensity=20): blobs = blob_log(normalize(img), max_sigma=maxRadius*0.70710678118, # sigma = radius/sqrt(2) num_sigma=sizeIters, threshold=threshold/np.max(img), overlap=overlap) blobs = np.asarray([(y, x, r) for x, y, r in blobs if (img[int(x), int(y)] > minIntensity)]) return blobs[:,(0,1)], blobs[:,2]
def _fit(self, min_sigma, max_sigma, num_sigma, threshold): fitted_blobs = blob_log(self.blobs, min_sigma, max_sigma, num_sigma, threshold) fitted_blobs[:, 2] = fitted_blobs[:, 2] * np.sqrt(2) self.num_objs = fitted_blobs.shape[0] return fitted_blobs
def test_blob_log(): 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(160, 50, 15) img[xs, ys] = 255 xs, ys = circle(100, 300, 25) img[xs, ys] = 255 xs, ys = circle(200, 350, 30) img[xs, ys] = 255 blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1) radius = lambda x: r2 * x[2] s = sorted(blobs, key=radius) thresh = 3 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] - 160) <= thresh assert abs(b[1] - 50) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 300) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 350) <= thresh assert abs(radius(b) - 30) <= thresh # Testing log scale blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1, log_scale=True) 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] - 160) <= thresh assert abs(b[1] - 50) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 300) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 350) <= thresh assert abs(radius(b) - 30) <= thresh assert_raises(ValueError, blob_log, img3)
def main(argv): #excel summary book = openpyxl.load_workbook("/home/toya/Research/Wasan/data/summary/evaluate.xlsx") sheet = book['パラメータ評価'] sheet.cell(row=int(argv[5]), column=1).value = str(argv[1]) #parameter set min_sList=[i for i in range(38, 43)]*12 #int min_sList2=[i for i in range(35, 45)]*6 #int min_sList3=[i for i in range(50, 65)]*4 #int max_sList=[i for i in range(35, 65)]*2 #int max_sList2=[i for i in range(40, 50)]*6 #int max_sList3=[i for i in range(55, 70)]*4 #int num_sList=[i for i in range(1, 4)]*20 #int num_sList3=[i for i in range(1, 6)]*12 #int sigma_List=[i*0.1 for i in range(15, 66, 10)]*12 #float thresList=[i*0.01 for i in range(1, 21)]*3 #float thresList2=[i*0.1 for i in range(6, 16)]*6 #float thresList3=[i*0.001 for i in range(5, 15)]*6 #float overList=[i*0.1 for i in range(1, 11)]*6 #float overList2=[i*0.1 for i in range(1, 5)]*15 #float overList3=[i*0.1 for i in range(3, 8)]*12 #float #parameters: #argv[1]:COfile #argv[2]:method #argv[3]:KPfile #argv[4]:KPfileAN #argv[5]:pageCount for p in range(30): image_gray=cv2.imread(argv[1], cv2.IMREAD_GRAYSCALE) image=image_gray image_black=(255-image_gray) maskOutputFile = str(argv[3])+"_"+str(min_sList[p])+"-"+str(max_sList[p])+"-"+str(num_sList[p])+"-"+str(thresList[p])+"-"+str(overList[p])+".tif" #switch between the different types of blob detector if int(argv[2])==0: keypoints=SimpleBlobDetector(argv,image) #print ("number of keypoints outside "+str(len(keypoints))) elif int(argv[2])==1: #parameters: http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_log min_s=min_sList[p] max_s=max_sList[p] num_s=num_sList[p] thres=thresList[p] over=overList[p] print(min_s, max_s, num_s, thres, over) blob_List = blob_log(image_black, min_sigma=min_s, max_sigma=max_s, num_sigma=num_s, threshold=thres, overlap=over) # Compute radii in the 3rd column. blob_List[:, 2] = blob_List[:, 2] * sqrt(2) elif int(argv[2])==2: #parameters: http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_dog min_s=min_sList2[p] max_s=max_sList2[p] sigma=sigma_List[p] thres=thresList2[p] over=overList2[p] print(min_s, max_s, sigma, thres, over) blob_List = blob_dog(image_black, min_sigma=min_s, max_sigma=max_s, sigma_ratio=sigma, threshold=thres, overlap=over) #blob_List = blob_dog(image_black, min_sigma=35, max_sigma=40, sigma_ratio=1.5, threshold=1.0, overlap=0.3) blob_List[:, 2] = blob_List[:, 2] * sqrt(2) elif int(argv[2])==3: #parameters: http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_doh min_s=min_sList3[p] max_s=max_sList3[p] num_s=num_sList3[p] thres=thresList3[p] over=overList3[p] print(min_s, max_s, num_s, thres, over) blob_List = blob_doh(image_gray, min_sigma=min_s, max_sigma=max_s, num_sigma=5, threshold=thres, overlap=over) #blob_List = blob_doh(image_gray, min_sigma=65, max_sigma=70, num_sigma=5, threshold=0.005, overlap=0.7) else: print("Blob detector type not supported: "+argv[3]) sys.exit(-1) #Now write the results to file if int(argv[2])==1 or int(argv[2])==2 or int(argv[2])==3: for blob in blob_List: y, x, r = blob cv2.rectangle(image,(int(x-r), int(y-r)), (int(x+r), int(y+r)), (0, 0, 255), 1) outputMask=np.ones((image.shape[0],image.shape[1]),np.uint8) i=0 for blob in blob_List: y, x, r = blob outputMask[int(y-r):int(y+r),int(x-r):int(x+r)]=255 i=i+1 invertOutputMask=255-outputMask cv2.imwrite("/home/toya/Research/Wasan/data/summary/AllKanjiPositionTest/"+str(maskOutputFile.split("/")[-1]),invertOutputMask) else: for kp in keypoints: x = kp.pt[0] y = kp.pt[1] r = kp.size cv2.rectangle(image,(int(x-r), int(y-r)), (int(x+r), int(y+r)), (0, 0, 255), 1) cv2.imwrite(argv[2],image) ############################################################################################################################################################## warnings.simplefilter('ignore', Image.DecompressionBombWarning) im1 = Image.open("/home/toya/Research/Wasan/data/summary/AllKanjiPositionTest/"+str(maskOutputFile.split("/")[-1])) im2 = Image.open(argv[4]) # Error control if only one parameter for inverting image is given. if len(sys.argv) == 7: print("Invert options must be set for both images") sys.exit() # Inverting input images if is wanted. if len(sys.argv) > 6: if int(sys.argv[6]) == 1: im1 = ImageOps.invert(im1) if int(sys.argv[7]) == 1: im2 = ImageOps.invert(im2) # Image resize for squared images. size = 300, 300 # Converting to b/w. gray1 = im1.convert('L') im1 = gray1.point(lambda x: 0 if x < 128 else 255, '1') gray2 = im2.convert('L') im2 = gray2.point(lambda x: 0 if x < 128 else 255, '1') # Dice coeficinet computation res = dice(im1, im2) ################################################################################################################################################################# sheet.cell(row=1, column=p+2).value = str(min_sList[p])+"-"+str(max_sList[p])+"-"+str(num_sList[p])+"-"+str(thresList[p])+"-"+str(overList[p]) sheet.cell(row=int(argv[5]), column=p+2).value = res print("/home/toya/Research/Wasan/data/summary/AllKanjiPositionTest/"+str(maskOutputFile.split("/")[-1])) print(res) #exit() book.save('/home/toya/Research/Wasan/data/summary/evaluate.xlsx') book.close()
# cen_row, cen_col, min_row, min_col, max_row, max_col, X nuclei_list = [] with open(NUCLEI_COOR_FILE, "r") as f: for i in f.readlines(): nuclei_list.append(i[:-1].split("\t")[:-1]) foci_list = [] for i in nuclei_list: roi_region = region_img[int(i[2]):int(i[4]), int(i[3]):int(i[5])] roi_binary = binary_img[int(i[2]):int(i[4]), int(i[3]):int(i[5])] roi_foci = foci_img[int(i[2]):int(i[4]), int(i[3]):int(i[5])] roi_binary = binary_dilation(roi_binary, disk(params['DILATION_FAC'])) roi_binary = binary_fill_holes(roi_binary) binary_img[int(i[2]):int(i[4]), int(i[3]):int(i[5])] = roi_binary foci = blob_log(roi_foci, min_sigma=params['MIN_SIGMA'], \ max_sigma=params['MAX_SIGMA'], num_sigma=params['NUM_SIGMA'],\ threshold=params['BACK_THRES'], overlap=params['OVERLAP_RATIO']) print("X={}, list generated".format(int(i[6]))) on_list = [] off_list = [] for j in foci: focus_row = int(j[0]) focus_col = int(j[1]) if focus_row < roi_binary.shape[0] and \ focus_col < roi_binary.shape[1] and \ roi_binary[focus_row,focus_col]: on_list.append(j) print("X={}, + 1".format(int(i[6]))) else: off_list.append(j) if focus_row >= roi_binary.shape[0]:
# Unix style pathname pattern expansion, e.g. glob.glob(r"C:\Users\Tavish\Deskto\pwint_sky.gif")[0] # String is to be treated as a raw string, exactly the string literals marked by a 'r' example_file = glob.glob("../Assets/wint_sky.gif")[0] # Out: 'Assets/wint_sky.gif' im = imread(example_file, as_grey=True) sp1 = fig.add_subplot(121) sp1.imshow(im, cmap=plt.get_cmap('gray')) # Counting: search continuous objects in the picture # Blobs are found using the Laplacian of Gaussian (LoG) method. For each blob found, # the method returns its coordinates and the standard deviation of the Gaussian kernel # that detected the blob. # threshold: The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. # Reduce this to detect blobs with less intensities. # Output: A 2d array with each row representing 3 values, (y,x,sigma) where (y,x) are coordinates of the blob # and sigma is the standard deviation blobs_log = blob_log(im, max_sigma=30, num_sigma=10, threshold=.1) # len(blobs_log) = 308 # .. output - first two are coordinates, and the third is the area of the object # Compute radii in the 3rd column blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) numrows = len(blobs_log) print("Number of stars : ", numrows) # Check whether there is a missing # fig, ax = plt.subplots(1, 1) sp2 = fig.add_subplot(122) sp2.imshow(im, cmap=plt.get_cmap('gray')) for blob in blobs_log: y, x, r = blob c = plt.Circle((x,y), r+5, color='lime', linewidth=2, fill=False) sp2.add_patch(c)
def generate_orientation_fibers(cfg, eta_ome): """ From ome-eta maps and hklid spec, generate list of quaternions from fibers """ # grab the relevant parameters from the root config ncpus = cfg.multiprocessing chi = cfg.instrument.hedm.chi seed_hkl_ids = cfg.find_orientations.seed_search.hkl_seeds fiber_ndiv = cfg.find_orientations.seed_search.fiber_ndiv method_dict = cfg.find_orientations.seed_search.method # strip out method name and kwargs # !!! note that the config enforces that method is a dict with length 1 # TODO: put a consistency check on required kwargs, or otherwise specify # default values for each case? They must be specified as of now. method = next(iter(method_dict.keys())) method_kwargs = method_dict[method] logger.info('\tusing "%s" method for fiber generation' % method) # seed_hkl_ids must be consistent with this... pd_hkl_ids = eta_ome.iHKLList[seed_hkl_ids] # grab angular grid infor from maps del_ome = eta_ome.omegas[1] - eta_ome.omegas[0] del_eta = eta_ome.etas[1] - eta_ome.etas[0] # labeling mask structureNDI_label = ndimage.generate_binary_structure(2, 1) # crystallography data from the pd object pd = eta_ome.planeData hkls = pd.hkls tTh = pd.getTTh() bMat = pd.latVecOps['B'] csym = pd.getLaueGroup() params = dict(bMat=bMat, chi=chi, csym=csym, fiber_ndiv=fiber_ndiv) # ========================================================================= # Labeling of spots from seed hkls # ========================================================================= qfib = [] input_p = [] numSpots = [] coms = [] for i in seed_hkl_ids: if method == 'label': # First apply filter filt_stdev = fwhm_to_stdev * method_kwargs['filter_radius'] this_map_f = -ndimage.filters.gaussian_laplace( eta_ome.dataStore[i], filt_stdev) labels_t, numSpots_t = ndimage.label( this_map_f > method_kwargs['threshold'], structureNDI_label) coms_t = np.atleast_2d( ndimage.center_of_mass(this_map_f, labels=labels_t, index=np.arange(1, np.amax(labels_t) + 1))) elif method in ['blob_log', 'blob_dog']: # must scale map # TODO: we should so a parameter study here this_map = eta_ome.dataStore[i] this_map[np.isnan(this_map)] = 0. this_map -= np.min(this_map) scl_map = 2 * this_map / np.max(this_map) - 1. # TODO: Currently the method kwargs must be explicitly specified # in the config, and there are no checks # for 'blob_log': min_sigma=0.5, max_sigma=5, # num_sigma=10, threshold=0.01, overlap=0.1 # for 'blob_dog': min_sigma=0.5, max_sigma=5, # sigma_ratio=1.6, threshold=0.01, overlap=0.1 if method == 'blob_log': blobs = np.atleast_2d(blob_log(scl_map, **method_kwargs)) else: # blob_dog blobs = np.atleast_2d(blob_dog(scl_map, **method_kwargs)) numSpots_t = len(blobs) coms_t = blobs[:, :2] numSpots.append(numSpots_t) coms.append(coms_t) pass for i in range(len(pd_hkl_ids)): for ispot in range(numSpots[i]): if not np.isnan(coms[i][ispot][0]): ome_c = eta_ome.omeEdges[0] + (0.5 + coms[i][ispot][0]) * del_ome eta_c = eta_ome.etaEdges[0] + (0.5 + coms[i][ispot][1]) * del_eta input_p.append( np.hstack([ hkls[:, pd_hkl_ids[i]], tTh[pd_hkl_ids[i]], eta_c, ome_c ])) pass pass pass # do the mapping start = timeit.default_timer() qfib = None if ncpus > 1: # multiple process version # ???: Need a chunksize in map? chunksize = max(1, len(input_p) // (10 * ncpus)) pool = mp.Pool(ncpus, discretefiber_init, (params, )) qfib = pool.map(discretefiber_reduced, input_p, chunksize=chunksize) ''' # This is an experiment... ntotal= 10*ncpus + np.remainder(len(input_p), 10*ncpus) > 0 for _ in tqdm.tqdm( pool.imap_unordered( discretefiber_reduced, input_p, chunksize=chunksize ), total=ntotal ): pass print(_.shape) ''' pool.close() pool.join() else: # single process version. discretefiber_init(params) # sets paramMP # We convert to a list to ensure the map is full iterated before # clean up. Otherwise discretefiber_reduced will be called # after cleanup. qfib = list(map(discretefiber_reduced, input_p)) discretefiber_cleanup() elapsed = (timeit.default_timer() - start) logger.info("\tfiber generation took %.3f seconds", elapsed) return np.hstack(qfib)
def test_blob_log(): r2 = math.sqrt(2) img = np.ones((256, 256)) xs, ys = circle(200, 65, 5) img[xs, ys] = 255 xs, ys = circle(80, 25, 15) img[xs, ys] = 255 xs, ys = circle(50, 150, 25) img[xs, ys] = 255 xs, ys = circle(100, 175, 30) img[xs, ys] = 255 blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1) radius = lambda x: r2 * x[2] s = sorted(blobs, key=radius) thresh = 3 b = s[0] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 65) <= thresh assert abs(radius(b) - 5) <= thresh b = s[1] assert abs(b[0] - 80) <= thresh assert abs(b[1] - 25) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 50) <= thresh assert abs(b[1] - 150) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 175) <= thresh assert abs(radius(b) - 30) <= thresh # Testing log scale blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1, log_scale=True) b = s[0] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 65) <= thresh assert abs(radius(b) - 5) <= thresh b = s[1] assert abs(b[0] - 80) <= thresh assert abs(b[1] - 25) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 50) <= thresh assert abs(b[1] - 150) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 175) <= thresh assert abs(radius(b) - 30) <= thresh # Testing no peaks img_empty = np.zeros((100, 100)) assert blob_log(img_empty).size == 0 # Testing 3D r = 6 pad = 10 im3 = ellipsoid(r, r, r) im3 = util.pad(im3, pad, mode='constant') blobs = blob_log(im3, min_sigma=3, max_sigma=10) 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 action(self, export_images=False): """ :param export_images: True for export detected and undetected images :return: csv file contain all the cell's are c-fos positive for given bregma """ if export_images: try: mkdir(self.__path + "\\blob_filter_" + self.__data_file_name[:-4]) except FileExistsError: None try: mkdir(self.__path + "\\blob_filter_not_found_" + self.__data_file_name[:-4]) except FileExistsError: None Image.MAX_IMAGE_PIXELS = 275727232 count_verify = 0 image = plt.imread(self.__path + "\\" + self.__image_file_name) data = pn.read_csv(self.__path + "\\" + self.__data_file_name) mean_channel_3 = data['Channel 3'].mean() # data = data[data['id name'] == 'Field CA1'] d = 20 # Represnting the pixels for each side for index, row in data.iterrows(): verify = False cell_channels_images = image[abs(int(row['y'])) - d:abs(int(row['y'])) + d, abs(int(row['x'])) - d:int(row['x']) + d, :] cell_image = cell_channels_images[:, :, 1] gray_cell_image = rgb2gray(cell_image) blob_log_list = blob_log(gray_cell_image, max_sigma=8, min_sigma=2, threshold=.03) blob_log_list[:, 2] = blob_log_list[:, 2] * sqrt(2) if len(blob_log_list) == 0: data.drop(index, inplace=True) continue for blob in blob_log_list: x, y, r = blob if distance.euclidean([d, d], [x, y]) <= r: # or (25 >= x >= 15 and 25 >= y >= 15) verify = True break if not verify: data.drop(index, inplace=True) if row['Channel 3'] > mean_channel_3: if export_images: plt.clf() fig = plt.figure(figsize=(20, 20)) plt.subplot(131) plt.title("C-fos") plt.imshow(cell_image) for blob in blob_log_list: y, x, r = blob # print("X: " + str(x) + " Y: " + str(y) + " R: " + str(r)) c = plt.Circle((x, y), r, color="Yellow", linewidth=1, fill=False) plt.gca().add_patch(c) plt.gca().add_patch( ptc.Rectangle((15, 15), 10, 10, linewidth=1, edgecolor='r', facecolor='none')) plt.subplot(132) plt.title("NeuN") plt.imshow(cell_channels_images[:, :, 0]) plt.gca().add_patch( ptc.Rectangle((15, 15), 10, 10, linewidth=1, edgecolor='r', facecolor='none')) plt.subplot(133) plt.title("Dapi") plt.imshow(cell_channels_images[:, :, 2]) plt.gca().add_patch( ptc.Rectangle((15, 15), 10, 10, linewidth=1, edgecolor='r', facecolor='none')) plt.savefig(self.__path + "\\blob_filter_not_found_" + self.__data_file_name[:-4] + "\\" + str(index) + ".jpg") plt.close(fig) if verify: count_verify += 1 if export_images: fig = plt.figure(figsize=(20, 20)) plt.subplot(131) plt.title("C-fos") plt.imshow(cell_image) plt.subplot(132) plt.title("Dapi") plt.imshow(cell_channels_images[:, :, 2]) plt.savefig(self.__path + "\\blob_filter_" + self.__data_file_name[:-4] + "\\" + str(index) + ".jpg") data.to_csv(self.__path + "\\" + self.__data_file_name[:-4] + "filtered.csv", index=False) print(count_verify)
def main(): from pyhdf.SD import SD, SDC plot = True # setup paths # TODO update when all MAIAC data has been pulled root = '/Users/danielfisher/Projects/kcl-ltss-bioatm/data' maiac_path = os.path.join(root, 'raw/plume_identification/maiac') for maiac_fname in os.listdir(maiac_path): if 'MCD19A2.A2017210.h12v11.006.2018117231329' not in maiac_fname: continue # MCD19A2.A2017210.h12v11.006.2018117231329 # 'MCD19A2.A2017255.h12v09.006.2018119143112' if '.hdf' not in maiac_fname: continue hdf_file = SD(os.path.join(maiac_path, maiac_fname), SDC.READ) aod, lat, lon = tools.read_modis_aod(hdf_file) blobs_log = blob_log(aod, max_sigma=30, num_sigma=10, threshold=.1) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(aod, max_sigma=30, threshold=.1) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(aod, max_sigma=30, threshold=.01) blobs_list = [blobs_log, blobs_dog, blobs_doh] colors = ['yellow', 'lime', 'red'] titles = [ 'Laplacian of Gaussian', 'Difference of Gaussian', 'Determinant of Hessian' ] sequence = zip(blobs_list, colors, titles) fig, axes = plt.subplots(1, 3, figsize=(9, 3), sharex=True, sharey=True) ax = axes.ravel() for idx, (blobs, color, title) in enumerate(sequence): ax[idx].set_title(title) ax[idx].imshow(aod, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False) ax[idx].add_patch(c) ax[idx].set_axis_off() plt.tight_layout() plt.show()
def detectSpotsLoG(image, min_sigma=1, max_sigma=10, num_sigma=10, threshold=0.2, overlap=0.5): image = image.astype('uint8') blobs = blob_log(image, min_sigma, max_sigma, num_sigma, threshold, overlap) return blobs
def test_blob_log(): r2 = math.sqrt(2) img = np.ones((256, 256)) xs, ys = disk((200, 65), 5) img[xs, ys] = 255 xs, ys = disk((80, 25), 15) img[xs, ys] = 255 xs, ys = disk((50, 150), 25) img[xs, ys] = 255 xs, ys = disk((100, 175), 30) img[xs, ys] = 255 blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1) radius = lambda x: r2 * x[2] s = sorted(blobs, key=radius) thresh = 3 b = s[0] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 65) <= thresh assert abs(radius(b) - 5) <= thresh b = s[1] assert abs(b[0] - 80) <= thresh assert abs(b[1] - 25) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 50) <= thresh assert abs(b[1] - 150) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 175) <= thresh assert abs(radius(b) - 30) <= thresh # Testing log scale blobs = blob_log(img, min_sigma=5, max_sigma=20, threshold=1, log_scale=True) b = s[0] assert abs(b[0] - 200) <= thresh assert abs(b[1] - 65) <= thresh assert abs(radius(b) - 5) <= thresh b = s[1] assert abs(b[0] - 80) <= thresh assert abs(b[1] - 25) <= thresh assert abs(radius(b) - 15) <= thresh b = s[2] assert abs(b[0] - 50) <= thresh assert abs(b[1] - 150) <= thresh assert abs(radius(b) - 25) <= thresh b = s[3] assert abs(b[0] - 100) <= thresh assert abs(b[1] - 175) <= thresh assert abs(radius(b) - 30) <= thresh # Testing no peaks img_empty = np.zeros((100, 100)) assert blob_log(img_empty).size == 0
def _get_plane_cells(img, blob_detect_info): max_radius, size_iterations, rel_threshold, overlap, min_intensity = blob_detect_info blobs = blob_log(normalize(img),min_sigma = 1, max_sigma=max_radius*0.70710678118, # sigma = radius/sqrt(2) num_sigma=size_iterations, threshold=rel_threshold/np.max(img), overlap=overlap) blobs = np.asarray([(y, x, r) for x, y, r in blobs if (img[int(x), int(y)] > min_intensity)]) #chera y ro miare aval bad x ro? return blobs[:,(0,1)], blobs[:,2]
# # Blob # In[157]: from skimage.feature import blob_dog, blob_log, blob_doh from skimage.color import rgb2gray # In[169]: type(sample_imgs) # In[171]: len(blob_log(rgb2gray(sample_imgs[4]))) # # Hough line # In[181]: from skimage.transform import (hough_line, probabilistic_hough_line, hough_line_peaks) # In[189]: a,b,c = hough_line(rgb2gray(sample_imgs[5])) e,f,g = hough_line_peaks(a,b,c)
def angle(p1, p2): xDiff = p2[0] - p1[0] yDiff = p2[1] - p1[1] #return degrees(atan2(yDiff, xDiff)) return atan2(yDiff, xDiff) io.imshow(image_gray) io.show() # blobs print('Computing laplace of gaussian') #blobs_log = blob_log(image_gray, max_sigma=35, min_sigma=3, num_sigma=10, threshold=2, overlap=.01) blobs_log = blob_log(image_gray, max_sigma=35, min_sigma=6, num_sigma=10, threshold=2, overlap=.01) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) print('Computed') fig, ax = plt.subplots(1, 1) # ax.set_title('Laplacian of Gaussian') ax.imshow(image_gray) print('Drawing') for blob in blobs_log: y, x, r = blob #c = plt.Circle((x, y), 3, color='red', linewidth=1, fill=False) c = plt.Circle((x, y), r, color='red', linewidth=1, fill=False) ax.add_patch(c)
def Id_cells(self): if type(self.BLUEimage) == type(0): return while self.table.rowCount() < int(self.numLayers.text()) + 2: self.table.insertRow(0) while self.table.rowCount() > int(self.numLayers.text()) + 2: self.table.removeRow(0) for num, layer in enumerate( [str(x + 1) for x in range(int(self.numLayers.text()))] + ['Total selected reg', 'Total image']): self.table.setItem(num, 0, QtWidgets.QTableWidgetItem(layer)) self.table.setItem(num, 1, QtWidgets.QTableWidgetItem("0")) self.table.setItem(num, 2, QtWidgets.QTableWidgetItem("0")) self.table.setItem(num, 3, QtWidgets.QTableWidgetItem("0")) self.table.setItem(num, 4, QtWidgets.QTableWidgetItem("0")) self.table.setItem(num, 5, QtWidgets.QTableWidgetItem("0")) squaresize = self.cropsize image_gray = self.BLUEimage self.BLUEblobs = blob_log(self.BLUEimage, max_sigma=int(self.maxSigSpin.text()), num_sigma=10, min_sigma=int(self.minSigSpin.text()), overlap=float(self.log_overlap.text()), threshold=float(self.thresholdSpin.text()), exclude_border=squaresize) self.table.setItem( int(self.numLayers.text()) + 1, 4, QtWidgets.QTableWidgetItem(str(len(self.BLUEblobs)))) if str(self.fMarker.currentText()) == 'RFP': blobs = blob_log(self.REDimage, max_sigma=int(self.maxSigSpin.text()), num_sigma=10, min_sigma=int(self.minSigSpin.text()), overlap=float(self.log_overlap.text()), threshold=float(self.thresholdSpin.text()), exclude_border=squaresize) self.table.setItem( int(self.numLayers.text()) + 1, 4, QtWidgets.QTableWidgetItem(str(len(self.BLUEblobs)))) if str(self.fMarker.currentText()) == 'GFP': blobs = blob_log(self.GREENimage, max_sigma=int(self.maxSigSpin.text()), num_sigma=10, min_sigma=int(self.minSigSpin.text()), overlap=float(self.log_overlap.text()), threshold=float(self.thresholdSpin.text()), exclude_border=squaresize) self.table.setItem( int(self.numLayers.text()) + 1, 4, QtWidgets.QTableWidgetItem(str(len(self.BLUEblobs)))) if str(self.fMarker.currentText()) == 'GFP or RFP': blobs = blob_log(self.REDimage + self.GREENimage, max_sigma=int(self.maxSigSpin.text()), num_sigma=10, min_sigma=int(self.minSigSpin.text()), overlap=float(self.log_overlap.text()), threshold=float(self.thresholdSpin.text()), exclude_border=squaresize) self.table.setItem( int(self.numLayers.text()) + 1, 4, QtWidgets.QTableWidgetItem(str(len(self.BLUEblobs)))) #blobsDAPI = blob_log(self.BLUEimage[squaresize:-squaresize,squaresize:-squaresize], max_sigma=10, num_sigma=10, min_sigma = 3, threshold=.1) self.THEblobs = blobs self.nMarkedCells.setText(str(len(blobs))) self.table.setItem( int(self.numLayers.text()) + 1, 1, QtWidgets.QTableWidgetItem(str(len(blobs)))) #self.table.setItem(9 , 2, QtWidgets.QTableWidgetItem(str(len(blobsDAPI)))) if float(self.table.item(int(self.numLayers.text()) + 1, 2).text()) != 0: self.table.setItem( int(self.numLayers.text()) + 1, 3, QtWidgets.QTableWidgetItem( str( float( self.table.item(int(self.numLayers.text()) + 1, 1).text()) / float( self.table.item(int(self.numLayers.text()) + 1, 2).text())))) self.ImgAddPatches()
def main(argv): # Blod detector tester function #parameters: #argv[1] contains input file name #argv[2] contains output file name #argv[3] contains type of blob detector: 0 for simple detector, 1 for Laplacian Of Gaussians (LoG), 2 for Difference of Gaussian (DoG), 3 for Hessian of Gaussian (HoG) # other parameters are included after、argv[4] and later, check each method image_gray = cv2.imread(argv[1], cv2.IMREAD_GRAYSCALE) image = image_gray image_black = (255 - image_gray) #let's create a text output file too positionsOutputFile = argv[2].split(".")[0] + "POSITIONS.txt" print("positions file " + str(positionsOutputFile)) print("output file " + argv[2]) #open it too posF = open(positionsOutputFile, "a") #switch between the different types of blob detector if int(argv[3]) == 0: keypoints = SimpleBlobDetector(argv, image) #print ("number of keypoints outside "+str(len(keypoints))) elif int(argv[3]) == 1: #parameters: http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_log min_s = 30 over = .1 #example!, other parameters exist if len(argv) > 4: min_s = int(argv[4]) if len(argv) > 5: over = float(argv[5]) #print("starting laplacion of gaussians detector with parameters "+str(min_s)+" "+str(over)) blob_List = blob_log(image_black, min_sigma=min_s, overlap=over) # Compute radii in the 3rd column. blob_List[:, 2] = blob_List[:, 2] * sqrt(2) elif int(argv[3]) == 2: #parameters: http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_dog blob_List = blob_dog(image_black, min_sigma=40, threshold=1) blob_List[:, 2] = blob_List[:, 2] * sqrt(2) elif int(argv[3]) == 3: #parameters: http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.blob_doh min_s = 30 if len(argv) > 4: min_s = int(argv[4]) blob_List = blob_doh(image_gray, min_sigma=min_s, max_sigma=100, threshold=.01, overlap=0.4) else: print("Blob detector type not supported: " + argv[3]) sys.exit(-1) #Now write the results to file if int(argv[3]) == 1 or int(argv[3]) == 2 or int(argv[3]) == 3: for blob in blob_List: y, x, r = blob cv2.rectangle(image, (int(x - r), int(y - r)), (int(x + r), int(y + r)), (0, 0, 255), 1) #cv2.circle(image,(int(x),int(y)),int(r),(0,0,255)) cv2.imwrite(argv[2], image) else: # must be 0 as we already controled other cases # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob #im_with_keypoints = cv2.drawKeypoints(image, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) #cv2.imwrite("sambombita.jpg",im_with_keypoints) for kp in keypoints: x = kp.pt[0] y = kp.pt[1] r = kp.size cv2.rectangle(image, (int(x - r), int(y - r)), (int(x + r), int(y + r)), (0, 0, 255), 1) #cv2.circle(image,(int(x),int(y)),int(r),(0,0,255)) cv2.imwrite(argv[2], image) #now crop each kanji image #sys.exit(0) #print("now Cropping") try: os.mkdir(argv[2] + "PATCHES") except: #print("An exception occurred Probably directory already existed") pass margin = 5 scale_percent = 5000 # percent of original size if int(argv[3]) == 1 or int(argv[3]) == 2 or int(argv[3]) == 3: i = 0 image = cv2.imread(argv[1], cv2.IMREAD_GRAYSCALE) #print("Number of Blobs "+str(len(blob_List))) print(str(len(blob_List))) for blob in blob_List: #print("Cropping blob "+str(i)) y, x, r = blob posF.write("kanji" + str(int(i)) + " " + str(int(y)) + " " + str(int(x)) + " " + str(r) + "\n") currentKanjiImage = imcrop( image, (int(x - r - margin), int(y - r - margin), int(x + r + margin), int(y + r + margin))) newImageName = argv[2] + "PATCHES/kanji" + str(i) + ".png" #cv2.imwrite(newImageName,currentKanjiImage) width = int(currentKanjiImage.shape[1] * scale_percent / 100) height = int(currentKanjiImage.shape[0] * scale_percent / 100) #width = int(800) #height = int(593) dim = (width, height) # resize image resized = cv2.resize(currentKanjiImage, dim, interpolation=cv2.INTER_NEAREST) #negative image negImage = (255 - resized) cv2.imwrite(newImageName, negImage) i = i + 1 else: i = 0 image = cv2.imread(argv[1], cv2.IMREAD_GRAYSCALE) #print("Number of Blobs "+str(len(keypoints))) print(str(len(keypoints))) for kp in keypoints: #print("Cropping simple blob "+str(i)) x = kp.pt[0] y = kp.pt[1] r = kp.size currentKanjiImage = imcrop( image, (int(x - r - margin), int(y - r - margin), int(x + r + margin), int(y + r + margin))) newImageName = argv[2] + "PATCHES/kanji" + str(i) + ".png" posF.write("kanji" + str(int(i)) + " " + str(int(y)) + " " + str(int(x)) + " " + str(r) + "\n") #cv2.imwrite(newImageName,currentKanjiImage) width = int(currentKanjiImage.shape[1] * scale_percent / 100) height = int(currentKanjiImage.shape[0] * scale_percent / 100) #width = int(800) #height = int(593) dim = (width, height) # resize image resized = cv2.resize(currentKanjiImage, dim, interpolation=cv2.INTER_NEAREST) #negative image negImage = (255 - resized) cv2.imwrite(newImageName, negImage) i = i + 1 posF.close()
if not os.path.exists(directory): os.makedirs(directory) images = os.fsencode(img_dir) num = 1 for file in os.listdir(images): filename = os.fsdecode(file) if filename.endswith('.jpg'): print(filename) img = imread(img_dir + '/' + filename) img_gray = rgb2gray(img) blobs_log = blob_log(img_gray, min_sigma=5, max_sigma=30, num_sigma=10, threshold=.075) blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) X = blobs_log[:, 1] Y = blobs_log[:, 0] fileName2 = filename.replace('.jpg', '') for i in range(X.shape[0]): y1 = int(Y[i] - 20) y2 = int(Y[i] + 20) x1 = int(X[i] - 20) x2 = int(X[i] + 20) if y1 < 0 or x1 < 0 or y2 > img.shape[0] or x2 > img.shape[1]:
def yard_mark_detection(image, img_f, view): image_gray = rgb2gray(image) # io.imshow(image_gray) # io.show() if (view == 'sideline'): sideline_mask = load_sideline_mask(img_f) sideline_mask = sideline_mask.astype(int) else: sideline_mask = np.ones_like(image_gray) print('sideline mask') print(sideline_mask) grad = gradient(image_gray, disk(2), mask=sideline_mask) grad = grad / 255 print(np.min(grad), np.max(grad), np.mean(grad)) grad_filter_high = np.zeros_like(image_gray) grad_filter_high[grad > 0.5] = 1 grad_filter_mid = np.zeros_like(image_gray) grad_filter_mid[np.logical_and(grad > 0.2, grad < 0.5)] = 1 # io.imshow(grad_filter_high) # io.show() grad_high_erode = binary_erosion(grad_filter_high, disk(1)) grad_high_dilate = binary_dilation(grad_high_erode, disk(5)) #grad_high_dilate = iterative_dilate(grad_filter_high, 1) # io.imshow(grad_high_dilate) # io.show() mask2 = np.logical_and(sideline_mask, np.logical_not(grad_high_dilate)).astype(int) # io.imshow(mask2) # io.show() ### step 2 with updated mask grad = gradient(image_gray, disk(2), mask=mask2) grad = grad / 255 print(np.min(grad), np.max(grad), np.mean(grad)) # io.imshow(grad) # io.show() #return grad_filter_high = np.zeros_like(image_gray) grad_filter_high[grad > 0.5] = 1 grad_filter_mid = np.zeros_like(image_gray) grad_filter_mid[np.logical_and(grad > 0.2, grad < 0.5)] = 1 # io.imshow(grad_filter_mid) # io.show() ### edges and closing edges = canny(grad_filter_mid, 1.0) #edges = canny(image_hsv[:, :, 1]) # io.imshow(edges) # io.show() edges_closed = binary_closing(edges) # io.imshow(edges_closed) # io.show() edges_filled = binary_fill_holes(edges_closed) edges_filled = binary_opening(edges_filled) # io.imshow(edges_filled) # io.show() ##################################### blob_type = 'dog' if (blob_type == 'log'): blobs = blob_log(edges_filled, max_sigma=100, num_sigma=10, threshold=.1) if (blob_type == 'dog'): blobs = blob_dog(edges_filled, max_sigma=100, threshold=.1) if (blob_type == 'doh'): blobs = blob_doh(edges_filled, max_sigma=100, threshold=.01) print('blobs') print(blobs) print(np.shape(blobs)) img_h, img_w = np.shape(image_gray) print(min(blobs[:, 2]), max(blobs[:, 2]), np.mean(blobs[:, 2])) blobs = blobs[blobs[:, 2] > 20] blobs = blobs[np.logical_or((blobs[:, 0] > 0.7 * img_h), (blobs[:, 0] < 0.3 * img_h))] blob_centres = np.zeros_like(grad_filter_high) print(np.shape(blob_centres)) for xs, ys, r in blobs: blob_centres[int(xs), int(ys)] = 1 blob_centres = blob_centres.astype(float) # io.imshow(blob_centres) # io.show() #return # blob_centre_output_folder = base_folder + '/images_processed/blob_centre/{0}/{1}'.format(view, blob_type) # if not os.path.exists(blob_centre_output_folder): # os.makedirs(blob_centre_output_folder) #io.imsave(blob_centre_output_folder + '/' + img_f, blob_centres) ### plot blobs fig, axes = plt.subplots(2, 1, figsize=(15, 9)) ax = axes.ravel() ax[0].imshow(image) ax[0].set_title('Input image') ax[0].set_axis_off() ax[1].imshow(image) origin = np.array((0, image.shape[1])) img_subs = [] for xs, ys, r in blobs: #ax[1].plot(xs, ys, 'b') c = plt.Circle((ys, xs), r, color='red', linewidth=2, fill=False) ax[1].add_patch(c) w_sub = 100 xs_sub = [max(0, int(xs - w_sub)), min(img_h, int(xs + w_sub))] ys_sub = [max(0, int(ys - w_sub)), min(img_w, int(ys + w_sub))] print('xy', xs, ys) print('xs sub', xs_sub) print('ys sub', ys_sub) img_sub = image[xs_sub[0]:xs_sub[1], ys_sub[0]:ys_sub[1], :] print('img_sub', np.shape(img_sub)) img_subs.append(img_sub) ax[1].set_xlim(origin) ax[1].set_ylim((image.shape[0], 0)) ax[1].set_axis_off() #ax[1].set_title(title) plt.tight_layout() plt.show() for img_sub in img_subs: print(np.shape(img_sub)) io.imshow(img_sub) io.show()
# El HoG es algo diferente y detecta los blobs directos e inversos. Este método tiene problemas con los blobs pequeños menores de 3 pixels. # In[7]: import skimage.io as io import skimage.color as color import matplotlib.pyplot as pylab from numpy import sqrt, flip from skimage.feature import blob_dog, blob_log, blob_doh im = io.imread('20190711_132853_R.jpg') im_gray = color.rgb2gray(im) ## im_gray = flip(im_gray, 1) log_blobs = blob_log(im_gray, max_sigma=30, num_sigma=10, threshold=.1) log_blobs[:, 2] = sqrt(2) * log_blobs[:, 2] # radio en 3a columna dog_blobs = blob_dog(im_gray, max_sigma=30, threshold=0.1) dog_blobs[:, 2] = sqrt(2) * dog_blobs[:, 2] doh_blobs = blob_doh(im_gray, max_sigma=30, threshold=0.001) list_blobs = [log_blobs, dog_blobs, doh_blobs] color, titles = ['yellow', 'lime', 'red'], [ 'Laplacian of Gaussian', 'Difference of Gaussian', 'Determinant of Hessian' ] sequence = zip(list_blobs, color, titles) fig, axes = pylab.subplots(2, 2, figsize=(20, 20), sharex=True, sharey=True) axes = axes.ravel() axes[0].imshow(im_gray, interpolation='nearest', cmap='gray') axes[0].set_title('original image', size=30), axes[0].set_axis_off()
from matplotlib import pyplot as plt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray image = data.imread('./lung-window.png')[100:400, 100:650] image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) blobs_list = [blobs_log, blobs_dog, blobs_doh] colors = ['yellow', 'lime', 'red'] titles = [ 'Laplacian of Gaussian', 'Difference of Gaussian', 'Determinant of Hessian' ] sequence = zip(blobs_list, colors, titles) fig, axes = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) axes = axes.ravel()
fig.suptitle("Grey level co-occurrence matrix features", fontsize=14) plt.show() #%% bob detection from matplotlib import pyplot as plt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray # image = data.hubble_deep_field()[0:500, 0:500] image = cv2.resize(img1, (256, 256)) image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=0.1) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=0.1) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=0.01) blobs_list = [blobs_log, blobs_dog, blobs_doh] colors = ["yellow", "lime", "red"] titles = ["Laplacian of Gaussian", "Difference of Gaussian", "Determinant of Hessian"] sequence = zip(blobs_list, colors, titles) for blobs, color, title in sequence: fig, ax = plt.subplots(1, 1)
original_image = io.imread( 'C:\Users\jackh\OneDrive\Documents\College\Python\Images\dice.jpg') #======================= Processing ============================# takes 1 minute Black_White_image = rgb2grey(original_image) thresh = threshold_minimum(Black_White_image) binary_image = Black_White_image > thresh contours1 = find_contours(binary_image, 0.1) binary_image_copy = np.copy(binary_image) binary_image_copy[1:-1, 1:-1] = 1 filled_image = reconstruction(binary_image_copy, binary_image, method='erosion') filled_image[0:100, :] = 0 filled_image[:, 0:200] = 0 contours2 = find_contours(filled_image, 0.1) Blob_centres = blob_log(filled_image, min_sigma=100) ### count dice #===================== Plotting & Printing =======================# print('The Total Number of Dices in Image = ', len(Blob_centres)) plt.subplot(2, 4, 1) plt.imshow(original_image, cmap=plt.cm.gray) plt.title('Original Image') plt.subplot(2, 4, 2) plt.imshow(Black_White_image, cmap=plt.cm.gray) plt.title('Black & White Image') plt.subplot(2, 4, 3) plt.imshow(binary_image, cmap=plt.cm.gray) plt.title('Binarized Image') plt.subplot(2, 4, 4)
cropSize = 100 outFile = open(outputDir + '/segmentation_' + str(rank) + '.dat', 'wb') for frame in tqdm(procFrameList[rank]): gImgRaw = fp['/dataProcessing/gImgRawStack/' + str(frame).zfill(zfillVal)].value gImgNorm = imageProcess.normalize(gImgRaw, min=0, max=230) gImgProc = fp['/dataProcessing/processedStack/' + str(frame).zfill(zfillVal)].value bImgBdry = gImgRaw.copy() bImgBdry[:] = 0 blobs_log = blob_log(gImgProc, min_sigma=15, max_sigma=20, num_sigma=5, threshold=0.15) if (blobs_log.size > 0): blobs_log[:, 2] = blobs_log[:, 2] * numpy.sqrt(2) counter = 0 particleDetails = [] for r, c, rad in blobs_log: rr, cc = circle_perimeter(int(r), int(c), int(rad)) if ((rr < 0).any() == True or (cc < 0).any() == True): pass elif ((rr > row - 1).any() == True or (cc > col - 1).any() == True): pass else:
density *= factor print density.max() _max = density.max() image = density print image.shape threshold = 100 # factor = image_gray.max() / _max # threshold = 100.0 * factor print threshold print image.shape blobs_log = blob_log( image, # max_sigma=30, # num_sigma=10, min_sigma=1, threshold=threshold) # Compute radii in the last column. blobs_log[:, 3] = blobs_log[:, 3] * sqrt(3) blobs_dog = blob_dog(image, max_sigma=30, threshold=threshold) blobs_dog[:, 3] = blobs_dog[:, 3] * sqrt(3) blobs_list = [blobs_log, blobs_dog] colors = ['yellow', 'lime'] titles = ['Laplacian of Gaussian', 'Difference of Gaussian'] sequence = zip(blobs_list, colors, titles) fig, axes = plt.subplots(1, 2, figsize=(6, 3), sharex=True, sharey=True)