Exemplo n.º 1
0
 def segmentTubes2(img_labeled, img_intensity):
     """
     Parameters
     ==========
     :img_labeled: labeled image before segmentation  
     
     img_intensity: intensity image  
     
     Returns
     =======
     labeld image segmented by Otsu's binarization by each region.  
     * This function do not perform histogram equalization by each region.  
     If you want to do that before the segmentation, use 'segementation1' function.
     """
     img_seg = np.zeros_like(img_intensity)
     labels = np.unique(img_labeled.flatten())
     for cell_id in labels[1:]:
         bin_region = (img_labeled == cell_id)
         region = bin_region * img_intensity
         region, _ = imtools.histeq(region)
         # segmentation
         T = otsu(np.uint(region), ignore_zeros=True)
         img_seg += (np.uint(region) > T)
     labeled, counts = label(img_seg)
     return labeled, counts
Exemplo n.º 2
0
def test3():
    im = array(
        Image.open(data_path + 'AquaTermi_lowcontrast.JPG').convert('L'))
    im2, cdf = imtools.histeq(im)

    figure()

    subplot(321)
    hist(im.flatten(), 128)

    subplot(322)
    hist(im2.flatten(), 128)

    subplot(323)
    imshow(im)
    gray()

    subplot(324)
    imshow(im2)
    gray()

    print cdf.shape
    subplot(325)
    plot(cdf)

    show()
Exemplo n.º 3
0
def process_image(imagename, resultname, histeq=False,
                  params='--edge-thresh 10 --peak-thresh 5'):
  if not imagename.endswith('pgm') or histeq:
    im = Image.open(imagename).convert('L')
    if histeq:
      import imtools
      im = Image.fromarray(numpy.uint8(imtools.histeq(numpy.array(im))[0]))
    im.save('out_tmp.pgm')
    imagename = 'out_tmp.pgm'

  # Assumes that vlfeat's sift binary is in PATH.
  cmd = ' '.join(['sift', imagename, '--output=' + resultname, params])
  os.system(cmd)

  # Re-write as .mat file, which loads faster.
  f = numpy.loadtxt(resultname)
  sio.savemat(resultname + '.mat', {'f':f}, oned_as='row')
Exemplo n.º 4
0
def process_image(imagename,
                  resultname,
                  histeq=False,
                  params='--edge-thresh 10 --peak-thresh 5'):
    if not imagename.endswith('pgm') or histeq:
        im = Image.open(imagename).convert('L')
        if histeq:
            import imtools
            im = Image.fromarray(
                numpy.uint8(imtools.histeq(numpy.array(im))[0]))
        im.save('out_tmp.pgm')
        imagename = 'out_tmp.pgm'

    # Assumes that vlfeat's sift binary is in PATH.
    cmd = ' '.join(['sift', imagename, '--output=' + resultname, params])
    os.system(cmd)

    # Re-write as .mat file, which loads faster.
    f = numpy.loadtxt(resultname)
    sio.savemat(resultname + '.mat', {'f': f}, oned_as='row')
  def fitSky(center, distances, pa, ba, img, mask, name):
    #limit = findClosestEdge(distances, center)
    band = Settings.getConstants().band
    #start = Photometry.getStart(CALIFA_ID) - 500
    start = 10
    radius = 30
    step = 5
    fluxSlopeM = -10 #init
    fluxSlope = -10
    while fluxSlopeM < 0:
      fluxData = Photometry.growEllipses(img, distances, center, start, start+radius, pa, ba, mask)
      #fitting unmasked
      xi = fluxData[:, 0] #isoA
      A = np.array([xi, np.ones(len(fluxData))])
      y = np.divide(fluxData[:, 1], fluxData[:, 2]) #flux ppx
      #print np.mean(y), start
      w = np.linalg.lstsq(A.T,y)[0] # obtaining the parameters
      fluxSlope = w[0]
      line = w[0]*xi+w[1] # regression line
      #print fluxSlope, 'slope'
      #fitting masked
      #print 'fitting masked'
      xi = fluxData[:, 0] #isoA
      A = np.array([xi, np.ones(len(fluxData))])
      yM = np.divide(fluxData[:, 3],fluxData[:, 4]) #flux ppx

      w = np.linalg.lstsq(A.T,yM)[0] # obtaining the parameters
      fluxSlopeM = w[0]
      #print np.mean(yM), np.mean(y), start, fluxSlope, np.sum(fluxData[:, 2]), np.sum(fluxData[:, 4])  
      line = w[0]*xi+w[1] # regression line
      print fluxSlopeM, 'slope', start+radius
      start = start + step
    img_c = img.copy()
    currentPixels = ellipse.draw_ellipse(img.shape, center[0], center[1], pa, start-step, ba)
    img_c[currentPixels] = 10
    img_c, cdf = imtools.histeq(img_c)
        
    scipy.misc.imsave('vimos/img/snapshots/'+band+"/"+name+'.png', img_c)         
    return np.mean(y), fluxSlope, np.mean(yM), fluxSlopeM, fluxData[-1, 0]
Exemplo n.º 6
0
 def segmentTubes3(img_labeled, img_intensity):
     """
     Parameters
     ==========
     :img_labeled: labeled image before segmentation  
     
     img_intensity: intensity image  
     
     Returns
     =======
     labeld image segmented by mean-intensity by each region.
     * This function perform histogram equalization by each region before segmentation. 
     """
     img_seg = np.zeros_like(img_intensity)
     labels = np.unique(img_labeled.flatten())
     for cell_id in labels[1:]:
         bin_region = (img_labeled == cell_id)
         region = bin_region * img_intensity
         region, _ = imtools.histeq(region)
         # segmentation
         T = np.mean(np.ma.masked_equal(region, 0))
         img_seg += (region > T)
     labeled, counts = label(img_seg)
     return labeled, counts
subplot(232)
title('当前值域%d', fontproperties=font)
imshow(rev_im)

im3 = (100 / 255) * im + 100
subplot(233)
title(u'试试', fontproperties=font)
imshow(im3)

im4 = (im / 255)**2 * 255
subplot(234)
imshow(im4)  #对像素值求平方后得到的图像
##---------------------------------------------------------------------------------
#直方图均衡化
import imtools


def histeq(im, nbr_bins=256):
    imhist, bins = histogram(im.flatten(), nbr_nbins, normed=True)
    cdf = imhist.cumsum()
    cdf = 255 * cdf / cdf[-1]
    im2 = interp(im.flatten(), bins[:-1], cdf)
    return im2.reshape(im.shape), cdf


im2, cdf = imtools.histeq(im)
subplot(235)
hist(im2.flatten(), 128, normed=true)

show()
Exemplo n.º 8
0
#coding: utf-8
'''
Created on 2015年7月23日

@author: Administrator
'''
from PIL import Image
from numpy import *
import imtools
from pylab import *
from matplotlib.pyplot import show, imshow, figure
im = array(Image.open('sunset.jpg').convert('L'))
im2,cdf = imtools.histeq(im)
im2=255.0*(im2/255.0)**2
gray()
imshow(im2)
figure()
hist(im.flatten(),128)
show()
Exemplo n.º 9
0
    imshow(im)
    subplot(222)
    title('Histogram of red color')
    hist(im[:, :, 0].flatten(), bins=256)  #红色通道直方图
    subplot(223)
    title('Histogram of green color')
    hist(im[:, :, 1].flatten(), bins=256)  #绿色通道直方图
    subplot(224)
    title('Histogram of blue color')
    hist(im[:, :, 2].flatten(), bins=256)  #蓝色通道直方图


im = imread('handsome.jpg')
showImage(im)  #显示图像和直方图
#分别调整r、g、b通道的对比度
red, rcdf = imtools.histeq(im[:, :, 0])
green, gcdf = imtools.histeq(im[:, :, 1])
blue, bcdf = imtools.histeq(im[:, :, 2])
#将调整后的值赋值给原图像
im[:, :, 0] = red
im[:, :, 1] = green
im[:, :, 2] = blue
showImage(im)  #显示图像和直方图
#绘制cdf曲线
figure()
subplot(311)
plot(rcdf / 255)  #重新归一化cdf的值域范围为[0,1]之间
subplot(312)
plot(gcdf / 255)  #重新归一化cdf的值域范围为[0,1]之间
subplot(313)
plot(bcdf / 255)  #重新归一化cdf的值域范围为[0,1]之间
Exemplo n.º 10
0
hist(pil_img.flatten(),128)
show()
figure(3)
im2 = 255 - pil_img
im3=(100/255.0)*pil_img+100
im4 = 255.0*(pil_img/255.0)**2
subplot(221)
imshow(pil_img,cmap=cm.Greys_r)
subplot(222)
imshow(im2,cmap=cm.Greys_r)
subplot(223)
imshow(im3,cmap=cm.Greys_r)
subplot(224)
imshow(im4,cmap=cm.Greys_r)
figure(4)
im5,cdf = imtools.histeq(pil_img)
subplot(221)
imshow(pil_img,cmap=cm.Greys_r)
subplot(222)
imshow(im5,cmap=cm.Greys_r)
subplot(223)
plot(cdf)
###########################################################
close("all")
# pca
imlist = imtools.get_imlist('gwb_cropped')
im = array(Image.open(imlist[0]))
m,n = im.shape[0:2]
imnbr = len(imlist)

immatrix = array([array(Image.open(im)).flatten() for im in imlist],'f')
  def calculateGrowthCurve(listFile, dataDir, i):
    CALIFA_ID = str(i+1)
    inputImage = Photometry.getInputFile(listFile, dataDir, i)
    dbDir = '../db/'
    imgDir = 'img/'+setBand()+'/'
    center = Photometry.getCenter(listFile, i, dataDir)
    distances = Photometry.createDistanceArray(listFile, i, dataDir)
    #hdu = pyfits.PrimaryHDU(distances)
    #hdu.writeto('distances.fits')
    sky = inputImage[np.where(distances > int(round(Photometry.iso25D)))]
    skyMean = np.mean(sky)   
    skySD = np.std(sky)
    #i+1 in the next line reflects the fact that CALIFA id's start with 1
    pa = db.dbUtils.getFromDB('PA', dbDir+'CALIFA.sqlite', 'nadine', ' where califa_id = '+ CALIFA_ID)[0][0]  #parsing tuples
    ba = db.dbUtils.getFromDB('ba', dbDir+'CALIFA.sqlite', 'nadine', ' where califa_id = '+ CALIFA_ID)[0][0]#parsing tuples
    #ba = 1
    #r_mag = db.dbUtils.getFromDB('r_mag', dbDir+'CALIFA.sqlite', 'nadine', ' where califa_id = '+ CALIFA_ID)[0][0]#parsing tuples
    #r_e = db.dbUtils.getFromDB('re', dbDir+'CALIFA.sqlite', 'nadine', ' where califa_id = '+ CALIFA_ID)[0][0]#parsing tuples
    #lucy_re = db.dbUtils.getFromDB('re', dbDir+'CALIFA.sqlite', 'lucie', ' where id = '+ CALIFA_ID)[0][0]#parsing tuples
    #l_SkyMean = db.dbUtils.getFromDB('sky', dbDir+'CALIFA.sqlite', 'lucie', ' where id = '+ CALIFA_ID)[0][0] - 1000#parsing tuples
 #   print 'ba', ba
    
    #fluxData = Photometry.buildGrowthCurve(inputImage, center, distances, skyMean, pa, ba)
    #isoA = fluxData.shape[0]

  
    # --------------------------------------- starting GC photometry in circular annuli
    print 'CIRCULAR APERTURE'
    #circFlux, circFluxData = Photometry.circularFlux(inputImage, center,  distances, skyMean)  
    circFlux, circFluxData, gc_sky = Photometry.buildGrowthCurve(inputImage, center, distances, skyMean, pa, 1, str(i+1))
    circRadius = circFluxData.shape[0]
    #print circRadius, 'circle radius'
    #otherFlux = circFluxData[-1, 1]   
    #print 'fluxes: mask:', circFlux, 'sum', otherFlux    
    try:
    	    circHLR = circFluxData[np.where(np.floor(circFlux/circFluxData[:,1]) == 1)][0][0] - 1 #Floor() -1 -- last element where the ratio is 2
    except IndexError as e:
    	    circHLR = str(e)
	    
    circMag = Photometry.calculateFlux(circFlux, listFile, i)
    
    
    # --------------------------------------- starting ellipse GC photometry

    print 'ELLIPTICAL APERTURE'
    totalFlux, fluxData, gc_sky = Photometry.buildGrowthCurve(inputImage, center, distances, skyMean, pa, ba, CALIFA_ID, e=True)  
    
    otherFlux = fluxData[fluxData.shape[0]-1, 6]   
   
    elMajAxis = fluxData.shape[0]
    #print totalFlux - otherFlux, 'flux diff'
    #print 't', totalFlux, 'o', otherFlux
    diff = [CALIFA_ID, totalFlux - otherFlux]
    utils.writeOut(diff, 'fluxdiff.txt')
    elMag = Photometry.calculateFlux(totalFlux, listFile, i)
    
    try:
	elHLR = fluxData[np.where(np.floor(totalFlux/fluxData[:, 1]) == 1)][0][0] - 1 #Floor() -1 -- last element where the ratio is 2
	print elHLR  
    except IndexError as e:
        print 'err'
	elHLR = e
    
    plotGrowthCurve.plotGrowthCurve(fluxData, CALIFA_ID)
 	
    
    # --------------------- writing output jpg file with both outermost annuli  
    outputImage = inputImage
    circpix = ellipse.draw_ellipse(inputImage.shape, center[0], center[1], pa, circRadius, 1)
    elPix = ellipse.draw_ellipse(inputImage.shape, center[0], center[1], pa, elMajAxis, ba)    
    outputImage[circpix] = 0
    outputImage[elPix] = 0
    
    outputImage, cdf = imtools.histeq(outputImage)
        
    #scipy.misc.imsave('img/output/'+CALIFA_ID+'.jpg', outputImage)    
    scipy.misc.imsave(imgDir+'snapshots/'+CALIFA_ID+'_gc.jpg', outputImage)

    #hdu = pyfits.PrimaryHDU(outputImage)
    #outputName = 'CALIFA'+CALIFA_ID+'.fits'
    #hdu.writeto(outputName) 
    

    
    # ------------------------------------- formatting output row
    output = [CALIFA_ID, elMag, elHLR, circMag, circHLR, np.mean(sky),  gc_sky] 
    print output
    #print skyMean, oldSky, 'sky'
    return output
Exemplo n.º 12
0
from PIL import Image
from matplotlib import pyplot as plt
import imtools
import numpy as np

# SET ALL PLOTS TO GRAY
plt.gray()

im = np.array(Image.open('empire.jpg').convert('L'))

im_eq, cdf = imtools.histeq(im)

plt.figure(6)
plt.imshow(im_eq)

plt.figure(7)
plt.hist(im_eq.flatten(), 128)

plt.figure(8)
plt.hist(im.copy().flatten(), 128)

#invert image
im2 = 255 - im
 
# Clamp to interval 100....200
im3 = (100.0/255.0) * im + 100 

# squared (This is a quadratic function that lowers values of darker pixels)
im4 = 255.0 * (im/255.0)**2

print(im)
  def buildGrowthCurve(center, distances, pa, ba, CALIFA_ID):
		band = Settings.getConstants().band
		sky = Settings.getSkyFitValues(str(CALIFA_ID)).sky
		isoA_max = Settings.getSkyFitValues(str(CALIFA_ID)).isoA			
		inputImage = Photometry.getInputFile(int(CALIFA_ID) - 1, band)
		#masked input array
		mask = Photometry.getMask(int(CALIFA_ID)-1)
		mask = getCroppedMask(mask, int(CALIFA_ID)-1)
		inputImageM = np.ma.masked_array(inputImage, mask=mask)
		ellipseMask = np.zeros((inputImage.shape), dtype=np.uint8)
		ellipseMaskM = ellipseMask.copy()
		fluxData = Photometry.initFluxData(inputImage, center, distances)
		#currentPixels = center
		#currentFlux = inputImage[center] 

		Npix = 1 #init
		growthSlope = 200 #init
		for isoA in range(1, int(isoA_max)+1):

		  #draw ellipse for all pixels:
		  currentPixels = ellipse.draw_ellipse(inputImage.shape, center[0], center[1], pa, isoA, ba)
		  #Npix = inputImage[currentPixels].shape[0]
		  #currentFlux = np.sum(inputImage[currentPixels])
		  ellipseMask[currentPixels] = 1
		  Npix = inputImage[currentPixels].shape[0]

		  #draw ellipse for masked pixels only:
		  currentPixelsM = ellipse.draw_ellipse(inputImageM.shape, center[0], center[1], pa, isoA, ba)
		  ellipseMaskM[currentPixelsM] = 1
		  maskedPixels = inputImageM[np.where((ellipseMaskM == 1) & (mask == 0))]
		  
		  #NpixM = inputImageM[currentPixelsM].compressed().shape[0]
		  #currentFluxM = np.sum(inputImageM.filled(0)[currentPixelsM])	
		  #print Npix - NpixM, currentFlux-currentFluxM
		  
		  #growthSlope = utils.getSlope(oldFlux, currentFlux, isoA-1, isoA)
		  #print 'isoA', isoA

		  fluxData[isoA, 0] = isoA
		  fluxData[isoA, 1] = np.sum(inputImage[np.where(ellipseMask == 1)])# cumulative flux
		  fluxData[isoA, 2] = inputImage[np.where(ellipseMask == 1)].shape[0]

		  fluxData[isoA, 3] = np.sum(maskedPixels)# cumulative flux, without masked pixels
		  fluxData[isoA, 4] = maskedPixels.shape[0]
		  #print Npix, NpixM, fluxData[isoA, 2], fluxData[isoA, 4]
		  isoA = isoA +1
		  #gc_sky = np.mean(fluxData[isoA-width:isoA-1, 2])
		#flux = np.sum(inputImage[np.where(ellipseMask == 1)]) - sky*inputImage[np.where(ellipseMask == 1)].shape[0]	
		fluxData = fluxData[0:isoA-1,:] #the last isoA value was incremented, so it should be subtracted
		#fluxData[:, 1] = fluxData[:, 1] - sky*fluxData[:, 5]#cumulative flux, _sky_subtracted
		#fluxData[:, 3] = fluxData[:, 3] - sky*fluxData[:, 4]
		#fluxData[:, 2] = fluxData[:, 2] - sky #sky-subtracted flux per pixel
		  #print inputImage[np.where(ellipseMask == 1)].shape[0], '***************************************'
		  # --------------------------------------- writing an ellipse of counted points, testing only
		
		#hdu = pyfits.PrimaryHDU(ellipseMask)
		#hdu.writeto('masks/ellipseMask'+CALIFA_ID+'.fits', clobber=True)
		    # --------------------- writing output jpg file with both outermost annuli  
		outputImage = inputImage
		elPix = ellipse.draw_ellipse(inputImage.shape, center[0], center[1], pa, isoA-1, ba)    
		outputImage[elPix] = 0	
		outputImage, cdf = imtools.histeq(outputImage)
		scipy.misc.imsave('img/2/snapshots/'+band+"/"+CALIFA_ID+'.jpg', outputImage)
		np.savetxt('growth_curves/2/'+Settings.getConstants().band+'/gc_profile'+CALIFA_ID+'.csv', fluxData)	
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
import imtools

im = np.array(Image.open('building.jpg').convert('L'))
im2,cdf,cdf2 = imtools.histeq(im)

plt.figure(1)
plt.subplot(131), plt.hist(im.flatten(), 256, normed=True)
plt.title('histogram of original image'), plt.xlabel('pixel depth') 
plt.ylabel('frequency')
plt.subplot(132), plt.plot(cdf)
plt.title('cdf')
plt.subplot(133), plt.plot(cdf2)
plt.title('normalized cdf')

plt.figure(2)
plt.subplot(121), plt.imshow(im, cmap='gray'), plt.axis('off')
plt.title('original image')
plt.subplot(122), plt.imshow(im2, cmap='gray'), plt.axis('off')
plt.title('processed image')
plt.show()

Exemplo n.º 15
0
from PIL import Image
from numpy import *
import imtools

# read image to array
im = array(Image.open('data/empire.jpg'))
print im.shape, im.dtype

im = array(Image.open('data/empire.jpg').convert('L'), 'f')
print im.shape, im.dtype

im = array(Image.open('data/empire.jpg').convert('L'))

# invert image
im2 = 255 - im

# clamp to interval 100...200
im3 = (100.0 / 255) * im + 100

# squared
im4 = 255.0 * (im / 255.0)**2

print int(im4.min()), int(im4.max())

# ====================================
im = array(Image.open('data/AquaTermi_lowcontrast.JPG').convert('L'))
im5, cdf = imtools.histeq(im)
Exemplo n.º 16
0
from PIL import Image
import matplotlib.pyplot as plt
from pylab import array, histogram, interp

import imtools


def showImage(im):
    # create a image in plt
    plt.figure()
    # no color
    plt.gray()
    # show image from left
    plt.contour(im, origin='image')

    plt.axis('equal')
    plt.axis('off')
    plt.figure()
    plt.hist(im.flatten(), 128)


# convert to gray and read into array
im = array(Image.open(imtools.imagePath('test.jpg')).convert('L'))
showImage(im)

im1 = array(Image.open(imtools.imagePath('test.jpg')).convert('L'))
a = im1.flatten()
im2, cdf = imtools.histeq(a, im1, 256)

showImage(im2)
plt.show()
Exemplo n.º 17
0
__author__ = '7times6'
import imtools
from PIL import Image
import numpy as np
import pylab as mp

filename = 'center_stan.jpg'
im = np.array(Image.open(filename).convert('L'))
im_he, cdf = imtools.histeq(im)

mp.gray()
mp.figure()
mp.imshow(im)
mp.title('Original')

mp.figure()
mp.imshow(im_he)
mp.title('Equalized')
mp.show()

Image.fromarray(np.uint8(im_he)).save('eq_' + filename)
Exemplo n.º 18
0
from imtools import histeq
from PIL import Image
from numpy import *
import os
import sys

sys.path.append('C:\\Project\\Python\\Image Recognition\\cp1')

im = array(Image.open('../data/AquaTermi_lowcontrast.jpg').convert('L'))
im2, cdf = histeq(im)
Exemplo n.º 19
0
    def detectMyotube(self,
                      segmentationMethod='seg1',
                      sizeThresh=0,
                      tophat=True,
                      tophatImgList=[]):
        if tophat == True and tophatImgList == []:
            tophatImgList = self.tophatAllPlanes()
        elif tophat == True and tophatImgList != []:
            #tophatImgList = tophatImgList[tophatImgList.keys()[0]]
            tophatImgList = tophatImgList[0]
        elif tophat == False:
            tophatImgList = self.images

        # median -> histeq -> otsu -> segmentation (histeq and otsu by region)
        if segmentationMethod == 'seg1':
            img_mip = self.maximumIntensityProjection(tophatImgList)
            img_median = self.smooth(img_mip)
            img_histeq, _ = imtools.histeq(img_median)
            T = otsu(np.uint(img_histeq), ignore_zeros=True)
            img_bin = (np.uint(img_histeq) > T)
            img_labeled, _ = label(img_bin)
            markers, counts = self.segmentTubes1(img_labeled, img_histeq)
            # segmentation by watershed
            img_labeled = img_bin * cwatershed(-distance(img_bin), markers)
            result = {
                'MIP': img_mip,
                'median': img_median,
                'histEq': img_histeq,
                'otsu': T,
                'bin': img_bin
            }

        # median -> otsu -> segmentation (histeq and otsu by region)
        elif segmentationMethod == 'seg2':
            img_mip = self.maximumIntensityProjection(tophatImgList)
            img_median = self.smooth(img_mip)
            T = otsu(np.uint(img_median), ignore_zeros=True)
            img_bin = (np.uint(img_median) > T)
            img_labeled, _ = label(img_bin)
            markers, counts = self.segmentTubes2(img_labeled, img_median)
            # segmentation by watershed
            img_labeled = img_bin * cwatershed(-distance(img_bin), markers)
            result = {
                'MIP': img_mip,
                'median': img_median,
                'otsu': T,
                'bin': img_bin
            }

        # median -> histeq -> otsu -> segmentation (histeq and cut regions less than mean-intensity by region)
        elif segmentationMethod == 'seg3':
            img_mip = self.maximumIntensityProjection(tophatImgList)
            img_median = self.smooth(img_mip)
            img_histeq, _ = imtools.histeq(img_median)
            T = otsu(np.uint(img_histeq), ignore_zeros=True)
            img_bin = (np.uint(img_histeq) > T)
            img_labeled, _ = label(img_bin)
            markers, counts = self.segmentTubes3(img_labeled, img_histeq)
            # segmentation by watershed
            img_labeled = img_bin * cwatershed(-distance(img_bin), markers)
            result = {
                'MIP': img_mip,
                'median': img_median,
                'histEq': img_histeq,
                'otsu': T,
                'bin': img_bin
            }

        # median -> histeq -> otsu -> segmentation (cut regions less than mean-intensity by region)
        elif segmentationMethod == 'seg4':
            img_mip = self.maximumIntensityProjection(tophatImgList)
            img_median = self.smooth(img_mip)
            img_histeq, _ = imtools.histeq(img_median)
            T = otsu(np.uint(img_histeq), ignore_zeros=True)
            img_bin = (np.uint(img_histeq) > T)
            img_labeled, _ = label(img_bin)
            markers, counts = self.segmentTubes4(img_labeled, img_histeq)
            # segmentation by watershed
            img_labeled = img_bin * cwatershed(-distance(img_bin), markers)
            result = {
                'MIP': img_mip,
                'median': img_median,
                'histEq': img_histeq,
                'otsu': T,
                'bin': img_bin
            }

        # median -> otsu -> segmentation (cut regions less than mean-intensity by region)
        elif segmentationMethod == 'seg5':
            img_mip = self.maximumIntensityProjection(tophatImgList)
            img_median = self.smooth(img_mip)
            T = otsu(np.uint(img_median), ignore_zeros=True)
            img_bin = (np.uint(img_median) > T)
            img_labeled, _ = label(img_bin)
            markers, counts = self.segmentTubes4(img_labeled, img_median)
            # segmentation by watershed
            img_labeled = img_bin * cwatershed(-distance(img_bin), markers)
            result = {
                'MIP': img_mip,
                'median': img_median,
                'otsu': T,
                'bin': img_bin
            }

        # non-segmentation
        else:
            img_mip = self.maximumIntensityProjection(tophatImgList)
            img_median = self.smooth(img_mip)
            img_histeq, _ = imtools.histeq(img_median)
            T = otsu(np.uint(img_histeq))
            img_bin = (np.uint(img_histeq) > T)
            img_labeled, counts = label(img_bin)
            result = {
                'MIP': img_mip,
                'median': img_median,
                'histEq': img_histeq,
                'otsu': T,
                'bin': img_bin
            }
            print('non-segmentation')
        print('Otsu\'s threshold:', T)
        print('Found {} objects.'.format(counts))
        sizes = labeled_size(img_labeled)
        img_labeled = remove_regions_where(
            img_labeled, sizes < sizeThresh)  #origin 10000, triangle 8585
        img_relabeled, counts = relabel(img_labeled)
        result['label'] = img_relabeled
        result['count'] = counts
        print('After filtering and relabeling, there are {} objects left.'.
              format(counts))
        result['labeledSkeleton'] = self.labeledSkeleton(img_relabeled)
        return ProcessImages(result)
Exemplo n.º 20
0
from PIL import Image
from pylab import *
import sys
import imtools

imo = Image.open(sys.argv[1])
im = array(imo.convert('L'))
im2, cdf, cdf0, bins = imtools.histeq(im)
#print Image.fromArray(im)
#imshow(Image.fromarray(uint8(im)))

subplot(2,2,1)
plot(bins[:-1], cdf0)
subplot(2,2,2)
plot(bins[:-1], cdf)
subplot(2,2,3)
imshow(Image.fromarray(im).convert('LA'))
subplot(2,2,4)
imshow(Image.fromarray(im2).convert('LA'))
show()


Exemplo n.º 21
0
import imtools

# read image to array
im = array(Image.open('data/empire.jpg'))
print im.shape, im.dtype

im = array(Image.open('data/empire.jpg').convert('L'), 'f')
print im.shape, im.dtype

im = array(Image.open('data/empire.jpg').convert('L'))

# invert image
im2 = 255 - im

# clamp to interval 100...200
im3 = (100.0/255) * im + 100

# squared
im4 = 255.0 * (im/255.0)**2

print int(im4.min()),  int(im4.max())

# ====================================
im = array(Image.open('data/AquaTermi_lowcontrast.JPG').convert('L'))
im5, cdf = imtools.histeq(im)





Exemplo n.º 22
0
from PIL import Image
from pylab import *
import sift
import sys
#import imtools

imname = 'board.jpeg'
if len(sys.argv) > 1:
  imname = sys.argv[1]

histeq = False

sift.process_image(imname, 'out_sift.txt', histeq=histeq)
l1, d1 = sift.read_features_from_file('out_sift.txt')

im1 = array(Image.open(imname).convert('L'))
if histeq:
  import imtools
  im1 = uint8(imtools.histeq(array(im1))[0])
print 'image size {}, {} features'.format(im1.shape, len(l1))

figure()
gray()
sift.plot_features(im1, l1, circle=False)
show()