Esempio n. 1
0
def bg_compensate(img, sigma, splinepoints, scale):
    """Reads file, subtracts background. Returns [compensated image, background]."""
    
    from PIL import Image
    # from pylab import ceil,imshow,show
    import matplotlib.pyplot as plt
    import numpy #,pylab
    from matplotlib.image import pil_to_array
    from filter import canny
    from matplotlib import cm
    import cProfile

    img = Image.open(img)
    if img.mode=='I;16':
        # 16-bit image
        # deal with the endianness explicitly... I'm not sure
        # why PIL doesn't get this right.
        imgdata = np.fromstring(img.tostring(),np.uint8)
        imgdata.shape=(int(imgdata.shape[0]/2),2)
        imgdata = imgdata.astype(np.uint16)
        hi,lo = (0,1) if img.tag.prefix == 'MM' else (1,0)
        imgdata = imgdata[:,hi]*256 + imgdata[:,lo]
        img_size = list(img.size)
        img_size.reverse()
        new_img = imgdata.reshape(img_size)
        # The magic # for maximum sample value is 281
        if img.tag.has_key(281):
            img = new_img.astype(np.float32) / img.tag[281][0]
        elif np.max(new_img) < 4096:
            img = new_img.astype(np.float32) / 4095.
        else:
            img = new_img.astype(np.float32) / 65535.
    else:
        img = pil_to_array(img)
    
    plt.subplot(1,3,1).imshow(img, cmap=cm.Greys_r)
    plt.show()
    
    if len(img.shape)>2:
        raise ValueError('Image must be grayscale')

## Create mask that will fix problem when image has black areas outside of well
    edges = canny(img, np.ones(img.shape, bool), 2, .1, .3)
    ci = np.cumsum(edges, 0)
    cj = np.cumsum(edges, 1)
    i,j = np.mgrid[0:img.shape[0], 0:img.shape[1]]
    mask = ci > 0
    mask = mask & (cj > 0)
    mask[1:,:] &= (ci[0:-1,:] < ci[-1,j[0:-1,:]])
    mask[:,1:] &= (cj[:,0:-1] < cj[i[:,0:-1],-1])
    
    import time
    t0 = time.clock()
    bg = backgr(img, mask, MODE_AUTO, sigma, splinepoints=splinepoints, scale=scale)
    print(("Executed in %f sec" % (time.clock() - t0)))
    bg[~mask] = img[~mask]

    plt.subplot(1,3,2).imshow(img - bg, cmap=cm.Greys_r)
    plt.subplot(1,3,3).imshow(bg, cmap=cm.Greys_r)
    plt.show()
Esempio n. 2
0
def bg_compensate(img, sigma, splinepoints, scale):
    '''Reads file, subtracts background. Returns [compensated image, background].'''
    
    from PIL import Image
    from pylab import ceil,imshow,show
    import numpy,pylab
    from matplotlib.image import pil_to_array
    from filter import canny
    import matplotlib
    import cProfile

    img = Image.open(img)
    if img.mode=='I;16':
        # 16-bit image
        # deal with the endianness explicitly... I'm not sure
        # why PIL doesn't get this right.
        imgdata = np.fromstring(img.tostring(),np.uint8)
        imgdata.shape=(int(imgdata.shape[0]/2),2)
        imgdata = imgdata.astype(np.uint16)
        hi,lo = (0,1) if img.tag.prefix == 'MM' else (1,0)
        imgdata = imgdata[:,hi]*256 + imgdata[:,lo]
        img_size = list(img.size)
        img_size.reverse()
        new_img = imgdata.reshape(img_size)
        # The magic # for maximum sample value is 281
        if img.tag.has_key(281):
            img = new_img.astype(np.float32) / img.tag[281][0]
        elif np.max(new_img) < 4096:
            img = new_img.astype(np.float32) / 4095.
        else:
            img = new_img.astype(np.float32) / 65535.
    else:
        img = pil_to_array(img)
    
    pylab.subplot(1,3,1).imshow(img, cmap=matplotlib.cm.Greys_r)
    pylab.show()
    
    if len(img.shape)>2:
        raise ValueError('Image must be grayscale')

## Create mask that will fix problem when image has black areas outside of well
    edges = canny(img, np.ones(img.shape, bool), 2, .1, .3)
    ci = np.cumsum(edges, 0)
    cj = np.cumsum(edges, 1)
    i,j = np.mgrid[0:img.shape[0], 0:img.shape[1]]
    mask = ci > 0
    mask = mask & (cj > 0)
    mask[1:,:] &= (ci[0:-1,:] < ci[-1,j[0:-1,:]])
    mask[:,1:] &= (cj[:,0:-1] < cj[i[:,0:-1],-1])
    
    import time
    t0 = time.clock()
    bg = backgr(img, mask, MODE_AUTO, sigma, splinepoints=splinepoints, scale=scale)
    print ("Executed in %f sec" % (time.clock() - t0))
    bg[~mask] = img[~mask]

    pylab.subplot(1,3,2).imshow(img - bg, cmap=matplotlib.cm.Greys_r)
    pylab.subplot(1,3,3).imshow(bg, cmap=matplotlib.cm.Greys_r)
    pylab.show()
def drawLanesPipeline(image):
    """ Process one image, detect two lanes and highlight them with solid color lines
    (1) apply the gaussian blur
    (2) convert bgr to hsv and segment while and yellow, because it is easier in HSV space than RGB
    (3) Canny edge detection
    (4) apply the designed mask to the image to obtian the region of interest
    (5) apply hough transform to get lines
    (6) augmented the lanes on the original image

    :param image: input image
    :return: an augmented image with two lane highlighted
    """

    #---------set parameters----------#
    # gaussian_blur para
    kernel_size = 5
    # canny edege detection para
    low_threshold = 50
    high_threshold = 150
    # region_of_interest para
    height, width, _ = image.shape
    scale_w = 7 / 16
    scale_h = 11 / 18
    left_bottom = [0, height - 1]
    right_bottom = [width - 1, height - 1]
    left_up = [scale_w * width, scale_h * height]
    right_up = [(1 - scale_w) * width, scale_h * height]
    # hough_line para
    rho = 2  # distance resolution in pixels of the Hough grid
    theta = np.pi / 180  # angular resolution in radians of the Hough grid
    threshold = 15  # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 15  # minimum number of pixels making up a line
    max_line_gap = 40  # maximum gap in pixels between connectable line segments
    #---------------------------------#

    # Define a kernel size and apply Gaussian smoothing
    blur_gray = gaussian_blur(image, kernel_size)

    # convert image from bgr to hsv
    hsv_img = cv2.cvtColor(blur_gray, cv2.COLOR_BGR2HSV)

    # filter out the white and yellow segments (lanes are either white or yellow in this case)
    filtered_hsv = selectWhiteAndYellow(hsv_img)

    # Apply Canny edge detection
    edges = canny(filtered_hsv, low_threshold, high_threshold)

    # create a masked edges image
    vertices = np.array([[left_bottom, left_up, right_up, right_bottom]],
                        dtype=np.int32)
    masked_edges = region_of_interest(edges, vertices)

    # Run Hough on edge detected image
    # Output "lines" is an array containing endpoints of detected line segments
    line_image = hough_lines(masked_edges, rho, theta, threshold,
                             min_line_length, max_line_gap)

    # Draw the lines on the edge image
    output = weighted_img(line_image, image)

    return output