Exemplo n.º 1
0
def h_watershed_peak_search(vote_hmap, hmap_thresh):
    label_mask = vote_hmap >= hmap_thresh
    vote_hmap = -1 * vote_hmap
    markers_bool = h_minima(vote_hmap, h=hmap_thresh) * label_mask
    markers, num_instances = ndi.label(markers_bool)
    ws_mask = watershed(vote_hmap, markers=markers, mask=label_mask)
    # 0 is background
    assert num_instances == len(np.unique(ws_mask)) - 1, \
        '{} vs {}'.format(num_instances, len(np.unique(ws_mask)) - 1)
    peak_bbox = []
    for i in range(1, num_instances + 1):
        bbox = get_xywh_bbox_from_binary_mask(ws_mask == i)
        peak_bbox.append(bbox)
    peak_bbox = np.array(peak_bbox).reshape(-1, 4)
    assert peak_bbox.shape == (num_instances, 4)
    peaks = np.stack((peak_bbox[:, 0] + peak_bbox[:, 2] // 2,
                      peak_bbox[:, 1] + peak_bbox[:, 3] // 2),
                     axis=1)
    assert peaks.shape == (num_instances, 2)
    return ws_mask, peaks, peak_bbox
Exemplo n.º 2
0
def segmentByClustering( rgbImage, colorSpace, clusteringMethod, numberOfClusters):
   #module importation
     import pandas as pd
     import numpy as np
     from sklearn.cluster import KMeans
     import matplotlib.pyplot as plt   
     from skimage import io, color
     import cv2
     import ipdb
     from sklearn.cluster import AgglomerativeClustering
     xyimg=[]
     # normalizing function
     def debugImg(rawData):
       toShow = np.zeros((rawData.shape), dtype=np.uint8)
       cv2.normalize(rawData, toShow, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
#       cv2.imwrite('img.jpg', toShow)
     print (type(rgbImage))
     def xy(img):
       height = np.size(img, 0)
       width = np.size(img, 1)
       mat=np.zeros((height,width,2))
       mat[::,::,1]=(mat[::,::,1]+np.arange(width)[np.newaxis,:])/width       
       mat[::,::,0]=(mat[::,::,0]+np.arange(height)[:,np.newaxis])/height
       return mat
   
    
     def merge(img,xy):
         im=np.sum(img,axis=-1)
         xysum=np.sum(xy,axis=-1)
         fin=np.add(im,xysum)/5
         return fin
     #resize if it is hierarchical
     if clusteringMethod=='hierarchical':       
#       rgbImage = cv2.resize(rgbImage, (0,0), fx=0.5, fy=0.5) 
       height = np.size(rgbImage, 0)
       width = np.size(rgbImage, 1)
     else:
       height = np.size(rgbImage, 0)
       width = np.size(rgbImage, 1)
     img=rgbImage
     #change to the specified color space
     if colorSpace == "lab":
      img_lab = color.rgb2lab(rgbImage)    
      debugImg(img_lab)
#      l = img_lab[:,:,0]
#      a = img_lab[:,:,1]
#      b = img_lab[:,:,2]
#      sum = l+a+b
#      sum = sum/3
      img =img_lab
     elif colorSpace == "hsv":
      img_hsv = color.rgb2hsv(rgbImage)    
      debugImg(img_hsv)
#      h = img_hsv[:,:,0]
#      s = img_hsv[:,:,1]
#      v = img_hsv[:,:,2]
#      sum = h+s+v
#      sum = sum/3
#      img = sum
      img =img_hsv
     elif colorSpace == "rgb+xy":
      r = rgbImage[:,:,0]
      g = rgbImage[:,:,1]
      b = rgbImage[:,:,2]
#      img_xyz = color.rgb2xyz(rgbImage)
#      x = img_xyz[:,:,0]
#      y = img_xyz[:,:,1]
      xyimg=xy(rgbImage)
      #img = np.concatenate((r,g,b, x, y), axis=0)
#      sum = r+g+b+x+y
#      sum = sum/5
#      img = sum
      
     elif colorSpace == "lab+xy":
      img_lab = color.rgb2lab(rgbImage)    
      debugImg(img_lab)
#      l = img_lab[:,:,0]
#      a = img_lab[:,:,1]
#      b = img_lab[:,:,2]
#      img_xyz = color.lab2xyz(img_lab)
#      x = img_xyz[:,:,0]
#      y = img_xyz[:,:,1]
#      sum = l+a+b+x+y
#      sum = sum/5
#      #img = np.concatenate((l,a,b, x, y), axis=0)
      img = img_lab
      xyimg=xy(img_lab)
     elif colorSpace == "hsv+xy":
      img_hsv = color.rgb2hsv(rgbImage)    
      debugImg(img_hsv)
#      h = img_hsv[:,:,0]
#      s = img_hsv[:,:,1]
#      v = img_hsv[:,:,2]
#      img_xyz = color.hsv2xyz(img_hsv)
#      x = img_xyz[:,:,0]
#      y = img_xyz[:,:,1]
#      #img = np.concatenate((h,s,v, x, y), axis=0)
#      sum = h+s+v+x+y
#      sum = sum/5
#      img = sum
      img=img_hsv
      xyimg=xy(img)
     else:
       img = rgbImage
#       img = color.rgb2gray(img)
     # preparation to classifiers
     
     
     
     
     #proceed to the specified clustering method
     f=img
     img=merge(f,xyimg)
     print(img.shape)
     print(img)
     debugImg(img)
     plt.imshow(img)
     plt.show()
     if clusteringMethod == "kmeans":
       feat = img.reshape(height*width,1)
       kmeans = KMeans(n_clusters=numberOfClusters).fit_predict(feat)
       segmentation = np.reshape(kmeans,(height,width))

     elif clusteringMethod == "gmm":
       from sklearn import mixture
       feat = img.reshape(height*width,1)
       gmm = mixture.GaussianMixture(n_components=numberOfClusters).fit_predict(feat)
       segmentation = np.reshape(gmm,(height,width))

     elif clusteringMethod == "hierarchical":
       feat = img.reshape(height*width,1)
       clustering = AgglomerativeClustering(n_clusters=numberOfClusters).fit_predict(feat)
       segmentation = (np.reshape(clustering,(height,width)))
       print(clustering)
       print(type(clustering[0][0]))
#       segmentation=cv2.resize(segmentation, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)  
     else:
        from skimage import morphology
        from skimage import feature
        import skimage
#        img = color.rgb2gray(img)
        sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
        sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
        # Compute gradient magnitude
        grad_magn = np.sqrt(sobelx**2 + sobely**2)
        debugImg(grad_magn)

        
        import matplotlib.pyplot as plt



        imagenW=grad_magn

        found=1000000
        minimum=found
        while(found>numberOfClusters): 
            imagenW=morphology.h_minima(grad_magn,found)
            _, labeled_fg = cv2.connectedComponents(imagenW.astype(np.uint8))
            labels = morphology.watershed(grad_magn, labeled_fg)
            found=len(np.unique(labels))
            if found==minimum:
              found=numberOfClusters
            if minimum>found:
              minimum=found

            

        plt.figure()
        plt.imshow(labeled_fg)
        print(labeled_fg)



#        superimposed = img.copy()
#        watershed_boundaries = skimage.segmentation.find_boundaries(labels)
#        superimposed[watershed_boundaries] = 255
#        superimposed[foreground_1] = 255
        segmentation = labels
        
 
     return segmentation
Exemplo n.º 3
0
kernel = np.ones((3, 3), np.uint8)

grad = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, kernel)

plt.imshow(grad, cmap="gray")
plt.show()

minimos = [0, 1, 5, 10, 20, 30, 50, 75, 100]

conf = 331

for h in minimos:
    # plt.subplot(conf)
    # plt.title(h)
    markers = morphology.h_minima(grad, h)
    ws = cv2.watershed(grad)
    plt.imshow(ws, cmap="gray")
    plt.show()
    conf += 1

plt.show()

# Generate an initial image with two overlapping circles
x, y = np.indices((80, 80))
x1, y1, x2, y2 = 28, 28, 44, 52
r1, r2 = 16, 20
mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2
mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2
image = np.logical_or(mask_circle1, mask_circle2)
Exemplo n.º 4
0
def IIT(I,sigma,lambdaa,min_mass,h,T_bg,min_hole):
    I_bg=I
    
    
    
    conn=4
    gamma=2
    
    
    
    sig=sigma
    filter_size= 2*np.ceil(3*sig)+1
    hn=(sig**gamma)*fspecial_log(filter_size, sig)
        
    log_map=-conv2(I,hn, 'same','symm')
        
    
    
    I=I+lambdaa*log_map
    
    
    
    
    bin=I>T_bg
    
    
    bin = mass_filt(bin,I_bg+T_bg,min_mass,conn)
    bin = area_filt(bin==0,min_hole)==0
    
    
    
    L=label(bin)
    max_L=np.max(L);
    region_nums=np.arange(max_L)
    
    
    for T in np.arange(T_bg,np.max(I),0.03):
        
        bin=I>T
        
        bin = mass_filt(bin,I_bg+T_bg,min_mass,conn)
        
        s = regionprops(label(bin))
        centroids = np.array([c.centroid for c in s])
    
        centroids=np.round(centroids).astype(np.int)
        
        sz=I.shape
        
        centroids_bin=np.zeros(sz)
        if len(centroids.shape)>1:
            centroids_bin[centroids[:,0],centroids[:,1]]=1
        
        LL=label(bin)
        
        s = regionprops(L,centroids_bin)
        
        cents_num=np.array([c.mean_intensity*c.area for c in s])
        cents_num_tmp=np.zeros(cents_num.shape)
        cents_num_tmp[region_nums]=cents_num[region_nums]>1
        
        region_nums_tmp = np.argwhere(cents_num_tmp)[:,0]
    
    
        for region_num in region_nums_tmp:
            u=np.unique(LL[L==(region_num+1)])
            
            u=u[u>0]
            
            if len(u)>1:
                
                region_nums=np.delete(region_nums,np.argwhere(region_nums==region_num)[:,0])
                
                for k in u:
                    
                    max_L=max_L+1
                    
                    L[LL==k]=max_L
            
                    region_nums=np.append(region_nums,max_L-1)
            
            
    nucs=np.zeros(I.shape)
    for k in region_nums:
        nucs[L==(k+1)]=1
    D=distance_transform_edt(nucs)
    seeds=h_minima(-D, h)
    w=watershed(-D,label(seeds),watershed_line=True)
    nucs_tmp=(nucs>0)&(w>0)
    
    removed=nucs_tmp.astype(np.int)-mass_filt(nucs_tmp,I_bg+T_bg,min_mass,conn).astype(np.int)
    removed=binary_dilation(removed>0,np.ones((3,3),np.int))*nucs
    nucs=(nucs_tmp>0)|(removed>0)
    
    
    w=watershed(-I,label(nucs),watershed_line=True)>0
    bin=I_bg>T_bg
    bin = mass_filt(bin,I_bg+T_bg,min_mass,conn)
    bin = area_filt(bin==0,min_hole)==0
    segm=w*bin
    segm = mass_filt(segm,I_bg+T_bg,min_mass,conn)
    
    
    return segm