コード例 #1
0
def findBvPeaks(gp1_2d_array):
    #bandwidth = 'scott'
    kde = stats.kde.gaussian_kde( ( gp1_2d_array.T[0][:], gp1_2d_array.T[1][:] ))#, bw_method = bandwidth )
    
    div = 128j
    
    # Regular grid to evaluate kde upon
    
    x_flat = np.r_[gp1_2d_array[:,0].min():gp1_2d_array[:,0].max():div]
    y_flat = np.r_[gp1_2d_array[:,1].min():gp1_2d_array[:,1].max():div]
    x,y = np.meshgrid(x_flat,y_flat)
    
    grid_coords = np.append(x.reshape(-1,1),y.reshape(-1,1),axis=1)
    z = kde(grid_coords.T)
    
    div_real = 128
    
    z = z.reshape(div_real,div_real)
    
    #plotDistro(kde,(u_min,u_max),(v_min,v_max),title='')
    
   
    
    limg = np.arcsinh(z)
    limg = limg / limg.max()
    low = np.percentile(limg, 0.25)
    high = np.percentile(limg, 99.9)
    opt_img = skie.exposure.rescale_intensity(limg, in_range=(low,high))
    
    lm = morph.is_local_maximum(limg)
    x1, y1 = np.where(lm.T == True)
    v = limg[(y1, x1)]
    lim = 0.6*high
    
    fp = 13 #smaller odd values are more sensitive to local maxima in image (use roughtly 5 thru 13)
    lm = morph.is_local_maximum(limg,footprint=np.ones((fp, fp)))
    x1, y1 = np.where(lm.T == True)
    v = limg[(y1, x1)]
    
    peaks = [[],[]]
    for idx in range(0,len(x1)):
        if limg[(y1[idx],x1[idx])] > lim: 
            peaks[0].append(x1[idx])
            peaks[1].append(y1[idx])
    
    fig = plt.figure()
    
    img = plt.imshow(opt_img,origin='lower',interpolation='bicubic')#,cmap=cm.spectral)
    ax = fig.add_subplot(111)
    ax.scatter(peaks[0],peaks[1], s=100, facecolor='none', edgecolor = '#009999')

    #plt.savefig(OUTPUT_DATA_DIR + '_peaks.png')
    plt.colorbar()
    plt.show()

    return peaks
コード例 #2
0
def findBivariatePeaks(kde):

    # Regular grid to evaluate kde upon
    x_flat = np.r_[start:end:div]
    y_flat = np.r_[start:end:div]
    x, y = np.meshgrid(x_flat, y_flat)

    grid_coords = np.append(x.reshape(-1, 1), y.reshape(-1, 1), axis=1)
    z = kde(grid_coords.T)
    z = z.reshape(div_real, div_real)

    #fig = plt.figure()
    #i = plt.imshow(z)#,aspect=x_flat.ptp()/y_flat.ptp(),origin='lower')
    #plt.show()

    limg = np.arcsinh(z)
    limg = limg / limg.max()
    low = np.percentile(limg, 0.25)
    high = np.percentile(limg, 99.9)
    opt_img = skie.exposure.rescale_intensity(limg, in_range=(low, high))

    lm = morph.is_local_maximum(limg)
    x1, y1 = np.where(lm.T == True)
    v = limg[(y1, x1)]
    lim = 0.6 * high
    #x2, y2 = x1[v > lim], y1[x > lim]

    peaks = [[], []]
    for idx in range(0, len(x1)):
        if limg[(y1[idx], x1[idx])] > lim:
            peaks[0].append(x1[idx])
            peaks[1].append(y1[idx])

    #print peaks
    #print x_flat[peaks[0]]
    #print y_flat[peaks[1]]

    num_peaks = len(peaks[0])

    peak_distances = []
    max_peak_distance = 0

    peak_vels = []
    peak_probs = []

    for idx in range(0, len(peaks[0][:])):
        peak_vels.append((x_flat[peaks[0][idx]], y_flat[peaks[1][idx]]))
        peak_probs.append(
            kde((x_flat[peaks[0][idx]], y_flat[peaks[1][idx]]))[0])

    if len(peaks[0]) > 1:
        for idx in range(0, len(peaks[0])):
            for idx2 in range(0, len(peaks[1])):
                peak_distances.append(math.sqrt(math.pow(x_flat[peaks[0][idx]]-x_flat[peaks[0][idx2]],2) \
                                       + math.pow(y_flat[peaks[1][idx]] - y_flat[peaks[1][idx2]],2)))
        max_peak_distance = max(peak_distances)
        print " %%max peak dist%% = " + str(max_peak_distance)

    return peak_vels, peak_probs, max_peak_distance
コード例 #3
0
ファイル: HW3.py プロジェクト: rrawat/AY250
def contour_features(im):
	"""features 19- 24; contours of the image: number of contours in the image, mean of distance to background, and local maxima:pixel ratio"""

	contours=[]

	x_size=int(im.size[1]/float(10))
	i=im.resize((x_size,int((im.size[0]/float(im.size[1])*x_size))))
		
	x=i.getdata()
	z=np.array(x)
	if z.size/(len(z))==1:
		if z.size%3 !=0:
			z= z[0:len(z)-len(z)%3]
		z= z.reshape(-1,3)

		#print z.resize(z.size/float(3),3)
		#print z
	#contour mapping	
	contour_array=measure.find_contours(z,0.5)
	len_contours=contours.__len__()
	
	contours.append(len_contours)

# 19-21: distance features: use ndimage.distance to compute "distance" to background of each pixel. Then find mean among x, y, and z values (r,g,b) 
	
	distance=ndimage.distance_transform_edt(z)
	yvaluemean= sum(distance[:,0])/len(distance[:,0])
	xvaluemean= sum(distance[:,1])/len(distance[:,1])
	zvaluemean= sum(distance[:,2])/len(distance[:,2])
					

	contours.append(yvaluemean)
	contours.append(xvaluemean)
	contours.append(zvaluemean)

#22-24: local_max features: find number of local maxima among x,y,z values (rgb) compared to the number of pixels
	
	local_max=is_local_maximum(distance,z,np.ones((3,3)))	
	xmaxsum, ymaxsum, zmaxsum = [0,0,0]
	for a in (local_max[:,0]):
		if a ==False:
			xmaxsum+=1
	contours.append(xmaxsum/float(len(local_max[:,0])))
	for a in (local_max[:,1]):
		if a ==False:
			ymaxsum+=1
	contours.append(ymaxsum/float(len(local_max[:,0])))
	for a in (local_max[:,2]):
		if a ==False:
			zmaxsum+=1
	contours.append(zmaxsum/float(len(local_max[:,0])))

###25: object count
	filt_img=ndimage.gaussian_filter(z,10)
	T=70
	labeled,nr_objects=ndimage.label(filt_img>T)
	contours.append(nr_objects)

	return contours
from skimage.morphology import watershed, is_local_maximum
import matplotlib.pyplot as plt
from scipy import ndimage

# 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)
# Now we want to separate the two objects in image
# Generate the markers as local maxima of the distance
# to the background
distance = ndimage.distance_transform_edt(image)
local_maxi = is_local_maximum(distance, image, np.ones((3, 3)))
markers = ndimage.label(local_maxi)[0]
labels = watershed(-distance, markers, mask=image)

plt.figure(figsize=(9, 3.5))
plt.subplot(131)
plt.imshow(image, cmap='gray', interpolation='nearest')
plt.axis('off')
plt.subplot(132)
plt.imshow(-distance, interpolation='nearest')
plt.axis('off')
plt.subplot(133)
plt.imshow(labels, cmap='spectral', interpolation='nearest')
plt.axis('off')

plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0,
コード例 #5
0
bkg = func(grid_x, grid_y)
bkg = bkg / np.max(bkg)

# Creating points
clean = np.zeros((200, 400))
clean[(x, y)] += 5
clean = ndimage.gaussian_filter(clean, 3)
clean = clean / np.max(clean)

# Combining both the non-uniform background
# and points
fimg = bkg + clean
fimg = fimg / np.max(fimg)

# Calculating local maxima
lm1 = morph.is_local_maximum(fimg)
x1, y1 = np.where(lm1.T == True)

# Creating figure to show local maximum detection
# rate success
fig = plt.figure(figsize=(8, 4))

ax = fig.add_subplot(111)
ax.imshow(fimg)
ax.scatter(x1, y1, s=100, facecolor='none', edgecolor='#009999')
ax.set_xlim(0, 400)
ax.set_ylim(0, 200)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

fig.savefig('scikits_412_ex1.png', bbox_inches='tight')
コード例 #6
0
import matplotlib.pyplot as plt
from skimage.morphology import watershed, is_local_maximum

# 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)

# Now we want to separate the two objects in image
# Generate the markers as local maxima of the distance to the background
from scipy import ndimage
distance = ndimage.distance_transform_edt(image)
local_maxi = is_local_maximum(distance, image, np.ones((3, 3)))
markers = ndimage.label(local_maxi)[0]
labels = watershed(-distance, markers, mask=image)

fig, axes = plt.subplots(ncols=3, figsize=(8, 2.7))
ax0, ax1, ax2 = axes

ax0.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
ax1.imshow(-distance, cmap=plt.cm.jet, interpolation='nearest')
ax2.imshow(labels, cmap=plt.cm.spectral, interpolation='nearest')

for ax in axes:
    ax.axis('off')

plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)
plt.show()
コード例 #7
0
bkg = func(grid_x, grid_y)
bkg = bkg / np.max(bkg)

# Creating points
clean = np.zeros((200, 400))
clean[(x, y)] += 5
clean = ndimage.gaussian_filter(clean, 3)
clean = clean / np.max(clean)

# Combining both the non-uniform background
# and points
fimg = bkg + clean
fimg = fimg / np.max(fimg)

# Calculating local maxima
lm1 = morph.is_local_maximum(fimg)
x1, y1 = np.where(lm1.T == True)

# Creating figure to show local maximum detection
# rate success
fig = plt.figure(figsize=(8, 4))

ax = fig.add_subplot(111)
ax.imshow(fimg)
ax.scatter(x1, y1, s=100, facecolor="none", edgecolor="#009999")
ax.set_xlim(0, 400)
ax.set_ylim(0, 200)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

fig.savefig("scikits_412_ex1.pdf", bbox_inches="tight")
コード例 #8
0
ファイル: hole_detector.py プロジェクト: softtrainee/arlab
        def test_target(tar):
            '''
                if the convexity of the target is <threshold try to do a watershed segmentation
                
                make black image with white polygon
                do watershed segmentation
                find polygon center
                
            '''
            def test(ti):
                ctest = ti.convexity > threshold
                centtest = self._near_center(*ti.centroid_value)
                atest = ma > ti.area > mi
                return ctest, centtest, atest

            ctest, centtest, atest = test(tar)
            if not ctest and (atest and centtest):
#                src = self.target_image.get_frame(0)
#                self._draw_result(src, tar)
#                w, h = self.croppixels
#                self.target_image.save('/Users/ross/Sandbox/machine_vision/polygon.jpg', width=w, height=h)

                src = self.target_image.get_frame(0)
                draw_polygons(src, [tar.poly_points], color=(0, 255, 255))

                # make image with polygon
                image = zeros(self.croppixels)
                points = asarray(tar.poly_points)

                points = asarray([(pi.x, pi.y) for pi in points])
                rr, cc = polygon(points[:, 0], points[:, 1])

                image[cc, rr] = 255

                # do watershedding
                distance = ndimage.distance_transform_edt(image)
                local_maxi = is_local_maximum(distance, image)
                markers, ns = ndimage.label(local_maxi)
                wsrc = watershed(-distance, markers,
                                  mask=image
                                 )

                # find the label with the max area ie max of histogram
                def get_limits(values, bins):
                    ind = argmax(values)
                    if ind == 0:
                        bil = bins[ind]
                        biu = bins[ind + 1]
                    elif ind == len(bins) - 1:
                        bil = bins[ind - 1]
                        biu = bins[ind]
                    else:
                        bil = bins[ind - 1]
                        biu = bins[ind + 1]

                    return bil, biu, ind

                # bins = 3 * number of labels. this allows you to precisely pick the value of the max area
                values, bins = histogram(wsrc, bins=ns * 3)
                bil, biu, ind = get_limits(values, bins)

                if not bil:
                    values = delete(values, ind)
                    bins = delete(bins, (ind, ind + 1))
                    bil, biu, ind = get_limits(values, bins)

#                print values
#                print bins
#                print bil, biu

                nimage = ones_like(wsrc, dtype='uint8')
                nimage[wsrc < bil] = 0
                nimage[wsrc > biu] = 0

                img = asMat(nimage)

                # locate new polygon from the segmented image
                tars = self._locate_targets(img)
                if globalv.show_autocenter_debug_image:
                    do_later(lambda: self.debug_show(image, distance, wsrc, nimage))

                if tars:
                    tar = tars[0]
                    ctest, centtest, atest = test(tar)
#                    ctest = tar.convexity > threshold
#                    centtest = self.
                else:
                    return None, False

            return tar, ctest and atest and centtest
コード例 #9
0
                    peak_distances = []
                    for idx in range(0,len(contour_centroids)):
                        for idx2 in range(0,len(contour_centroids)):
                            peak_distances.append(math.sqrt(math.pow(contour_centroids[idx][0]-contour_centroids[idx2][0],2) \
                                                   + math.pow(contour_centroids[idx][1] - contour_centroids[idx2][1],2)))
                    '''

                    limg = np.arcsinh(z)
                    limg = limg / limg.max()
                    low = np.percentile(limg, 0.25)
                    high = np.percentile(limg, 99.9)
                    opt_img = skie.exposure.rescale_intensity(limg,
                                                              in_range=(low,
                                                                        high))

                    lm = morph.is_local_maximum(limg)
                    x1, y1 = np.where(lm.T == True)
                    v = limg[(y1, x1)]
                    lim = 0.6 * high
                    #x2, y2 = x1[v > lim], y1[x > lim]

                    peaks = [[], []]
                    for idx in range(0, len(x1)):
                        if limg[(y1[idx], x1[idx])] > lim:
                            peaks[0].append(x1[idx])
                            peaks[1].append(y1[idx])

                    print peaks

                    peak_distances = []
                    for idx in range(0, len(peaks)):
コード例 #10
0
import skimage.morphology as morph
import skimage.exposure as skie
import matplotlib.pyplot as plt

# Loading astronomy image from an infrared space telescope
img = pyfits.getdata('stellar_cluster.fits')[500:1500, 500:1500]

# Prep file scikit-image environment and plotting
limg = np.arcsinh(img)
limg = limg / limg.max()
low = np.percentile(limg, 0.25)
high = np.percentile(limg, 99.5)
opt_img = skie.exposure.rescale_intensity(limg, in_range=(low, high))

# Calculating local maxima and filtering out noise
lm = morph.is_local_maximum(limg)
x1, y1 = np.where(lm.T == True)
v = limg[(y1, x1)]
lim = 0.5
x2, y2 = x1[v > lim], y1[v > lim]

# Creating figure to show local maximum detection
# rate success
fig = plt.figure(figsize=(8, 4))
fig.subplots_adjust(hspace=0.05, wspace=0.05)

ax1 = fig.add_subplot(121)
ax1.imshow(opt_img)
ax1.set_xlim(0, img.shape[1])
ax1.set_ylim(0, img.shape[0])
ax1.xaxis.set_visible(False)
コード例 #11
0
    if seg == 'edge detection':
	    # perform edge detection. Different edge filters are available in Python, here the Sobel filter is used
        edges = sobel(image)
        # threshold edges to select only strong contours (NB: intensity values (0-255) are normalized between 0 and 1)
        image_segmented = edges > 0.1
 
	# fill potential holes in segmented objects
    image_segmented_filled = nd.binary_fill_holes(image_segmented)
	
    #watershed segmentation to split touching objects, if activated in the user's section	
    if ws == '_ws_':
        # distance map is created where the distance of each foreground pixel to the closest background pixel is calculated and used for watershed splitting
        distance = nd.distance_transform_edt(image_segmented_filled)
		# apply Gaussian filter to the distance map to merge several local maxima into one
        distance=nd.gaussian_filter(distance,4)
        local_maxi = is_local_maximum(distance, labels=image_segmented_filled, footprint=np.ones((3, 3)))
        markers = nd.label(local_maxi)[0]
		# return labelled image (array of unique integers per object)
        labelled_image = watershed(-distance, markers, mask=image_segmented_filled)

# 2b. WATERSHED SPLIT
#--------------------

    # return labelled image (array of unique integers per object)
    if ws != '_ws_':
        labelled_image, nb_labels = nd.label(image_segmented_filled)

# 3. MEASURE OBJECT PROPERTIES AND CONDUCT SIZE-BASED EXCLUSION
#--------------------------------------------------------------
		
    # measure object size on labelled image