Ejemplo n.º 1
0
def fom(img, img_gold_std, alpha = DEFAULT_ALPHA):
    """
    Computes Pratt's Figure of Merit for the given image img, using a gold
    standard image as source of the ideal edge pixels.
    """

    # To avoid oversmoothing, we apply canny edge detection with very low
    # standard deviation of the Gaussian kernel (sigma = 0.1).
    edges_img = canny(img, 0.1, 20, 50)
    edges_gold = canny(img_gold_std, 0.1, 20, 50)
    
    # Compute the distance transform for the gold standard image.
    dist = distance_transform_edt(np.invert(edges_gold))

    fom = 1.0 / np.maximum(
        np.count_nonzero(edges_img),
        np.count_nonzero(edges_gold))

    N, M = img.shape

    for i in xrange(0, N):
        for j in xrange(0, M):
            if edges_img[i, j]:
                fom += 1.0 / ( 1.0 + dist[i, j] * dist[i, j] * alpha)

    fom /= np.maximum(
        np.count_nonzero(edges_img),
        np.count_nonzero(edges_gold))    

    return fom
Ejemplo n.º 2
0
def fom(img, img_gold_std, alpha=DEFAULT_ALPHA):
    """
    Computes Pratt's Figure of Merit for the given image img, using a gold
    standard image as source of the ideal edge pixels.
    """

    # To avoid oversmoothing, we apply canny edge detection with very low
    # standard deviation of the Gaussian kernel (sigma = 0.1).
    edges_img = canny(img, 0.1, 20, 50)
    edges_gold = canny(img_gold_std, 0.1, 20, 50)

    # Compute the distance transform for the gold standard image.
    dist = distance_transform_edt(np.invert(edges_gold))

    fom = 1.0 / np.maximum(np.count_nonzero(edges_img),
                           np.count_nonzero(edges_gold))

    N, M = img.shape

    for i in xrange(0, N):
        for j in xrange(0, M):
            if edges_img[i, j]:
                fom += 1.0 / (1.0 + dist[i, j] * dist[i, j] * alpha)

    fom /= np.maximum(np.count_nonzero(edges_img),
                      np.count_nonzero(edges_gold))

    return fom
Ejemplo n.º 3
0
def get_contours(img):
    '''Calculate the image contours using Canny edge detection.
    Automatically adjusts the Canny parameters so that the ratio of edge
    pixels in the image falls within a certain range.

    Args:
        img (np.ndarray): image as a numpy array

    Returns:
        Image contours as a numpy array of 0s and 1s
    '''
    rmin = 0.05
    rmax = 0.15

    n = 105
    alpha = 0.35
    beta = 1.5

    sp0 = sp1 = 0
    sig = 1
    for i in range(5):
        c = canny(img, sig, n, alpha, beta)
        r = c.sum() / c.size
        if r < rmin:
            alpha -= .02
            beta -= .1
        elif r > rmax:
            alpha += .05
            beta += .1
        else:
            break

    return c
Ejemplo n.º 4
0
def localize(img2):
    edges = canny(img2)
    edges = np.array(edges * 255, dtype=np.uint8)

    image1, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE,
                                                   cv2.CHAIN_APPROX_NONE)

    out = cv2.drawContours(img2, contours, -1, (0, 250, 0), 1)

    try:
        hierarchy = hierarchy[0]
    except:
        hierarchy = []

    height, width, _ = img2.shape
    min_x, min_y = width, height
    max_x = max_y = 0

    # computes the bounding box for the contour, and draws it on the frame,
    for contour, hier in zip(contours, hierarchy):
        (x, y, w, h) = cv2.boundingRect(contour)
        min_x, max_x = min(x, min_x), max(x + w, max_x)
        min_y, max_y = min(y, min_y), max(y + h, max_y)
        if w > 80 and h > 80:
            cv2.rectangle(img2, (x, y), (x + w, y + h), (255, 0, 0), 2)

    if max_x - min_x > 0 and max_y - min_y > 0:
        cv2.rectangle(img2, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)

    cv2.imshow("Show", img2)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Ejemplo n.º 5
0
def main(infile):
    c = canny.canny()
    img3 = misc.imread(infile, mode='RGBA')
    (height, width, channels) = img3.shape
    img = numpy.zeros((height,width))
    img[:,:] += img3[:,:,0] << 24
    img[:,:] += img3[:,:,1] << 16
    img[:,:] += img3[:,:,2] << 8
    img[:,:] += img3[:,:,3] << 0
    edges = c.main(50, 100, img)
    print edges
Ejemplo n.º 6
0
 def edge_detect(hr):
     canned = []
     if 1:
         for hr_i in hr:
             canned.append(canny(hr_i.unsqueeze(0).half(),use_cuda=True))
         canned = torch.cat(canned,dim=0).detach().float()
         EDGE_SIZE = 1
         canned[:,:,:EDGE_SIZE,:] = 0
         canned[:,:,-EDGE_SIZE:,:] = 0
         canned[:,:,:,:EDGE_SIZE] = 0
         canned[:,:,:,-EDGE_SIZE:] = 0
     return canned
Ejemplo n.º 7
0
def test_canny(img):
    start = perf_counter()
    res = canny(img)
    finish = perf_counter()
    cv2.imshow('Canny', res)
    print('Time = ' + str(finish - start))

    start = perf_counter()
    res_cv = cv2.Canny(img, 50, 70)
    finish = perf_counter()
    cv2.imshow('OpenCV Canny', res_cv)
    print('Time_opencv = ' + str(finish - start))

    mse_value = mse(res, res_cv)
    print('MSE: ' + str(mse_value) + '\n')
def run(updateImageSignal, mode, setLabelSignal):
    camera.capture('image.jpg')
    ogImg = cv2.imread('image.jpg')
    colorImg = ogImg.copy()
    img = resize(ogImg, 50)
    imgContour = img.copy()

    img = img[20:200, 0:500]
    imgContour = imgContour[20:200, 0:500]

    cv2.imwrite('imageCrop.jpg', imgContour)

    form = canny(imgContour)

    print(form.corners)

    imgContour = resize(imgContour, 50)
    cv2.imwrite('output.jpg', imgContour)
    updateImageSignal.emit()
    classifyForm(form, mode, setLabelSignal)
Ejemplo n.º 9
0
    """
    canvasImg = copy(rawImg)
    lines = cv2.HoughLinesP(edges,
                            rho=args.rho,
                            theta=args.theta,
                            threshold=args.threshold,
                            lines=args.lines,
                            minLineLength=args.minLineLength,
                            maxLineGap=args.maxLineGap)
    
    try:
        lines = np.asarray([line for l in lines for line in l])
        if (args.debug or args.opt):
            p = ProgressBar(1, len(lines))
            i = 0
            for x1, y1, x2, y2 in lines:
                cv2.line(canvasImg, (x1, y1), (x2, y2), (0, 255, 0), 2)
                p.update(i+1)
                i += 1
    except TypeError, ZeroDivisionError:
        pass
    cv2.imwrite("./results/result.jpg", canvasImg)

    return (lines)

if __name__ == "__main__":
    args             = get_args()
    pre_img, raw_img = preprocess(args)
    edges_img        = canny(pre_img, args)
    hough_img        = hough(edges_img, raw_img, args)
Ejemplo n.º 10
0
    theta = theta + ran_theta
    # Make sure it doesn't get below 0 (max can get up to is 135+15=150)
    if theta < 0:
        theta = 180+theta
    
    return theta


if __name__ == "__main__":
    # Read image and convert it to double, and scale each R,G,B
    # channel to range [0,1].
    imRGB = array(Image.open('orchid.jpg'))
    
    # Get monochrome image
    mono_im = convert_monochrome(imRGB)
    canny_im = can.canny(mono_im, 2.0, 7500, 2000)
    theta_im = get_theta(mono_im)
    
    imRGB = double(imRGB) / 255.0
    plt.clf()
    plt.axis('off')
    
    sizeIm = imRGB.shape
    sizeIm = sizeIm[0:2]
    # Set radius of paint brush and half length of drawn lines
    rad = 3
    halfLen = 5
    
    # Set up x, y coordinate images, and canvas.
    [x, y] = np.meshgrid(np.array([i+1 for i in range(int(sizeIm[1]))]), np.array([i+1 for i in range(int(sizeIm[0]))]))
    canvas = np.zeros((sizeIm[0],sizeIm[1], 3))
Ejemplo n.º 11
0
 def __init__(self):
     super(FromImage, self).__init__()
     self.theCanny = canny()
     self.showLine = displayLine()
     self.predLine = lineImg()
     self.theROI = roi()
Ejemplo n.º 12
0
Archivo: shape.py Proyecto: bhicks2/OCR
    plt.yticks([])
    for spine in plt.gca().spines.values():
        spine.set_visible(False)
    plt.show()


def plot_edge(img1, edgepts):
    data = 255 * np.ones(img1.shape)
    data[edgepts[:, 0], edgepts[:, 1]] = 0
    edge_img = Image.fromarray(data)
    plt.imshow(edge_img, cmap='gray')
    plt.xticks([])
    plt.yticks([])
    for spine in plt.gca().spines.values():
        spine.set_visible(False)
    plt.show()


# Main function
if __name__ == '__main__':
    filenames = ['a1.png']
    for file in filenames:
        img = imread(file, flatten=True)
        edges = canny.canny(img, sigma=0.8, low_thresh=0.01, high_thresh=0.1)
        edges_sample = edges[np.sort(
            np.random.choice(edges.shape[0], (200, ), replace=False))]
        # plot_fig(img)
        # plot_edge(img, edges)
        # plot_edge(img, edges_sample)
        shape_hist = build_histograms(
            edges_sample, 5, 12, np.sqrt(img.shape[0]**2 + img.shape[1]**2))
Ejemplo n.º 13
0
 rad = 1
 
 # Set up x, y coordinate images, and canvas.
 [x, y] = np.meshgrid(np.array([i+1 for i in range(int(sizeIm[1]))]), 
     np.array([i+1 for i in range(int(sizeIm[0]))]))
 canvas = np.zeros((sizeIm[0],sizeIm[1], 3))
 canvas.fill(-1) ## Initially mark the canvas with a value out of range.
 # Negative values will be used to denote pixels which are unpainted.
 
 # Random number seed
 np.random.seed(29645)
 
 red, green, blue = imRGB[:,:,0], imRGB[:,:,1], imRGB[:,:,2]
 imGray = 0.30 * red + 0.59 * green + 0.11 * blue
 
 part3 = canny.canny(imGray, 2.0, 25, 5)
 
 # Orientation of paint brush strokes
 theta = 2 * pi * np.random.rand(1,1)[0][0]
 gradientArray = findAngle(imGray, 4.0, 5)
 # Set vector from center to one end of the stroke.
 
 time.time()
 time.clock()
 numOfStrokes = 0
 while (len(np.where(canvas==-1)[0])>0):
     
     leftHalfLen = 5
     rightHalfLen = 5
     
     # finding a negative pixel
Ejemplo n.º 14
0
def getdropcenters(image, sizedict, entire):
    temp = entire.split("/")[-1]
    name = temp.split(".")[0]
    height, width = sizedict[0], sizedict[1]
    #== Processing =======================================================================
    title = image.split(".")[0]
    #-- Read image -----------------------------------------------------------------------
    im = cv2.imread(image)
    im = fillhole(im)
    contours, _ = canny(im, CANNY_THRESH_1, CANNY_THRESH_2)

    contours_area = []
    # calculate area and filter into new array
    for con in contours:
        area = cv2.contourArea(con)
        if 10000 < area < 25000:
            contours_area.append(con)

    contours_circles = []

    # check if contour is of circular shape
    for con in contours_area:
        perimeter = cv2.arcLength(con, True)
        area = cv2.contourArea(con)
        if perimeter == 0:
            break
        circularity = 4*math.pi*(area/(perimeter*perimeter))
        if 0.6 < circularity < 1.4:
            contours_circles.append(con)

    centers = []
    bounds = []
    plt.imshow(im)
    temp = []
    for c in contours_circles:
        (x,y),radius = cv2.minEnclosingCircle(c)
        temp.append((x,y,radius))

    count = 1
    length = len(contours_circles)
    actual = [1] * len(contours_circles)
    for i in range(length):
        x,y,r = temp[i]
        for j in range(i+1, length):
            x1, y1, r2 = temp[j]
            if abs(x-x1) < r and abs(y-y1) < r:
                if actual[j] == 1:
                    actual[j] = 0

    for c in range(length):
        if actual[c] == 1:
            x,y,r = temp[c]
            radius = r /math.sqrt(2)
            plt.plot(x, y, 'ro')
            centers.append((round(x),round(y),round(radius)))

            lowerx = max(0, round(x - radius))
            higherx = min(width, round(x + radius))
            lowery = max(0, round(y - radius))
            highery = min(height, round(y + radius))
            bounds.append((lowery, highery, lowerx, higherx))

            plt.text(x, y + 5, str(count))
            count +=1
    # print("BOUNDS: " + str(bounds))
    
    directory = "centers"
    if not os.path.exists(directory):
        os.makedirs(directory)
    plt.savefig("centers/" + name + "centers" + ".jpg")
    plt.clf()
    return centers, bounds
Ejemplo n.º 15
0
def getdropcenters(image):
    #-- Read image -----------------------------------------------------------------------
    im = cv2.imread(image)
    im = fillhole(im)
    contours, _ = canny(im, CANNY_THRESH_1, CANNY_THRESH_2)

    # cv2.drawContours(im, contours, -1, (0, 0, 255), 3)
    # cv2.imshow("all contours", im)
    # cv2.waitKey(0)

    # print("CONTOURS:" + str(len(contours)))

    contours_area = []
    # calculate area and filter into new array
    for con in contours:
        area = cv2.contourArea(con)
        if 20 < area < 1000:
            contours_area.append(con)

    # cv2.drawContours(im, contours, -1, (0, 255, 0), 3)
    # cv2.imshow("contours area", im)
    # cv2.waitKey(0)

    # print("CONTOURS AREAS:" + str(len(contours_area)))

    contours_circles = []

    # check if contour is of circular shape
    for con in contours_area:
        perimeter = cv2.arcLength(con, True)
        area = cv2.contourArea(con)
        if perimeter == 0:
            break
        circularity = 4 * math.pi * (area / (perimeter * perimeter))
        if 0.6 < circularity < 1.4:
            contours_circles.append(con)

    # centers = []
    # bounds = []
    # plt.imshow(im)
    # for c in contours_circles:
    #     (x,y),radius = cv2.minEnclosingCircle(c)
    #     plt.plot(x, y, 'ro')

    centers = []
    bounds = []
    plt.imshow(im)
    temp = []
    for c in contours_circles:
        (x, y), radius = cv2.minEnclosingCircle(c)
        temp.append((x, y, radius))

    count = 1
    length = len(contours_circles)
    actual = [1] * len(contours_circles)
    for i in range(length):
        x, y, r = temp[i]
        for j in range(i + 1, length):
            x1, y1, r2 = temp[j]
            if abs(x - x1) < r and abs(y - y1) < r:
                if actual[j] == 1:
                    actual[j] = 0

    final = []
    for c in range(length):
        if actual[c] == 1:
            final.append(contours_circles[c])
            x, y, r = temp[c]
            radius = r / math.sqrt(2)
            plt.plot(x, y, 'ro')
            centers.append((round(x), round(y), round(radius)))

            plt.text(x, y + 5, str(count))
            count += 1

    print(len(centers))

    cv2.drawContours(im, final, -1, (255, 0, 0), 3)
    cv2.imshow("contours circles", im)
    cv2.waitKey(0)

    print("CONTOURS CIRCLES:" + str(len(final)))

    directory = "centers"
    if not os.path.exists(directory):
        os.makedirs(directory)
    plt.savefig("centers/" + datetime.now().strftime('%Y-%m-%d=%H-%M-%S') +
                "centers" + ".jpg")
    plt.clf()
Ejemplo n.º 16
0
Archivo: p2.py Proyecto: blackle/Year_3
    
    # Set up x, y coordinate images, and canvas.
    [x, y] = np.meshgrid(np.array([i+1 for i in range(int(sizeIm[1]))]), np.array([i+1 for i in range(int(sizeIm[0]))]))
    canvas = np.zeros((sizeIm[0],sizeIm[1], 3))
    canvas.fill(-1) ## Initially mark the canvas with a value out of range.
    # Negative values will be used to denote pixels which are unpainted.

    cannyluma = None
    cannyimg = None 
    mytheta = None
    mygradient = None


    if(part_number >= 3):
        cannyluma = imRGB[:,:,1] * 0.59 + imRGB[:,:,2] * 0.11 + imRGB[:,:,0] * 0.30 
        cannyimg = canny.canny(cannyluma, 2.0, 25, 5)
        if(part_number == 3):
            cannyimgfilename = os.path.join(args.dir, base_file+'_canny'+ext)
            colorImSave(cannyimgfilename, cannyimg, 'gray')
    
    if(part_number >= 5):
        mythetafilename = os.path.join(args.dir, base_file+'_theta'+ext)
        if(part_number >= 7):
            (mytheta, mygradient) = computeGradient(cannyluma, 2, cannyimg, 10, True)
            if(part_number == 7):
                colorImSave(mythetafilename, mytheta)
        else:
            (mytheta, mygradient) = computeGradient(cannyluma, 4, cannyimg, 1, False)
            if(part_number == 5):
                colorImSave(mythetafilename, mytheta)
Ejemplo n.º 17
0
    rad = 1

    # Set up x, y coordinate images, and canvas.
    [x, y] = np.meshgrid(np.array([i + 1 for i in range(int(sizeIm[1]))]),
                         np.array([i + 1 for i in range(int(sizeIm[0]))]))
    canvas = np.zeros((sizeIm[0], sizeIm[1], 3))
    canvas.fill(-1)  ## Initially mark the canvas with a value out of range.
    # Negative values will be used to denote pixels which are unpainted.

    # Random number seed
    np.random.seed(29645)

    red, green, blue = imRGB[:, :, 0], imRGB[:, :, 1], imRGB[:, :, 2]
    imGray = 0.30 * red + 0.59 * green + 0.11 * blue

    part3 = canny.canny(imGray, 2.0, 25, 5)

    # Orientation of paint brush strokes
    theta = 2 * pi * np.random.rand(1, 1)[0][0]
    gradientArray = findAngle(imGray, 4.0, 5)
    # Set vector from center to one end of the stroke.

    time.time()
    time.clock()
    numOfStrokes = 0
    while (len(np.where(canvas == -1)[0]) > 0):

        leftHalfLen = 5
        rightHalfLen = 5

        # finding a negative pixel
Ejemplo n.º 18
0
import sys

from gradient import gradient
from nonmax import nonmax
from canny import canny
from bilateral import bilateral

if __name__ == '__main__':
    if len(sys.argv) < 5:
        print('Usage: python main.py (command) [parameters...] (input_image) (output_image) \n\
        commands: \n\
            canny (sigma) (thr_high) (thr_low) \n\
            dir (sigma) \n\
            nonmax (sigma) \n\
            bilateral (sigma_d) (sigma_r)')
        sys.exit(0)

    input_image = np.float64(imread(sys.argv[-2])) / 255.
    output_image = sys.argv[-1]

    command = sys.argv[1]
    if command == 'dir':
        _, directions = gradient(input_image, float(sys.argv[2]))
        imsave(output_image, directions)
    elif command == 'nonmax':
        imsave(output_image, nonmax(input_image, float(sys.argv[2])))
    elif command == 'canny':
        imsave(output_image, canny(input_image, float(sys.argv[2]), float(sys.argv[4]), float(sys.argv[3])))
    elif command == 'bilateral':
        imsave(output_image, bilateral(input_image, np.float64(sys.argv[2]), np.float64(sys.argv[3]) / 255))