Esempio n. 1
0
def extr_feat(img):
    #imfilt = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    imfilt = img
    imLap = cv2.Laplacian(img, cv2.CV_64F)
    #hist_vect,bins = np.histogram(imLap.flatten(),bins=50,range=(0,200))

    #entropy
    entr = np.sum(entropy(imfilt, disk(5))[:])

    #SIFTing
    #sift = cv2.xfeatures2d.SIFT_create()
    #kp, des = sift.detectAndCompute(imfilt,None)

    #corners
    corns = cv2.cornerHarris(imfilt, 2, 3, 0.04)
    numcorns = np.sum((corns > 0.1 * corns.max()).astype(int))

    #more edge pixels on left or right
    im_siz = imLap.shape
    left_weight = np.sum(imLap[:, 0:im_siz[1] / 2])
    right_weight = np.sum(imLap[:, im_siz[1] / 2:])

    which_side = left_weight / (left_weight + right_weight)

    f_vect = np.hstack((entr, numcorns, which_side))
    return f_vect
def extr_feat(img):
    imfilt = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    imLap = cv2.Laplacian(imfilt, cv2.CV_64F)
    #hist_vect,bins = np.histogram(imLap.flatten(),bins=50,range=(0,200))

    #for rgb find the mode
    med_col = np.array([0, 0, 0])

    for cc in range(3):
        med_col[cc] = np.array(np.mean(img[:, :, cc]))

    mostcol = np.argmax(med_col)

    #crop the image

    #entropy
    entr = np.sum(entropy(imfilt, disk(5))[:])

    #SIFTing
    #sift = cv2.xfeatures2d.SIFT_create()
    #kp, des = sift.detectAndCompute(imfilt,None)

    #corners
    corns = cv2.cornerHarris(imfilt, 2, 3, 0.04)
    numcorns = np.sum((corns > 0.1 * corns.max()).astype(int))

    #more edge pixels on left or right
    im_siz = imLap.shape
    left_weight = np.sum(imLap[:, 0:im_siz[1] / 2])
    right_weight = np.sum(imLap[:, im_siz[1] / 2:])

    which_side = left_weight / (left_weight + right_weight)

    f_vect = np.hstack((entr, med_col[0] / med_col[1], numcorns, which_side))
    return f_vect
Esempio n. 3
0
def feature_1(img): 
    """Computes the average local entropy over each pixel of the image.  
    The local entropy is computed over a disc of radius 5, and is an average of the local entropy over 
    the RGB channels or greyscale image if 2D
    input: a color or greyscale image img. 
    returns: a list representing the avg local entropy over each of the 3 color channels
    """
    import numpy as np
    from skimage.filter.rank import entropy
    from skimage.morphology import disk
    if img.ndim==3:
        ent_list = []
        for i in [0,1,2]:
            ent_array = entropy(img[:,:,i],disk(5))
            ent_list.append(np.mean(ent_array))
        return ent_list
    else:
        ent_array = entropy(img,disk(5))
        return [np.mean(ent_array)]*3
Esempio n. 4
0
    def calculateEntropy(self):

        self.entropy = 0
        for i in range(len(self.weights)):
            norm_weights = (self.weights[i]-self.weights[i].min())/\
                           (self.weights[i].max()-self.weights[i].min())
            self.entropy += entropy(norm_weights, disk(12)).mean()
#            self.entropy += self.entropyF(self.weights[i].sum(axis=0))+self.entropyF(self.weights[i].sum(axis=-1))
        self.entropy /= len(self.weights)
        return self.entropy
Esempio n. 5
0
def image_features_entropy(img, maxPixel, num_features,imageSize):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric

     X=np.zeros(num_features, dtype=float)
     image = resize(img, (maxPixel, maxPixel))
     imag=entropy(image, disk(5))

    # Store the rescaled image pixels
     X[0:imageSize] = np.reshape(imag,(1, imageSize))

     return X
Esempio n. 6
0
def image_features_entropy(img, maxPixel, num_features,imageSize):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric

     X=np.zeros(num_features, dtype=float)
     image = resize(img, (maxPixel, maxPixel))
     imag=entropy(image, disk(5))

    # Store the rescaled image pixels
     X[0:imageSize] = np.reshape(imag,(1, imageSize))

     return X
def entropy_image(image, disk_size):
	"""
	This function takes in a single-channel image and returns it's entropy 
	within a disk size around it.

	Inputs:
	- image: a single-channel image matrix.
	- disk_size: a pixel radius to compute the entropy around.

	Outputs:
	- entropied: a matrix representation of an image

	To screen: a rainbow-colored image that represents the entropy.
	"""
	entropied = entropy(image, disk(disk_size))
	imshow(entropied, cmap = plt.cm.jet)
	return entropied
Esempio n. 8
0
def test_entropy():
    #  verify that entropy is coherent with bitdepth of the input data

    selem = np.ones((16, 16), dtype=np.uint8)
    # 1 bit per pixel
    data = np.tile(np.asarray([0, 1]), (100, 100)).astype(np.uint8)
    assert(np.max(rank.entropy(data, selem)) == 1)

    # 2 bit per pixel
    data = np.tile(np.asarray([[0, 1], [2, 3]]), (10, 10)).astype(np.uint8)
    assert(np.max(rank.entropy(data, selem)) == 2)

    # 3 bit per pixel
    data = np.tile(
        np.asarray([[0, 1, 2, 3], [4, 5, 6, 7]]), (10, 10)).astype(np.uint8)
    assert(np.max(rank.entropy(data, selem)) == 3)

    # 4 bit per pixel
    data = np.tile(
        np.reshape(np.arange(16), (4, 4)), (10, 10)).astype(np.uint8)
    assert(np.max(rank.entropy(data, selem)) == 4)

    # 6 bit per pixel
    data = np.tile(
        np.reshape(np.arange(64), (8, 8)), (10, 10)).astype(np.uint8)
    assert(np.max(rank.entropy(data, selem)) == 6)

    # 8-bit per pixel
    data = np.tile(
        np.reshape(np.arange(256), (16, 16)), (10, 10)).astype(np.uint8)
    assert(np.max(rank.entropy(data, selem)) == 8)

    # 12 bit per pixel
    selem = np.ones((64, 64), dtype=np.uint8)
    data = np.tile(
        np.reshape(np.arange(4096), (64, 64)), (2, 2)).astype(np.uint16)
    assert(np.max(rank.entropy(data, selem)) == 12)

    # make sure output is of dtype double
    out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8))
    assert out.dtype == np.double
Esempio n. 9
0
def test_entropy():
    #  verify that entropy is coherent with bitdepth of the input data

    selem = np.ones((16, 16), dtype=np.uint8)
    # 1 bit per pixel
    data = np.tile(np.asarray([0, 1]), (100, 100)).astype(np.uint8)
    assert (np.max(rank.entropy(data, selem)) == 1)

    # 2 bit per pixel
    data = np.tile(np.asarray([[0, 1], [2, 3]]), (10, 10)).astype(np.uint8)
    assert (np.max(rank.entropy(data, selem)) == 2)

    # 3 bit per pixel
    data = np.tile(np.asarray([[0, 1, 2, 3], [4, 5, 6, 7]]),
                   (10, 10)).astype(np.uint8)
    assert (np.max(rank.entropy(data, selem)) == 3)

    # 4 bit per pixel
    data = np.tile(np.reshape(np.arange(16), (4, 4)),
                   (10, 10)).astype(np.uint8)
    assert (np.max(rank.entropy(data, selem)) == 4)

    # 6 bit per pixel
    data = np.tile(np.reshape(np.arange(64), (8, 8)),
                   (10, 10)).astype(np.uint8)
    assert (np.max(rank.entropy(data, selem)) == 6)

    # 8-bit per pixel
    data = np.tile(np.reshape(np.arange(256), (16, 16)),
                   (10, 10)).astype(np.uint8)
    assert (np.max(rank.entropy(data, selem)) == 8)

    # 12 bit per pixel
    selem = np.ones((64, 64), dtype=np.uint8)
    data = np.tile(np.reshape(np.arange(4096), (64, 64)),
                   (2, 2)).astype(np.uint16)
    assert (np.max(rank.entropy(data, selem)) == 12)

    # make sure output is of dtype double
    out = rank.entropy(data, np.ones((16, 16), dtype=np.uint8))
    assert out.dtype == np.double
def plotEntropy(filename):
    """
    Plots the entropy in the data. No really suitable as the input data
    not in a useful format.
    """
    data = pf.getdata(filename).astype(np.uint32)

    #plot the image
    fig = plt.figure(figsize=(18, 10))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    ax1.set_title('Data, Single Qaudrant')
    ax2.set_title('Background Mask')

    im1 = ax1.imshow(np.log10(data), origin='lower', vmin=2., vmax=3.5, interpolation='none')
    im2 = ax2.imshow(entropy(data, disk(5)), origin='lower', interpolation='none')
    c1 = plt.colorbar(im1, ax=ax1, orientation='horizontal')
    c2 = plt.colorbar(im2, ax=ax2, orientation='horizontal')
    c1.set_label('$\log_{10}$(Counts [ADU])')
    c2.set_label('Entropy')
    plt.savefig('entropy.png')
    plt.close()
Esempio n. 11
0
def intensity_stats(im):
    if im.shape != (64, 64):
        im = transform.resize(im, (64, 64))
    l = morphology.disk(10)
    h = entropy((im*255.0).astype(np.uint8), l)
    return [np.mean(h), np.std(h), float(np.std(im))]
Esempio n. 12
0
image = img_as_ubyte(original_image)

#preprocess image
#arr = mean(arr, disk(20))
#arr = mean_bilateral(arr.astype(np.uint16), disk(8), s0=4 , s1=4)
#(arr,labels_image,number_regions)=pms.segment(arr,spatial_radius=6,range_radius=4.5,min_density=50)

#plot original image
fig, [(ax0, ax1, ax2),(ax3, ax4, ax5)] = plt.subplots(ncols=3, nrows=2, figsize=(15,8))
img0 = ax0.imshow(image, cmap=plt.cm.gray)
ax0.set_title('Imagen original')
ax0.axis('off')
fig.colorbar(img0, ax=ax0)

#plot entropy image
entro=entropy(arr, disk(3))
img1 = ax1.imshow(entro,cmap=plt.cm.jet)
ax1.set_title('Entropia')
ax1.axis('off')
fig.colorbar(img1, ax=ax1)


#plot histogram of entropy image
ax2.set_title('Histograma')
ax2.hist(entro.ravel(), 256, histtype='step', color='black')
ax2.ticklabel_format(axis='y', style='scientific', scilimits=(0,0))
ax2.set_xlim(0,7)
ax2.set_yticks([])

#plot sample extracted from image
sample_location = (320,240)
Esempio n. 13
0
Entropy
=======

Image entropy is a quantity which is used to describe the amount of information
coded in an image.

"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
from skimage.util import img_as_ubyte


image = img_as_ubyte(data.camera())

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(10, 4))

img0 = ax0.imshow(image, cmap=plt.cm.gray)
ax0.set_title('Image')
ax0.axis('off')
plt.colorbar(img0, ax=ax0)

img1 = ax1.imshow(entropy(image, disk(5)), cmap=plt.cm.jet)
ax1.set_title('Entropy')
ax1.axis('off')
plt.colorbar(img1, ax=ax1)

plt.show()
Esempio n. 14
0
def get_entropy_and_mean_motion_temp(videofile):
    """
	After messing around with detecting the full body coordinates, I moved to simply calculating aggregate measures of the amount of motion by individuals during a date. This is better because it accounts for factors like head movement or gestures. 
	It still didn't help much though because how much a person moves during a date doesn't seem to provide much information about how the date will turn out.
	"""

    # input video to use (called cam b/c I'm lazy, actually a cap "capture")
    cam = cv2.VideoCapture(videofile)
    # read the first frame to initialize
    if cam.isOpened():
        print('open')
    else:
        print('not open')
    ret, frame = cam.read()
    if not ret:
        sys.exit(1)

    # get height and width
    h, w = reduce_region(frame).shape[:2]
    # init the prev frame
    prev_frame = reduce_region(frame.copy())
    # init motion his to an array of zeros of size (h,w)
    motion_history = np.zeros((h, w), np.float32)
    sum_history = np.zeros((h, w), np.float32)

    hsv = np.zeros((h, w, 3), np.uint8)
    hsv[:, :, 1] = 255

    # iterate through the frames
    frame_num = 0
    while True:

        # read in a frame
        ret, frame = cam.read()
        frame_num += 1
        if not ret:
            break

        if frame_num % 5 == 0:
            frame = reduce_region(frame)

            # calc the difference between this frame and the prev one
            frame_diff = cv2.absdiff(frame, prev_frame)

            # convert to gray
            gray_diff = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY)

            # get the threshold from the user window
            thrs = DEFAULT_THRESHOLD

            # get the motion_mask value to use based upon the threshold and diff
            ret, motion_mask = cv2.threshold(gray_diff, thrs, 1,
                                             cv2.THRESH_BINARY)
            sum_history += motion_mask

            prev_frame = frame.copy()

    cam.release()
    cv2.destroyAllWindows()

    history_max = sum_history.max(axis=1).max()
    entropy_img = entropy(sum_history / history_max, disk(5))
    entropy_sum = entropy_img.sum(axis=1).sum()

    motion_template_mean = sum_history.mean(axis=1).mean()

    print('sum'),
    print(entropy_sum)
    print('mean'),
    print(motion_template_mean)

    return entropy_sum, motion_template_mean
Esempio n. 15
0
thresholding. In practice, you might want to define a region for tinting based
on segmentation results or blob detection methods.
"""

from skimage.filter import rank

# Square regions defined as slices over the first two dimensions.
top_left = (slice(100),) * 2
bottom_right = (slice(-100, None),) * 2

sliced_image = image.copy()
sliced_image[top_left] = colorize(image[top_left], 0.82, saturation=0.5)
sliced_image[bottom_right] = colorize(image[bottom_right], 0.5, saturation=0.5)

# Create a mask selecting regions with interesting texture.
noisy = rank.entropy(grayscale_image, np.ones((9, 9)))
textured_regions = noisy > 4
# Note that using `colorize` here is a bit more difficult, since `rgb2hsv`
# expects an RGB image (height x width x channel), but fancy-indexing returns
# a set of RGB pixels (# pixels x channel).
masked_image = image.copy()
masked_image[textured_regions, :] *= red_multiplier

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))
ax1.imshow(sliced_image)
ax2.imshow(masked_image)

plt.show()

"""
.. image:: PLOT2RST.current_figure
Esempio n. 16
0
import matplotlib.patches as mp
from skimage.filter.rank import entropy, otsu
from skimage.filter import threshold_otsu
from skimage.morphology import square, rectangle, label, closing, disk, binary_erosion, opening
from skimage.color import label2rgb, rgb2gray
from skimage.segmentation import clear_border
from skimage.measure import regionprops
from skimage import io
i = rgb2gray(io.imread('z.jpg'))
t = threshold_otsu(i)
i = i > t
z = binary_erosion(1 - i, square(3))
z = np.logical_xor(z, i)
z = binary_erosion(1 - z, square(2))
i = 1 - z
i = entropy(i, rectangle(18, 20))
t = threshold_otsu(i)
c = opening(i > t, square(2))
b = c.copy()
clear_border(b)
l = label(b)
z = np.logical_xor(c, b)
l[z] = -1
iol = label2rgb(l, image=i)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(iol)
for region in regionprops(l, ['Area', 'BoundingBox']):
    if region['Area'] < 3500:
        continue
    minr, minc, maxr, maxc = region['BoundingBox']
    rect = mp.Rectangle((minc, minr),
Esempio n. 17
0
def segmentation(sample):
    samples = []
    cores = []
    images = []
    cf = .9
    entropy_ratio = .5
    core_ratio = .07 #around 10% of image is core
    eq_thresh = 10
    csize = 300 #change it later
#    for sample in samples:
    #    if image_number<5:
    #        image_number += 1
    #        continue
        
#    image_number += 1
    try:
        gray_images = np.array([i for i in open_image(sample)])
    except:
        print 'can\'t open'
#        continue
    m, n = gray_images[0].shape
    
    g_min = np.min(gray_images[1:], axis=0)
    g_max = np.max(gray_images[1:], axis=0)
    g_avg = np.average(gray_images[1:], axis=0)
    g_mean = rank.mean_bilateral(g_max, disk(40))
    images.append(g_max)
    
    
    selem = disk(5)
    
    diff = g_max-g_min
    diff1 = g_avg-g_min
    diff2 = g_max-g_avg
    h2 = histogram(diff2)
    
    '''
    equalize image -> cores are white or black
    '''
    equalized = img_as_ubyte(exposure.equalize_hist(diff))
    
    
    #equalized = img_as_ubyte(exposure.equalize_hist(g_min))#g_min
    equalized = exposure.adjust_gamma(g_max,2)
    ##eq_mask = []
    #equalized = img_as_ubyte(exposure.equalize_hist(mask))
    #eq_mask = equalized<eq_thresh
    
    
    '''
    local otsu
    '''
    radius = 20
    selem = disk(radius)
    local_otsu = rank.otsu(equalized, selem)
#    local_otsu = tmp<threshold_otsu(equalized)
    bg = diff<=local_otsu
    

    ent = rank.entropy(g_max*~bg, disk(35))
    grad = rank.gradient(g_mean, disk(50))
    tmp = ent*grad
    core_mask = tmp>(np.min(tmp)+(np.max(tmp)-np.min(tmp))*entropy_ratio)    
    
#    
#    h = histogram(local_otsu)
#    cdf = 0
#    t = g_min.shape[0]*g_min.shape[1]*core_ratio
#    
#    for i in range(len(h)):
#        cdf += h[i]
#        if cdf > t:
#            maxi = i
#            break
#        
#    core_mask = (local_otsu<maxi)
##    imshow(core_mask)
#    ##cores = np.logical_and(eq_mask, core_mask)
#    ##imshow(eq_mask)
#    #
#    #
    
    
    lbl, num_lbl = ndi.label(core_mask)
    
    
    for i in range(1,num_lbl+1):
        '''
        lbl==0 is background
        '''
        c = np.where(np.max(lbl==i, axis=0)==True)[0]
        left = c[0]
        right = c[-1]
        
        c = np.where(np.max(lbl==i, axis=1)==True)[0]
        up = c[0]
        down = c[-1]

#        '''
#        Don't consider edge cores
#        '''            
#        if left<csize/2 or right>n-csize/2:
#            continue
#        if up<csize/2 or down>m-csize/2:
#            continue
#        
        
    
        core = np.zeros((csize, csize))
        h = down-up
        w = right-left
        
        middle_x = min(max((up+down)/2, csize/2),m-csize/2)
        middle_y = min(max((left+right)/2, csize/2), n-csize/2)
        
#        core = (core_mask*gray_images[0])[middle_x-csize/2:middle_x+csize/2, middle_y-csize/2:middle_y+csize/2]
        core = gray_images[0][middle_x-csize/2:middle_x+csize/2, middle_y-csize/2:middle_y+csize/2]
        core = exposure.adjust_gamma(core,.5)
        
        
        cores.append(core)
    return cores
#    print 'image', image_number
#    
#if __name__=='__main__':
#    os.system('rm %s -R'%(output_dir))
#    os.system('mkdir %s'%(output_dir))
#    #os.system('mkdir %sres/021'%(input_dir))
#    #os.system('mkdir %sres/041'%(input_dir))
#    for i in range(len(cores)):
#        image_name = '%s/%i.png'%(output_dir, i)
#        imsave(image_name, cores[i])
        
        
        
        
        
def get_entropy_and_mean_motion_temp(videofile):
	"""
	After messing around with detecting the full body coordinates, I moved to simply calculating aggregate measures of the amount of motion by individuals during a date. This is better because it accounts for factors like head movement or gestures. 
	It still didn't help much though because how much a person moves during a date doesn't seem to provide much information about how the date will turn out.
	"""

	# input video to use (called cam b/c I'm lazy, actually a cap "capture")
	cam = cv2.VideoCapture(videofile)
	# read the first frame to initialize
	if cam.isOpened():
		print('open')
	else:
		print('not open')
	ret, frame = cam.read()
	if not ret:
		sys.exit(1)

	# get height and width
	h, w = reduce_region(frame).shape[:2]
	# init the prev frame
	prev_frame = reduce_region(frame.copy())
	# init motion his to an array of zeros of size (h,w)
	motion_history = np.zeros((h, w), np.float32)
	sum_history = np.zeros((h, w), np.float32)

	hsv = np.zeros((h, w, 3), np.uint8)
	hsv[:,:,1] = 255

	# iterate through the frames
	frame_num = 0
	while True:

		# read in a frame
		ret, frame = cam.read()
		frame_num += 1
		if not ret:
			break

		if frame_num % 5 == 0:
			frame = reduce_region(frame)

			# calc the difference between this frame and the prev one
			frame_diff = cv2.absdiff(frame, prev_frame)

			# convert to gray
			gray_diff = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY)

			# get the threshold from the user window
			thrs = DEFAULT_THRESHOLD

			# get the motion_mask value to use based upon the threshold and diff
			ret, motion_mask = cv2.threshold(gray_diff, thrs, 1, cv2.THRESH_BINARY)
			sum_history += motion_mask

			prev_frame = frame.copy()

	cam.release()
	cv2.destroyAllWindows()

	history_max = sum_history.max(axis=1).max()
	entropy_img = entropy(sum_history/history_max, disk(5))
	entropy_sum = entropy_img.sum(axis=1).sum()

	motion_template_mean = sum_history.mean(axis=1).mean()

	print('sum'),
	print(entropy_sum)
	print('mean'),
	print(motion_template_mean)

	return entropy_sum, motion_template_mean
        #     sx = ndimage.sobel(seg, axis=0, mode='constant')
        #     sy = ndimage.sobel(seg, axis=1, mode='constant')
        #     contorno = n.hypot(sx, sy)
        #     #imsave('cont.jpg', contorno)
            
        #     area = n.sum(seg != 0)
        #     peri = n.sum(contorno != 0)
        #     raz = float(peri**2)/area
        #     qr.append(raz)
        #     D2.append(area, peri)
        # # guardamos a media das razoes de perimetro/area de todos os segmentos
        # # da pintura
        # qrm = n.sum(qr) / k

        # entropia local (media)
        entropia_local = entropy(im_media, disk(5))
        sh = entropia_local.shape
        m_entropia_local = n.sum(entropia_local) / (sh[0]*sh[1])
        qel = m_entropia_local

        # entropia local (media) com disco maior, 50x50
        entropia_local_maior = entropy(im_media, disk(50))
        sh2 = entropia_local_maior.shape
        m_entropia_local_maior = n.sum(entropia_local_maior) / (sh2[0]*sh2[1])
        qel_maior = m_entropia_local_maior

        
        # usando canny/sobel + transformada de hough para detectar linhas de qualquer angulo
        #edges = canny(im_binaria, 2, 1, 25)
        #edges = canny(im_binaria, 0.3, 0.2)
        sx = ndimage.sobel(im_binaria, axis=0, mode='constant')
Esempio n. 20
0
from skimage.morphology import disk
import numpy as np
import matplotlib.pyplot as plt

image = data.camera()

plt.figure(figsize=(10, 4))

plt.subplot(1, 2, 1)
plt.imshow(image, cmap=plt.cm.gray)
plt.title('Image')
plt.colorbar()
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(entropy(image, disk(5)), cmap=plt.cm.jet)
plt.title('Entropy')
plt.colorbar()
plt.axis('off')
"""

.. image:: PLOT2RST.current_figure

Implementation
==============

The central part of the `skimage.rank` filters is build on a sliding window
that updates the local gray-level histogram. This approach limits the algorithm
complexity to O(n) where n is the number of image pixels. The complexity is
also limited with respect to the structuring element size.
Esempio n. 21
0
=======

"""
import numpy as np
import matplotlib.pyplot as plt

from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk


# defining a 8- and a 16-bit test images
a8 = data.camera()
a16 = a8.astype(np.uint16) * 4

ent8 = entropy(a8, disk(5)) # pixel value contain 10x the local entropy
ent16 = entropy(a16, disk(5)) # pixel value contain 1000x the local entropy

# display results
plt.figure(figsize=(10, 10))

plt.subplot(2,2,1)
plt.imshow(a8, cmap=plt.cm.gray)
plt.xlabel('8-bit image')
plt.colorbar()

plt.subplot(2,2,2)
plt.imshow(ent8, cmap=plt.cm.jet)
plt.xlabel('entropy*10')
plt.colorbar()
Esempio n. 22
0
from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
import numpy as np
import matplotlib.pyplot as plt

image = data.camera()

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

fig.colorbar(ax1.imshow(image, cmap=plt.cm.gray), ax=ax1)
ax1.set_title('Image')
ax1.axis('off')

fig.colorbar(ax2.imshow(entropy(image, disk(5)), cmap=plt.cm.jet), ax=ax2)
ax2.set_title('Entropy')
ax2.axis('off')

"""

.. image:: PLOT2RST.current_figure

Implementation
==============

The central part of the `skimage.rank` filters is build on a sliding window
that updates the local gray-level histogram. This approach limits the algorithm
complexity to O(n) where n is the number of image pixels. The complexity is
also limited with respect to the structuring element size.
Esempio n. 23
0
# AC, DTU, April 2014
# Code written in preparation of the J-PARC beamtime
# First step to locate blobs is adaptive equalization
# Source: http://scikit-image.org/docs/0.9.x/auto_examples/plot_equalize.html

import matplotlib.pyplot as plt
import pyfits

from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
from skimage.util import img_as_ubyte

file = pyfits.open('/Users/Alberto/Desktop/Test_image_raw.fits')
image = file[0].data
fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(10, 4))

img0 = ax0.imshow(image, cmap=plt.cm.gray)
ax0.set_title('Image')
ax0.axis('off')
plt.colorbar(img0, ax=ax0)

img1 = ax1.imshow(entropy(image, disk(3)), cmap=plt.cm.jet)
ax1.set_title('Entropy')
ax1.axis('off')
plt.colorbar(img1, ax=ax1)

plt.show()
def kmFindEntropy(frame):
    frameBlurred = cv2.GaussianBlur(frame, (3,3), 0)
    gray = cv2.cvtColor(frameBlurred, cv2.COLOR_BGR2GRAY)
    entropyImg = entropy(img_as_ubyte(gray), disk(5))
    
    return entropyImg
Esempio n. 25
0
from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
import numpy as np
import matplotlib.pyplot as plt

image = data.camera()

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

fig.colorbar(ax1.imshow(image, cmap=plt.cm.gray), ax=ax1)
ax1.set_title('Image')
ax1.axis('off')

fig.colorbar(ax2.imshow(entropy(image, disk(5)), cmap=plt.cm.jet), ax=ax2)
ax2.set_title('Entropy')
ax2.axis('off')
"""

.. image:: PLOT2RST.current_figure

Implementation
==============

The central part of the `skimage.rank` filters is build on a sliding window
that updates the local gray-level histogram. This approach limits the algorithm
complexity to O(n) where n is the number of image pixels. The complexity is
also limited with respect to the structuring element size.

In the following we compare the performance of different implementations
# AC, DTU, April 2014
# Code written in preparation of the J-PARC beamtime
# First step to locate blobs is adaptive equalization
# Source: http://scikit-image.org/docs/0.9.x/auto_examples/plot_equalize.html

import pyfits
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pylab as py
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from skimage import data, img_as_float
from skimage import exposure
from skimage.filter.rank import entropy

file = pyfits.open('/Users/Alberto/Desktop/Test_image_raw.fits')
img = file[0].data
img1 = ax1.imshow(entropy(img, disk(5)), cmap=plt.cm.jet)
# Conceptually, equalizing and rescaling exposure are the same thing
p2, p98 = np.percentile(img, (2, 98))
img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
img_adapteq = exposure.equalize_adapthist(img_rescale, clip_limit=0.1)
#img_eq = exposure.equalize_hist(img_adapteq)
#print img_eq
plt.imshow(img1)
plt.show()
Esempio n. 27
0
http://www.astro.cornell.edu/research/projects/compression/entropy.html

"""

from skimage.filter.rank import entropy
from skimage.morphology import disk
import numpy as np
import skimage
import os

#Declare here where you want the script to write the csv results
outputfile=open("C

#Provide the directory where all the .jpgs are
filepath="C:
shots=os.listdir(filepath)

#Loop to calculate the average entropy for each image in the directory, and write the "Name","Score" to each row of a csv.
#c is just a counter to print % progess. you can def delete it if you want.
c=0
for shot in shots:
    c+=1
    # deifning 16-bit images
    a16 = skimage.io.imread(filepath+shot,flatten=True).astype(np.uint16)*100
    ent16 = entropy(a16,disk(5))
    ent=np.average(ent16)
    outputfile.write(str(ent)+','+shot+'\n')
    print((float(c)/len(shots)*100))


Esempio n. 28
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mp
from skimage.filter.rank import entropy,otsu
from skimage.filter import threshold_otsu
from skimage.morphology import square,rectangle,label,closing,disk,binary_erosion,opening
from skimage.color import label2rgb,rgb2gray
from skimage.segmentation import clear_border
from skimage.measure import regionprops
from skimage import io
i=rgb2gray(io.imread('z.jpg'))
t=threshold_otsu(i)
i=i>t
z=binary_erosion(1-i,square(3))
i=1-z
i=entropy(i,rectangle(10,1))
t=threshold_otsu(i)
c=i>t
c=closing(c,rectangle(4,28))
b=c.copy()
clear_border(b)
l=label(b)
z=np.logical_xor(c,b)
l[z]=-1
iol=label2rgb(l,image=i)
fig,ax=plt.subplots(ncols=1,nrows=1,figsize=(6,6))
ax.imshow(iol)
for region in regionprops(l,['Area','BoundingBox']):
	if region['Area']<3500:
		continue
	minr,minc,maxr,maxc=region['BoundingBox']
Esempio n. 29
0
    to better use the available image bit, the function returns 10x entropy for
    8-bit images and 1000x entropy for 16-bit images.

"""

from skimage import data
from skimage.filter.rank import entropy
from skimage.morphology import disk
import numpy as np
import matplotlib.pyplot as plt

# defining a 8- and a 16-bit test images
a8 = data.camera()
a16 = data.camera().astype(np.uint16) * 4

ent8 = entropy(a8, disk(5))  # pixel value contain 10x the local entropy
ent16 = entropy(a16, disk(5))  # pixel value contain 1000x the local entropy

# display results
plt.figure(figsize=(10, 10))

plt.subplot(2, 2, 1)
plt.imshow(a8, cmap=plt.cm.gray)
plt.xlabel('8-bit image')
plt.colorbar()

plt.subplot(2, 2, 2)
plt.imshow(ent8, cmap=plt.cm.jet)
plt.xlabel('entropy*10')
plt.colorbar()
def preprocessing_gauss_center_entr(img, det):
    return im_crop(entropy(ndimage.gaussian_filter((img / MaximumPixelIntensity), sigma=0.95)
                   , disk(6)), 6.0)