Exemple #1
0
def blurry_histogram(im, num_samples=300, offset=1):
    im = image.rgb2gray(im)
    size = cv.GetSize(im)
    used = set([])
    i = 0
    diffs = {}
    while i < num_samples:
        # we can't use the first row of pixels
        x = random.randrange(0, size[0])
        y = random.randrange(offset, size[1])
        if (x, y) not in used:
            pixel1 = cv.Get2D(im, y, x)
            pixel2 = cv.Get2D(im, y - offset, x)
            diff = tuple(map(lambda a, b: a - b, pixel1, pixel2))
            if diff not in diffs:
                diffs[diff] = 0
            diffs[diff] += 1
            used = used.union([(x, y)])
            i += 1
    max_i = max_v = 0
    second_max_i = second_max_v = 0
    for key, val in diffs.iteritems():
        if max_v < val:
            second_max_i, second_max_v = max_i, max_v
            max_v, max_i = val, key
    return (max_v - second_max_v) / abs(max_i[0] - second_max_i[0])
def detect(im, cascade, haar_scale=1.2, min_neighbors=2, min_size=(20,20)):
    haar_flags = 0

    gray = image.rgb2gray(im)
    small = image.resize(gray, by_percent=im_scale)
    cv.EqualizeHist(small, small)
    objs = cv.HaarDetectObjects(small, cascade, cv.CreateMemStorage(0),
        haar_scale, min_neighbors, cv.CV_HAAR_DO_CANNY_PRUNING, min_size)
    return [Rect(r,n,cv.GetSize(im)) for r,n in objs]
def measure(im, debug=False):
    gray = image.rgb2gray(im)
    _, s, v = image.split(image.rgb2hsv(im))
    h = GrayscaleHist(bins=64).use_image(v)
    s = GrayscaleHist(bins=64).use_image(s)
    scores = [score_hist(h)]

    if debug:
        image.show(v, "1. Value")
        image.show(h.to_img(), "2. Value Histogram")
        image.show(s.to_img(), "2. Saturation Histogram")
        print score_hist(s)

    return (None, scores[0])  # h.to_img(),
def measure(im, debug=False):
    gray = image.rgb2gray(im)
    _, s, v = image.split(image.rgb2hsv(im))
    h = GrayscaleHist(bins=64).use_image(v)
    s = GrayscaleHist(bins=64).use_image(s)
    scores = [score_hist(h)]

    if debug:
        image.show(v, "1. Value")
        image.show(h.to_img(), "2. Value Histogram")
        image.show(s.to_img(), "2. Saturation Histogram")
        print score_hist(s)

    return (
        None,  #h.to_img(),
        scores[0],
    )
Exemple #5
0
def training_patches(imnames,
                     npatches,
                     psize,
                     maxdim=None,
                     colour=False,
                     verbose=False):
    """ Extract patches from images for dictionary training

    Arguments:
        imnames: A list of image names from which to extract training patches.
        npatches: The number (int) of patches to extract from the images
        maxdim: The maximum dimension of the image in pixels. The image is
            rescaled if it is larger than this. By default there is no scaling. 
        psize: A int of the size of the square patches to extract
        verbose: bool, print progress bar

    Returns:
        An np.array (npatches, psize**2*3) for RGB or (npatches, psize**2) for
        grey of flattened image patches. NOTE, the actual npatches found may be
        less than that requested.

    """

    nimg = len(imnames)
    ppeimg = int(round(float(npatches) / nimg))
    plist = []

    # Set up progess updates
    progbar = Progress(nimg, title='Extracting patches', verbose=verbose)

    for i, ims in enumerate(imnames):
        img = imread_resize(ims, maxdim)  # read in and resize the image
        spaceing = max(int(round(img.shape[1] * ppeimg**(-0.5))), 1)

        # Extract patches and map to grayscale if necessary
        if (colour == False) and (img.ndim == 3):
            imgg = rgb2gray(img)
            plist.append(grid_patches(imgg, psize, spaceing)[0])
        else:
            plist.append(grid_patches(img, psize, spaceing)[0])

        progbar.update(i)

    progbar.finished()
    patches = np.concatenate(plist, axis=0)
    return np.reshape(patches, (patches.shape[0], np.prod(patches.shape[1:])))
Exemple #6
0
def training_patches (imnames, npatches, psize, maxdim=None, colour=False,
                        verbose=False):
    """ Extract patches from images for dictionary training

    Arguments:
        imnames: A list of image names from which to extract training patches.
        npatches: The number (int) of patches to extract from the images
        maxdim: The maximum dimension of the image in pixels. The image is
            rescaled if it is larger than this. By default there is no scaling. 
        psize: A int of the size of the square patches to extract
        verbose: bool, print progress bar

    Returns:
        An np.array (npatches, psize**2*3) for RGB or (npatches, psize**2) for
        grey of flattened image patches. NOTE, the actual npatches found may be
        less than that requested.

    """

    nimg = len(imnames)
    ppeimg = int(round(float(npatches)/nimg))
    plist = []

    # Set up progess updates
    progbar = Progress(nimg, title='Extracting patches', verbose=verbose)

    for i, ims in enumerate(imnames):
        img = imread_resize(ims, maxdim) # read in and resize the image
        spaceing = max(int(round(img.shape[1] *  ppeimg**(-0.5))), 1)
        
        # Extract patches and map to grayscale if necessary
        if (colour == False) and (img.ndim == 3):
            imgg = rgb2gray(img)
            plist.append(grid_patches(imgg, psize, spaceing)[0])
        else:
            plist.append(grid_patches(img, psize, spaceing)[0])

        progbar.update(i)

    progbar.finished()
    patches = np.concatenate(plist, axis=0)
    return np.reshape(patches, (patches.shape[0], np.prod(patches.shape[1:])))
Exemple #7
0
def measure(im, debug=False):
    gray = image.rgb2gray(im)
    size = cv.GetSize(im)
    total = float(size[0] * size[1])
    edges = image.auto_edges(im)

    hue, sat, val = tuple(
        map(image.equalize_hist, image.split(image.rgb2hsv(im))))
    l, u, v = tuple(map(image.equalize_hist, image.split(image.rgb2luv(im))))

    values = []
    if debug:
        image.show(l, "L")
        image.show(val, "Value")
    sat = image.threshold(val, 255 - 32)  #image.And(val, sat)
    if debug:
        image.show(sat, "Thresh")
    #cv.And(val, l, val)
    cv.Sub(l, sat, l)
    cv.Set(l, 0, image.dilate(edges, iterations=3))
    if debug:
        image.show(l, "L - Value")
    val = l
    g = Grid(cv.GetSize(val))
    images = g.split_into(val, 16)
    arr = image.cv2array(val)
    avgmean, avgstd = arr.mean(), arr.std()
    for i in images:
        a = image.cv2array(i)
        mean, std = abs(a.mean() - avgmean), max(a.std(), 0)
        values.append((mean + std))

    if debug:
        print values
        print "AVG", avgmean, avgstd
        image.show(val, "Result")

    return val, (avgmean, avgstd, len([v for v in values if v > avgstd * 2]))
Exemple #8
0
def measure(im, debug=False):

    gray = image.rgb2gray(im)
    size = cv.GetSize(im)
    total = float(size[0] * size[1])
    edges = image.auto_edges(im)

    _, sat, val = image.split(image.rgb2hsv(im))
    edges = image.auto_edges(im)
    l, u, v = tuple(map(image.equalize_hist, image.split(image.rgb2luv(im))))
    u, v = tuple(map(image.gaussian, (u, v)))
    if debug:
        image.show(l, "1. L")
        image.show(u, "1. U")
        image.show(v, "1. V")
    la, ua, va, uva = tuple(map(image.cv2array, (l, u, v, image.And(l, u, v))))
    test = image.new_from(gray)
    test2 = image.new_from(gray)
    cv.Xor(u, v, test)
    #cv.AbsDiff(u,v, test2)
    if debug:
        #cv.Threshold(test, test, 32, 255, cv.CV_THRESH_BINARY)
        image.show(test, "2. U Xor V")
        #image.show(test2, "TEST 2")
        #test = image.dilate(test)
    cv.Set(test, 0, image.dilate(edges))
    #cv.Set(test, 0, image.invert(image.threshold(sat, threshold=8)))
    uv_score = cv.CountNonZero(test) / total
    if debug:
        image.show(
            test, "3. U Xor V - dilate(Edges) - invert(threshold(Saturation))")

    arr = image.cv2array(test)
    avg_mean, avg_std = arr.mean(), arr.std()

    score = uv_score, avg_std

    return test, score
def measure(im, debug=False):       
    gray = image.rgb2gray(im)
    size = cv.GetSize(im)
    total = float(size[0] * size[1])
    edges = image.auto_edges(im)

    hue, sat, val = tuple(map(image.equalize_hist, image.split(image.rgb2hsv(im)) ))
    l,u,v = tuple(map(image.equalize_hist, image.split(image.rgb2luv(im))))
    
    values = []
    if debug:
        image.show(l, "L")
        image.show(val, "Value")
    sat = image.threshold(val,255-32)#image.And(val, sat)
    if debug:
        image.show(sat, "Thresh")
    #cv.And(val, l, val)
    cv.Sub(l, sat, l)
    cv.Set(l, 0, image.dilate(edges, iterations=3))
    if debug:
        image.show(l, "L - Value")
    val = l
    g = Grid(cv.GetSize(val))
    images = g.split_into(val, 16)
    arr = image.cv2array(val)
    avgmean, avgstd = arr.mean(), arr.std()
    for i in images:
        a = image.cv2array(i)
        mean, std = abs(a.mean() - avgmean), max(a.std(), 0)
        values.append((mean+std))
    
    if debug:
        print values
        print "AVG", avgmean, avgstd
        image.show(val, "Result")
        
    return val, (avgmean, avgstd, len([v for v in values if v > avgstd*2]))
def measure(im, debug=False):
    
    gray = image.rgb2gray(im)
    size = cv.GetSize(im)
    total = float(size[0] * size[1])
    edges = image.auto_edges(im)

    _, sat, val = image.split(image.rgb2hsv(im))
    edges = image.auto_edges(im)
    l,u,v = tuple(map(image.equalize_hist, image.split(image.rgb2luv(im))))
    u,v = tuple(map(image.gaussian, (u,v)))
    if debug:
        image.show(l, "1. L")
        image.show(u, "1. U")
        image.show(v, "1. V")
    la,ua,va,uva = tuple(map(image.cv2array, (l,u,v, image.And(l,u,v))))
    test = image.new_from(gray)
    test2 = image.new_from(gray)
    cv.Xor(u,v,test)
    #cv.AbsDiff(u,v, test2)
    if debug:
        #cv.Threshold(test, test, 32, 255, cv.CV_THRESH_BINARY)
        image.show(test, "2. U Xor V")
        #image.show(test2, "TEST 2")
        #test = image.dilate(test)
    cv.Set(test, 0, image.dilate(edges))
    #cv.Set(test, 0, image.invert(image.threshold(sat, threshold=8)))
    uv_score = cv.CountNonZero(test) / total
    if debug:
        image.show(test, "3. U Xor V - dilate(Edges) - invert(threshold(Saturation))")
    
    arr = image.cv2array(test)
    avg_mean, avg_std = arr.mean(), arr.std()
    
    score = uv_score, avg_std
    
    return test, score
Exemple #11
0
def measure(im, debug=False):
    gray = image.rgb2gray(im)
    size = cv.GetSize(im)
    total = float(size[0] * size[1])
    l = image.sub(gray, image.gaussian(gray, 5))
    l2 = image.sub(gray, image.gaussian(gray, 9))
    edges = image.dilate(image.auto_edges(im, percentage=0.2))
    if debug:
        image.show(image.threshold(l, threshold=1),
                   "Before Edge Removal (kernel=5)")
        image.show(image.threshold(l2, threshold=1),
                   "Before Edge Removal (kernel=9)")
    cv.Set(l, 0, image.threshold(edges, threshold=1))
    cv.Set(l2, 0, image.threshold(edges, threshold=1))

    l = image.threshold(l, threshold=1)
    l2 = image.threshold(l2, threshold=1)

    if debug:
        image.show(image.threshold(edges, threshold=1), "Edges")
        image.show(l, "After Edge Removal (kernel=5)")
        image.show(l2, "After Edge Removal (kernel=9)")

    noise2 = image.new_from(gray)
    cv.EqualizeHist(gray, noise2)
    cv.AbsDiff(noise2, gray, noise2)
    cv.Set(noise2, 0,
           image.threshold(image.sobel(im, xorder=2, yorder=2), threshold=4))
    diff = image.cv2array(noise2)
    if debug:
        image.show(noise2, "DIFF")
        print "M", diff.mean(), "S", diff.std()
    diff_stat = (diff.mean(), diff.std())
    percent_noise = cv.CountNonZero(noise2) / total
    if debug:
        image.show(noise2, "NOISE2")

    # magical, I don't understand how this works
    _, sat, _ = image.split(image.rgb2hsv(im))
    edges = image.auto_edges(im)
    l, u, v = tuple(map(image.equalize_hist, image.split(image.rgb2luv(im))))
    u, v = tuple(map(image.gaussian, (u, v)))
    if debug:
        image.show(l, "1. L")
        image.show(u, "1. U")
        image.show(v, "1. V")
    la, ua, va, uva = tuple(map(image.cv2array, (l, u, v, image.And(l, u, v))))
    test = image.new_from(gray)
    test2 = image.new_from(gray)
    cv.Xor(u, v, test)
    if debug:
        image.show(test, "2. U Xor V")
    cv.Set(test, 0, image.dilate(edges))
    #cv.Set(test, 0, image.invert(image.threshold(sat, threshold=8)))
    uv_score = cv.CountNonZero(test) / total
    if debug:
        image.show(
            test, "3. U Xor V - dilate(Edges) - invert(threshold(Saturation))")

    g = Grid(size)
    images = map(image.cv2array, g.split_into(test, 6))
    arr = image.cv2array(test)
    avg_mean, avg_std = arr.mean(), arr.std()

    #ms = [(a.mean(), a.std()) for a in images]
    #min_mean = min_std = 255
    #max_mean = max_std = 0
    #for m,s in ms:
    #    min_mean = min(min_mean, m)
    #    min_std = min(min_std, s)
    #    max_mean = max(max_mean, m)
    #    max_std = max(max_std, s)
    #if debug:
    #    print min_mean, min_std
    #    print avg_mean, avg_std
    #    print max_mean, max_std
    #
    #score = uv_score, min_mean, avg_mean, avg_std, max_mean
    uv_score = uv_score, avg_std

    score = cv.CountNonZero(l) / total,  cv.CountNonZero(l2) / total, \
        diff_stat[0], diff_stat[1], uv_score

    return l, score
Exemple #12
0
def measure_color_roi(im, roi, area, focused_regions, debug=False):
    im = cv.CloneImage(im)
    g = Grid(cv.GetSize(im))
    
    
    """
    contours = Contours(image.threshold(focused_regions, threshold=1)).approx_poly()
    if debug:
        test = image.new_from(im)
        cv.Set(test, 0)
        for c in contours:
            i = 1
            while c:
                cv.FillPoly(test, [[c[x] for x in range(len(c))]], cv.RGB(0,64*i,0))
                c = c.v_next()
                i += 1
        #contours.draw(test, levels=9)
        image.show(test, "Test")
    """    
    #mask = image.And(image.threshold(focused_regions, threshold=1), roi)
    #
    #canvas = image.new_from(im, nChannels=1)
    #cv.Set(canvas, 0)
    #if cv.CountNonZero(mask) <= 1:
    #    return 0, 0
    #contours = Contours(image.dilate(mask)).approx_poly()
    #for c in contours:
    #    i = 1
    #    while c:
    #        cv.FillPoly(canvas, [[c[x] for x in range(len(c))]], 255)
    #        c = c.v_next()
    #        i += 1
    #mask = image.Or(mask, canvas)
    #if debug:
    #    image.show(mask, "MASK")
    #        
    #cv.Set(im, 0, image.invert(mask))
    cv.Set(im, 0, image.invert(roi))
    
    #area = cv.CountNonZero(image.threshold(im, threshold=1))
    
    if debug:
        image.show(g.draw(im,thickness=2), "Image + ROI + Focus point mask")

    scores = []
    im = image.rgb2gray(im)
    #canvas = image.And(plane, roi)
    quadrants = g.split_in_four(im)
    hist = []
    for q,quad in enumerate(quadrants):
        #scores.append(cv.Sum(quad)[0] / float(area/4))
        h = GrayscaleHist(value_range=(1,255)).use_image(quad)
        #image.show(h.to_img(), ['gray', 'red','green','blue'][i] + ' in ' + str(q))
        hist.append(h.to_array())
    scores = []
    excluded_points = set([(2, 1), (3, 0)])
    for i,h1 in enumerate(hist):
        for j,h2 in enumerate(hist):
            if i <= j or (i,j) in excluded_points:
                continue
            h = abs(h2-h1)
            ht = GrayscaleHist(value_range=(0,255)).use_array_as_hist(h)
            scores.append((h[5:].mean(), h[5:].std()))
    means = max([x[0] for x in scores])        
    stddevs = max([x[1] for x in scores])
    return means/255.0, stddevs/255.0
Exemple #13
0
def measure_contrast(im, debug=False):
    h = GrayscaleHist(bins=64).use_image(image.rgb2gray(im))
    return h.stddev()
Exemple #14
0
def measure(im, debug=False):
    size = cv.GetSize(im)
    npixels = size[0] * size[1]
    #print 'np', npixels

    focused = get_focus_points(im, debug)
    points = convert_to_points(focused)

    if debug:
        print "\t" + str(
            len(points)), '/', npixels, '=', len(points) / float(npixels)
        print "\tlen(points) =", len(points)
        image.show(focused, "4. Focused Points")

    saturation_score = 0
    if not image.is_grayscale(im):
        edges = image.auto_edges(im)
        _, saturation, _ = image.split(image.rgb2hsv(im))
        if debug:
            image.show(saturation, "5. Saturation")
        #saturation = image.laplace(image.gaussian(saturation, 3))
        saturation = image.invert(saturation)
        mask = image.invert(image.threshold(im, threshold=16))
        if debug:
            image.show(saturation, "5.3. Laplace of Saturation")
        cv.Set(saturation, 0, mask)
        cv.Set(saturation, 0, focused)
        if debug:
            image.show(mask,
                       "5.6. Mask(focused AND invert(threshold(im, 16)))")
            image.show(saturation, "6. Set(<5.3>, 0, <5.6>)")

        saturation_score = cv.Sum(saturation)[0] / float(npixels * 255)
        print "\tSaturation Score:", saturation_score

    # light exposure
    h, s, v = image.split(image.rgb2hsv(im))
    if debug:
        image.show(h, "7. Hue")
        image.show(s, "7. Saturation")
        image.show(v, "7. Value")
    diff = cv.CloneImage(v)
    cv.Set(diff, 0, image.threshold(s, threshold=16))
    diff = image.dilate(diff, iterations=10)
    if debug:
        thres_s = image.threshold(s, threshold=16)
        image.show(thres_s, "8.3. Mask(threshold(<7.Saturation>, 16))")
        image.show(diff, "8.6. Dilate(Set(<7.Value>, 0, <8.3>), 10)")

    cdiff = cv.CountNonZero(diff)
    if cdiff > 0 and cdiff / float(npixels) > 0.01:
        test = cv.CloneImage(v)
        cv.Set(test, 0, image.invert(diff))
        s = cv.Sum(test)[0] / float(cdiff * 255)
        if debug:
            print '\tLight Exposure Score:', s
    else:
        s = 0

    if image.is_grayscale(im):
        return focused, (1, 1, 1, saturation_score, s)

    # we want to short circuit ASAP to avoid doing KMeans 50% of the image's pixels
    if len(points) > npixels / 2:
        return focused, (1, 1, 1, saturation_score, s)

    # we're so blurry we don't have any points!
    if len(points) < 1:
        return focused, (0, 0, 0, saturation_score, s)

    if debug:
        im2 = cv.CloneImage(im)
    focused_regions = image.new_from(im)
    cv.Set(focused_regions, 0)

    r = lambda x: random.randrange(1, x)
    groups = form_groups(points,
                         estimated_size=min(max(int(len(points) / 1000), 2),
                                            15))
    #groups = form_groups(points, threshold=max(cv.GetSize(im))/16)
    #print 'groups', len(groups)
    hulls = draw_groups(groups, focused_regions)
    focused_regions = image.threshold(focused_regions,
                                      threshold=32,
                                      type=cv.CV_THRESH_TOZERO)
    min_area = npixels * 0.0005
    densities = [h.points_per_pixel() for h in hulls if h.area() >= min_area]

    if debug:
        #image.show(focused, "Focused Points")
        image.show(focused_regions, "9. Focused Regions from <4>")
        cv.Sub(
            im2,
            image.gray2rgb(
                image.invert(image.threshold(focused_regions, threshold=1))),
            im2)
        image.show(im2, "10. threshold(<9>)")

    focused_regions = image.rgb2gray(focused_regions)

    densities = array(densities)
    c = cv.CountNonZero(focused_regions)
    c /= float(npixels)

    score = (c, densities.mean(), densities.std(), saturation_score, s)

    return focused, score
def measure(im, debug=False):
    size = cv.GetSize(im)
    npixels = size[0] * size[1]
    #print 'np', npixels
    
    
    focused = get_focus_points(im, debug)
    points = convert_to_points(focused)
    
    if debug:
        print "\t"+str(len(points)), '/', npixels, '=', len(points) / float(npixels)
        print "\tlen(points) =", len(points)
        image.show(focused, "4. Focused Points")

    saturation_score = 0
    if not image.is_grayscale(im):
        edges = image.auto_edges(im)
        _, saturation, _ = image.split(image.rgb2hsv(im))
        if debug:
            image.show(saturation, "5. Saturation")
        #saturation = image.laplace(image.gaussian(saturation, 3))
        saturation = image.invert(saturation)
        mask = image.invert(image.threshold(im, threshold=16))
        if debug:
            image.show(saturation, "5.3. Laplace of Saturation")
        cv.Set(saturation, 0, mask)
        cv.Set(saturation, 0, focused)
        if debug:
            image.show(mask, "5.6. Mask(focused AND invert(threshold(im, 16)))")
            image.show(saturation, "6. Set(<5.3>, 0, <5.6>)")

        saturation_score = cv.Sum(saturation)[0] / float(npixels * 255)
        print "\tSaturation Score:", saturation_score
        
    # light exposure
    h,s,v = image.split(image.rgb2hsv(im))
    if debug:
        image.show(h, "7. Hue")
        image.show(s, "7. Saturation")
        image.show(v, "7. Value")
    diff = cv.CloneImage(v)
    cv.Set(diff, 0, image.threshold(s, threshold=16))
    diff = image.dilate(diff, iterations=10)
    if debug:
        thres_s = image.threshold(s, threshold=16)
        image.show(thres_s, "8.3. Mask(threshold(<7.Saturation>, 16))")
        image.show(diff, "8.6. Dilate(Set(<7.Value>, 0, <8.3>), 10)")

    cdiff = cv.CountNonZero(diff)
    if cdiff > 0 and cdiff / float(npixels) > 0.01:
        test = cv.CloneImage(v)
        cv.Set(test, 0, image.invert(diff))
        s = cv.Sum(test)[0] / float(cdiff * 255)
        if debug:
            print '\tLight Exposure Score:', s
    else:
        s = 0
        
    if image.is_grayscale(im):
        return focused, (1, 1, 1, saturation_score, s)
    
    # we want to short circuit ASAP to avoid doing KMeans 50% of the image's pixels
    if len(points) > npixels/2:
        return focused, (1, 1, 1, saturation_score, s)

    # we're so blurry we don't have any points!
    if len(points) < 1:
        return focused, (0, 0, 0, saturation_score, s)
    
    if debug:
        im2 = cv.CloneImage(im)
    focused_regions = image.new_from(im)
    cv.Set(focused_regions, 0)
    
    r = lambda x: random.randrange(1, x)
    groups = form_groups(points,
        estimated_size=min(max(int(len(points) / 1000), 2), 15))
    #groups = form_groups(points, threshold=max(cv.GetSize(im))/16)
    #print 'groups', len(groups)
    hulls = draw_groups(groups, focused_regions)
    focused_regions = image.threshold(focused_regions, threshold=32, type=cv.CV_THRESH_TOZERO)
    min_area = npixels * 0.0005
    densities = [h.points_per_pixel() for h in hulls if h.area() >= min_area]
    
    if debug:    
        #image.show(focused, "Focused Points")
        image.show(focused_regions, "9. Focused Regions from <4>")
        cv.Sub(im2, image.gray2rgb(image.invert(image.threshold(focused_regions, threshold=1))), im2)
        image.show(im2, "10. threshold(<9>)")
    
    
    focused_regions = image.rgb2gray(focused_regions)
    
    densities = array(densities)
    c = cv.CountNonZero(focused_regions)
    c /= float(npixels)
    
    score = (c, densities.mean(), densities.std(), saturation_score, s)
    
    return focused, score
def measure(im, debug=False):
    gray = image.rgb2gray(im)
    size = cv.GetSize(im)
    total = float(size[0] * size[1])
    l = image.sub(gray, image.gaussian(gray, 5))
    l2 = image.sub(gray, image.gaussian(gray, 9))
    edges = image.dilate(image.auto_edges(im, percentage=0.2))
    if debug:
        image.show(image.threshold(l, threshold=1), "Before Edge Removal (kernel=5)")
        image.show(image.threshold(l2, threshold=1), "Before Edge Removal (kernel=9)")
    cv.Set(l, 0, image.threshold(edges, threshold=1))
    cv.Set(l2, 0, image.threshold(edges, threshold=1))
    
    l = image.threshold(l, threshold=1)
    l2 = image.threshold(l2, threshold=1)
    
    
    
    if debug:
        image.show(image.threshold(edges, threshold=1), "Edges")
        image.show(l, "After Edge Removal (kernel=5)")
        image.show(l2, "After Edge Removal (kernel=9)")
        
    noise2 = image.new_from(gray)
    cv.EqualizeHist(gray, noise2)
    cv.AbsDiff(noise2, gray, noise2)
    cv.Set(noise2, 0, image.threshold(image.sobel(im, xorder=2, yorder=2), threshold=4))
    diff = image.cv2array(noise2)
    if debug:
        image.show(noise2, "DIFF")
        print "M", diff.mean(), "S", diff.std()
    diff_stat = (diff.mean(), diff.std())
    percent_noise = cv.CountNonZero(noise2) / total
    if debug:
        image.show(noise2, "NOISE2")
        


    # magical, I don't understand how this works
    _, sat, _ = image.split(image.rgb2hsv(im))
    edges = image.auto_edges(im)
    l,u,v = tuple(map(image.equalize_hist, image.split(image.rgb2luv(im))))
    u,v = tuple(map(image.gaussian, (u,v)))
    if debug:
        image.show(l, "1. L")
        image.show(u, "1. U")
        image.show(v, "1. V")
    la,ua,va,uva = tuple(map(image.cv2array, (l,u,v, image.And(l,u,v))))
    test = image.new_from(gray)
    test2 = image.new_from(gray)
    cv.Xor(u,v,test)
    if debug:
        image.show(test, "2. U Xor V")
    cv.Set(test, 0, image.dilate(edges))
    #cv.Set(test, 0, image.invert(image.threshold(sat, threshold=8)))
    uv_score = cv.CountNonZero(test) / total
    if debug:
        image.show(test, "3. U Xor V - dilate(Edges) - invert(threshold(Saturation))")

    g = Grid(size)
    images = map(image.cv2array, g.split_into(test, 6))
    arr = image.cv2array(test)
    avg_mean, avg_std = arr.mean(), arr.std()


    #ms = [(a.mean(), a.std()) for a in images]
    #min_mean = min_std = 255
    #max_mean = max_std = 0
    #for m,s in ms:
    #    min_mean = min(min_mean, m)
    #    min_std = min(min_std, s)
    #    max_mean = max(max_mean, m)
    #    max_std = max(max_std, s)
    #if debug:
    #    print min_mean, min_std
    #    print avg_mean, avg_std
    #    print max_mean, max_std
    #
    #score = uv_score, min_mean, avg_mean, avg_std, max_mean
    uv_score = uv_score, avg_std

    score = cv.CountNonZero(l) / total,  cv.CountNonZero(l2) / total, \
        diff_stat[0], diff_stat[1], uv_score
    
    return l, score