예제 #1
0
def test_probabilistic_hough_bad_input():
    img = np.zeros(100)
    img[10] = 1

    # Expected error, img must be 2D
    with testing.raises(ValueError):
        transform.probabilistic_hough_line(img)
예제 #2
0
def test_probabilistic_hough():
    # Generate a test image
    img = np.zeros((100, 100), dtype=int)
    for i in range(25, 75):
        img[100 - i, i] = 100
        img[i, i] = 100

    # decrease default theta sampling because similar orientations may confuse
    # as mentioned in article of Galambos et al
    theta = np.linspace(0, np.pi, 45)
    lines = transform.probabilistic_hough_line(img,
                                               threshold=10,
                                               line_length=10,
                                               line_gap=1,
                                               theta=theta)
    # sort the lines according to the x-axis
    sorted_lines = []
    for line in lines:
        line = list(line)
        line.sort(key=lambda x: x[0])
        sorted_lines.append(line)

    assert ([(25, 75), (74, 26)] in sorted_lines)
    assert ([(25, 25), (74, 74)] in sorted_lines)

    # Execute with default theta
    transform.probabilistic_hough_line(img, line_length=10, line_gap=3)
예제 #3
0
def test_probabilistic_hough_bad_input():
    img = np.zeros(100)
    img[10] = 1

    # Expected error, img must be 2D
    with testing.raises(ValueError):
        transform.probabilistic_hough_line(img)
def find_objects_by_edges(image_path, new_image_path, params):
    hough_line_color = params["hough_line_color"]
    hough_mode = params["hough_mode"]
    blur_strength = params["blur_strength"]
    canny_lower = params["canny_lower"]
    canny_upper = params["canny_upper"]
    hough_line_length = params["hough_line_length"]
    hough_line_treshold =  params["hough_line_treshold"]
    hough_line_gap =  params["hough_line_gap"]
    hough_circle_min_radius = params["hough_circle_min_radius"]
    hough_circle_max_radius = params["hough_circle_max_radius"]
    hough_circle_param1 = params["hough_circle_param1"]
    hough_circle_param2 = params["hough_circle_param2"]
    hough_circle_min_dist = params["hough_circle_min_dist"]
    img = imread(image_path)
    blur = cv2.medianBlur(img,blur_strength)
    edges = cv2.Canny(blur, canny_lower, canny_upper, apertureSize=3)
    if hough_mode == "lines":
      lines = probabilistic_hough_line(edges, threshold=hough_line_treshold, line_length=hough_line_length, line_gap=hough_line_gap)
      line_r = int(hough_line_color[0])
      line_g = int(hough_line_color[1])
      line_b = int(hough_line_color[2])
      for line in lines:
          p0, p1 = line
          cv2.line(img,(p0[0], p0[1]),(p1[0], p1[1]),(line_r, line_g, line_b), 2)
    elif hough_mode == "circles":
      circles = cv2.HoughCircles(edges,cv2.HOUGH_GRADIENT,1,hough_circle_min_dist, param1=hough_circle_param1,param2=hough_circle_param2,minRadius=hough_circle_min_radius,maxRadius=hough_circle_max_radius)
      if circles is not None:
          circles = np.uint16(np.around(circles))
          for i in circles[0,:]:
                # draw the outer circle
            cv2.circle(img,(i[0],i[1]),i[2],(255,255,0),5)
            # draw the center of the circle
            cv2.circle(img,(i[0],i[1]),2,(255,0,255),3)
    elif hough_mode == "lines_and_circles":
      lines = probabilistic_hough_line(edges, threshold=hough_line_treshold, line_length=hough_line_length, line_gap=hough_line_gap)
      for line in lines:
          p0, p1 = line
          cv2.line(img,(p0[0], p0[1]),(p1[0], p1[1]),(255, 0, 255), 2)
      circles = cv2.HoughCircles(edges,cv2.HOUGH_GRADIENT,1,hough_circle_min_dist, param1=hough_circle_param1,param2=hough_circle_param2,minRadius=hough_circle_min_radius,maxRadius=hough_circle_max_radius)
      if circles is not None:
          circles = np.uint16(np.around(circles))
          for i in circles[0,:]:
                # draw the outer circle
            cv2.circle(img,(i[0],i[1]),i[2],(255,255,0),5)
            # draw the center of the circle
            cv2.circle(img,(i[0],i[1]),2,(255,0,255),3)
    # display(Image.fromarray(img))
    save_image(img, new_image_path, "edges")
예제 #5
0
def prob_hough_line(img):
    # edges = canny(img, sigma=4)
    edges = canny(img, sigma=5, low_threshold=0.05, high_threshold=0.10)
    lines = probabilistic_hough_line(edges,
                                     threshold=50,
                                     line_length=20,
                                     line_gap=10)
    # Generating figure 2
    fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)
    ax = axes.ravel()
    ax[0].imshow(img, cmap=cm.gray)
    ax[0].set_title('Input image')
    ax[1].imshow(edges, cmap=cm.gray)
    ax[1].set_title('Canny edges')
    ax[2].imshow(edges * 0)
    for line in lines:
        p0, p1 = line
        ax[2].plot((p0[0], p1[0]), (p0[1], p1[1]))
    ax[2].set_xlim((0, img.shape[1]))
    ax[2].set_ylim((img.shape[0], 0))
    ax[2].set_title('Probabilistic Hough')
    for a in ax:
        a.set_axis_off()
    plt.tight_layout()
    plt.show()
예제 #6
0
def get_image_dynamics(image):
    edges = canny(image, 1, .4, .6)
    lines = probabilistic_hough_line(edges, line_gap=6)
    TAN15 = 0.26794919243
    TAN75 = 3.73205080757
    EPS = 0.0000000005
    c1, c2, c3 = (0, 0, 0)
    dynamics = np.zeros(6, dtype=np.float64)
    for (x1, y1), (x2, y2) in lines:
        aslope = abs((x2 - x1) / (y2 - y1 + EPS))
        linelen = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        if (aslope < TAN15):
            c1 = c1 + 1
            dynamics[0] = dynamics[0] + aslope
            dynamics[3] = linelen
        elif (aslope > TAN75):
            c2 = c2 + 1
            dynamics[1] = dynamics[1] + aslope
            dynamics[4] = linelen
        else:
            c3 = c3 + 1
            dynamics[2] = dynamics[2] + aslope
            dynamics[5] = linelen
    if (c1 > 0):
        dynamics[0] /= c1
        dynamics[1] /= c1
    if (c2 > 0):
        dynamics[2] /= c2
        dynamics[3] /= c2
    if (c3 > 0):
        dynamics[4] /= c3
        dynamics[5] /= c3
    return dynamics;
예제 #7
0
def get_line(image):
    thresh = threshold_otsu(image)
    normalize = image > thresh

    edges = canny(normalize, 1.5)

    min_line_length = int(min(image.shape) / 2)

    lines = []
    while not lines:
        lines = probabilistic_hough_line(edges,
                                         seed=16,
                                         line_length=min_line_length,
                                         line_gap=3)
        min_line_length = int(min_line_length * 0.9)

    longest_line = None
    longest_line_distance = 0.0

    for line in lines:
        point_a, point_b = line
        distance = euclidean(point_a, point_b)

        if longest_line_distance < distance:
            longest_line = line
            longest_line_distance = distance

    return longest_line
예제 #8
0
def extract_edge_segments(d: np.ndarray) -> list:
    """
    Given an image, ``d``, extract line segments along the edges
    """
    edges = feature.canny(d, sigma=2)
    lines = transform.probabilistic_hough_line(edges, threshold=5, line_length=7, line_gap=2)
    return lines
예제 #9
0
def lines_detection(img_gray, img_height, img_width, chart_type):
    if chart_type == 'table':
        thr = 80
        gap = 2
        length = min(img_height, img_width)//2
    else:
        thr = 50
        gap = 10
        length = 50
    ## Sobel
    edge_sobel = sobel(img_gray)
    thresh = threshold_otsu(edge_sobel)
    edge_binary = edge_sobel > thresh
    # IMGIO.imsave('./edge.png', edge_sobel)
    # im = Image.fromarray((edge_binary * 255.0).astype('uint8'), mode='L')
    # im.save('./edge.png')
    # edge_binary = canny(img_gray, sigma=3)
    lines = probabilistic_hough_line(edge_binary, threshold=thr, line_length=length,
                                     line_gap=gap, theta=np.asarray([-PI/2, 0, PI/2]))
    ## TODO: It seems that the dot on the axis will interrupt the line detection of image....

    # Save Result
    fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)
    ax = axes.ravel()

    ax[0].imshow(img_gray, cmap=cm.gray)
    ax[0].set_title('Input image')

    ax[1].imshow(edge_binary, cmap=cm.gray)
    ax[1].set_title('Sobel edges')

    ax[2].imshow(edge_binary * 0, cmap=cm.gray)
    line_exist = []
    def swap(p0, p1):
        return p1, p0
    for line in lines:
        p0, p1 = line
        # save in order of r/c smaller one, first.
        if p0[0] > p1[0]:
            p0, p1 = swap(p0, p1)
        if p0[0] == p1[0] and p0[1] > p1[1]:
            p0, p1 = swap(p0, p1)
        # remove the replicated lines
        line_exist = repli_lines(line_exist, p0, p1)
    for line in line_exist:
        p0, p1 = line
        ax[2].plot((p0[0], p1[0]), (p0[1], p1[1]))
    ax[2].set_xlim((0, edge_binary.shape[1]))
    ax[2].set_ylim((edge_binary.shape[0], 0))
    ax[2].set_title('Probabilistic Hough with replicated line remove')

    for a in ax:
        a.set_axis_off()
    # plt.savefig('edge_gray.png')
    plt.tight_layout()
    plt.show()

    return line_exist

    '''
예제 #10
0
def compute_probabilistic_hough_lines(image):
    lines = probabilistic_hough_line(
        image,
        threshold=g.ipm.hough_p_parameters['threshold'],
        line_length=g.ipm.hough_p_parameters['line_length'],
        line_gap=g.ipm.hough_p_parameters['line_gap'])
    return lines
예제 #11
0
파일: hough.py 프로젝트: sssruhan1/xray
def hough_horizontal(edges, fn, hough_line_len=30, save=True, show=True):
    div = 9
    hough_end = math.pi/2 
    de = 180/div
    hough_start = math.pi/2 - math.pi/div
    ds = 0
    hough_gap = 0.001
    hough_line_gap = 5
    hough_angle = np.arange(hough_start,hough_end, hough_gap)

    lines = probabilistic_hough_line(edges, threshold=30, line_gap=hough_line_gap,line_length=hough_line_len, theta=hough_angle)
    plt.close()
    plt.imshow(edges, cmap=plt.cm.gray)

    pts = []
    for line in lines:
        p0, p1 = line
        pts.append(p0)
        pts.append(p1)
        plt.plot((p0[0], p1[0]), (p0[1], p1[1]), linewidth=1, color='g')
    if save:
        feature = 'h_range' + str(int(ds))+ '_' + str(int(de)) + '_gap' + str(int(hough_line_gap)) + '_len' + str(int(hough_line_len))
        fn = fn + feature        
        plt.title('horizontal hough line' + feature  )
        saveplot(plt, fn)
    return pts, lines
def compute_edgelets(image, sigma=3):
    """Create edgelets as in the paper.
    Uses canny edge detection and then finds (small) lines using probabilstic
    hough transform as edgelets.
    """
    gray_img = color.rgb2gray(image)
    edges = feature.canny(gray_img, sigma)
    lines = transform.probabilistic_hough_line(edges, threshold=10, line_length=50,
                                               line_gap=10)
    locations = []
    directions = []
    strengths = []

    for p0, p1 in lines:
        p0, p1 = np.array(p0), np.array(p1)
        locations.append((p0 + p1) / 2)
        directions.append(p1 - p0)
        strengths.append(np.linalg.norm(p1 - p0))

    # convert to numpy arrays and normalize
    locations = np.array(locations)
    directions = np.array(directions)
    strengths = np.array(strengths)

    directions = np.array(directions) / np.linalg.norm(directions, axis=1)[:, np.newaxis]

    return (locations, directions, strengths)
예제 #13
0
파일: hough.py 프로젝트: sssruhan1/xray
def hough_vertical(edges, fn=None, hough_line_len=30, line_gap=5, save=False, show=False, raw=None, xdiff=0, ydiff=0):
    height = edges.shape[0]
    width = edges.shape[1]
    div = 9
    hough_end = 0 + math.pi/div
    hough_start = 0 - math.pi/div
    hough_gap = 0.001
    hough_angle = np.arange(hough_start,hough_end, hough_gap)

    lines_ret = probabilistic_hough_line(edges, threshold=30, line_gap=line_gap,line_length=hough_line_len, theta=hough_angle)
    from src.utils.util import tuple2list
    lines = tuple2list(lines_ret)
    from src.utils.util import changecoord
    if xdiff != 0 and ydiff !=0:
     lines= changecoord(lines, xdiff, ydiff)
    if lines is not None:
        if save is True or  show is True:

            if raw is None:
                logging.error('background image is not provided')
                sys.exit(1)

            from src.utils.io import add_lines
            raw = add_lines(lines, raw)

            if show is True:
                raw.show()

            if save is True:
                raw.save(fn + '.jpg')


    return lines, raw
예제 #14
0
    def run_phough_transform(self, filename=None):
        """ Run the Probabilistic Hough Transform """
        print('Running Probabilistic Hough Transform')
        if filename is None:
            filename = './output/phough_transform'

        self.lines = probabilistic_hough_line(
            self.edge_labels,
            line_length=self.phough_min_line_length_px,
            line_gap=self.phough_line_gap_px,
            threshold=self.phough_accumulator_threshold)

        if self.show_figures | self.save_figures:
            fig, ax = plt.subplots(1, 1)
            for line in self.lines:
                p0, p1 = line
                ax.plot((p0[0], p1[0]), (p0[1], p1[1]))
            ax.set_xlim((0, self.edge_labels.shape[1]))
            ax.set_ylim((self.edge_labels.shape[0], 0))
            ax.set_aspect('equal')
            if self.save_figures:
                fig.savefig(filename + '.pdf')
                fig.savefig(filename + '.tif')
            if self.show_figures:
                plt.show(block=False)
예제 #15
0
def compute_edgelets(image, sigma=3):
    gray_img = color.rgb2gray(image)
    edges = feature.canny(gray_img, sigma)
    lines = transform.probabilistic_hough_line(edges,
                                               line_length=50,
                                               line_gap=10)

    locations = []
    directions = []
    strengths = []

    for p0, p1 in lines:
        p0, p1 = np.array(p0), np.array(p1)
        locations.append((p0 + p1) / 2)
        directions.append(p1 - p0)
        strengths.append(np.linalg.norm(p1 - p0))

    # convert to numpy arrays and normalize
    locations = np.array(locations)
    directions = np.array(directions)
    strengths = np.array(strengths)

    directions = np.array(directions) / \
        np.linalg.norm(directions, axis=1)[:, np.newaxis]

    return (locations, directions, strengths)
def compute_edgelets(image, sigma=3):
    gray_img = color.rgb2gray(image)
    edges = feature.canny(gray_img, sigma)
    # print (edges.shape, "edges from feature")
    lines = transform.probabilistic_hough_line(edges,
                                               line_length=3,
                                               line_gap=2)

    # print (len(lines), "lines from hough")
    # print (lines[0])
    locations = []
    directions = []
    strengths = []

    for p0, p1 in lines:
        p0, p1 = np.array(p0), np.array(p1)
        locations.append(
            (p0 + p1) /
            2)  # computes the average of the starting point and ending point
        directions.append(p1 - p0)
        strengths.append(np.linalg.norm(p1 - p0))

    # convert to numpy arrays and normalize
    locations = np.array(locations)
    directions = np.array(directions)
    strengths = np.array(strengths)

    directions = np.array(directions) / \
        np.linalg.norm(directions, axis=1)[:, np.newaxis]

    return (locations, directions, strengths)
    def detectTowerLine(self,
                        src_img,
                        img,
                        minLineLength=50,
                        maxLineGap=5,
                        threshold=30,
                        other_condition=True):
        '''

        :param src_img:
        :param img:
        :param minLineLength:
        :param maxLineGap:
        :param threshold:
        :param other_condition:
        :return:
        '''

        # 直线检测,(电线杆上有直线,自然界直线比较少)
        line_list = (transform.probabilistic_hough_line(
            img,
            threshold=threshold,
            line_length=minLineLength,
            line_gap=maxLineGap))
        lines = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)

        for (x1, y1), (x2, y2) in line_list:
            cv2.line(lines, (x1, y1), (x2, y2), (255, 255, 255), 2)

        return cv2.cvtColor(lines, cv2.COLOR_RGB2GRAY), line_list
예제 #18
0
def dynamics(rim):
    grey = color.rgb2grey(rim)
    edges = feature.canny(grey, sigma=3.5)
    lines = transform.probabilistic_hough_line(edges)
    #showDynamics(grey, lines)
    nstatic, ndynamic = 0, 0
    lstatic, ldynamic = 0, 0
    for (p1, p2) in lines:
        v = (p2[0] - p1[0], p2[1] - p1[1])
        angle = 180 / np.pi * np.arctan2(v[1], v[0])
        length = np.sqrt(v[0]**2 + v[1]**2)
        if (angle > -15 and angle < 15) or (angle > 75 and angle < 105):
            #Static line
            nstatic += 1
            lstatic += length
        else:
            #Dynamic line
            ndynamic += 1
            ldynamic += length
    tot = len(lines)
    if tot == 0:
        return np.zeros(6)
    else:
        return np.array([
            nstatic, ndynamic, nstatic / tot, ndynamic / tot, lstatic, ldynamic
        ])
예제 #19
0
def alignHoughTransf(image, out_file_path):

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        blur = filters.gaussian(image, 3)
        edges = feature.canny(blur)
        hough_lines = transform.probabilistic_hough_line(edges)

        slopes = [(y2 - y1) / (x2 - x1) if (x2 - x1) else 0 for (x1, y1), (x2, y2) in hough_lines]

        rad_angles = [np.arctan(x) for x in slopes]
        deg_angles = [np.degrees(x) for x in rad_angles]

        rotation_number = statistics.median(deg_angles)

        final_image = abs(image - 1)
        final_image = final_image * 255
        final_image = transform.rotate(final_image, rotation_number, resize=True, order=5, clip=False, preserve_range=True)

        print()
        print("Salvando arquivo", out_file_path, "...")
        io.imwrite(out_file_path, final_image, "PNG-PIL", compress_level=0, optimize=False)

        final_text = ocr.image_to_string(final_image)

        file = open(file_path + "text_result_hough.txt", "w")
        file.writelines(final_text)
        file.close()

    return 0
예제 #20
0
파일: hough.py 프로젝트: sssruhan1/xray
def hough_vertical_mask(edges, background, fn, hough_line_len=30, save=True, show=True):
    #hough line features.
    div = 9
    hough_start = -math.pi/div
    ds = round(180/div)
    hough_end= 0
    de = 0
    hough_gap = 0.001
    hough_line_gap = 10
    hough_angle = np.arange(hough_start,hough_end, hough_gap)

    #detect lines
    lines = probabilistic_hough_line(edges, threshold=30, line_gap=hough_line_gap,line_length=hough_line_len, theta=hough_angle)
    canvas = background.copy()   
    draw = ImageDraw.Draw(canvas)
    
    pts = []
    ret = []
    for line in lines:
        p0, p1 = line
        # 400 <= x <= 2000, 800 <= y <= 1000
        if  1000<= p0[1]<=2500 and 1000 <=p1[1]<=2500 and  500<= p0[0]<=1000 and 500<= p1[0] <= 1000:
            pts.append(p0)
            pts.append(p1)
            ret.append(line)
            draw.line(line, fill='red')
    if save:
        feature = 'v_range' + str(int(ds))+ '_' + str(int(de)) + '_gap' + str(int(hough_line_gap)) + '_len' + str(int(hough_line_len))
        fn = fn + feature + '.tiff'
        canvas.save(fn)
    if show:
        canvas.show('vertical hough line')
        
    return pts, ret
예제 #21
0
파일: _hough.py 프로젝트: sssruhan1/xray
def hough_v():
    hough_line_len = 30
    div = 9
    hough_start = -math.pi/div
    ds = round(180/div)
    hough_end=0
    de = 0
    hough_gap = 0.001
    hough_line_gap = 8
    hough_angle = np.arange(hough_start,hough_end, hough_gap)

    lines = probabilistic_hough_line(edges, threshold=30, line_gap=hough_line_gap,line_length=hough_line_len, theta=hough_angle)
    #plt.imshow(gray, cmap=plt.cm.gray)
    plt.imshow(edges, cmap=plt.cm.gray)
    #im = Image.new('L', gray.shape)
    #im.putdata(gray)
    #draw = ImageDraw.Draw(im)

    for line in lines:
        p0, p1 = line
        plt.plot((p0[0], p1[0]), (p0[1], p1[1]), linewidth=1, color='r')
        #draw.line((line), width=2)
    #plt.show()
    fn = dir +'/canny_hough/canny_'+str(canny_sigma) + '_V_range' + str(ds)+ '_' + str(de) + '_gap' + str(hough_line_gap) + '_len' + str(hough_line_len) + '.png'
    plt.title('vertical hough line')
    Util.saveplot(plt, fn)
    #im.show()
    return lines
예제 #22
0
def probHoughTransform(image, threshold=15, line_length=4, line_gap=5):

    edges = canny(image, 1, 5, 25)
    lines = probabilistic_hough_line(edges,
                                     threshold=15,
                                     line_length=4,
                                     line_gap=5)
    Dx = []
    Dy = []
    for line in lines:
        p0, p1 = line
        dx = p1[0] - p0[0]
        dy = p1[1] - p0[1]
        Dx.append(dx)
        Dy.append(dy)

    Dx = np.array(Dx)
    Dy = np.array(Dy)
    displacement = np.sqrt(Dx**2 + Dy**2)
    angle = np.rad2deg(np.arctan(Dy / Dx))
    predictionDelta = displacement.mean()
    predictionAngle = angle.mean()
    rmsDelta = displacement.std()
    rmsAngle = angle.std()

    return lines, displacement, angle, predictionDelta, predictionAngle, rmsDelta, rmsAngle
예제 #23
0
파일: hough.py 프로젝트: sssruhan1/xray
def my_hough_2(edges, hough_start, hough_end, hough_line_len=30, line_gap=50, fn = None, show=False, raw=None, xdiff=0, ydiff=0):

    height = edges.shape[0]
    width = edges.shape[1]
    hough_gap = 0.001
    hough_angle = np.arange(hough_start,hough_end, hough_gap)

    lines_ret = probabilistic_hough_line(edges, threshold=30, line_gap=line_gap,line_length=hough_line_len, theta=hough_angle)

    from src.utils.util import tuple2list
    lines_temp1 = tuple2list(lines_ret)
    from src.utils.util import sortlines_len
    lines = sortlines_len(lines_temp1)
    from src.utils.util import changecoord
    if xdiff != 0 and ydiff != 0:
        lines = changecoord(lines, xdiff=xdiff, ydiff=ydiff)
    if lines is not None:
        if show is True:
            if raw is None:
                logging.error('background image is not provided')
                sys.exit(1)

            from src.utils.io import add_lines
            raw = add_lines(lines, raw)


    return lines, raw
예제 #24
0
def bar_extraction(img_gray, axis_x, axis_y, img_height, img_width):
    ## Mask
    down_bound = axis_x[0][1]
    left_bound = axis_y[0][0]
    img = np.ones_like(img_gray)
    pad_size = 2
    img[:down_bound - pad_size, left_bound + pad_size:] = img_gray[:down_bound - pad_size, left_bound + pad_size:]

    ## Sobel
    edge_sobel = sobel(img)
    thresh = threshold_otsu(edge_sobel)
    edge_binary = edge_sobel > thresh

    lines = probabilistic_hough_line(edge_binary, threshold=50, line_length=10,
                                     line_gap=10, theta=np.asarray([-PI/2, PI/2]))  # only need horizontal ones

    line_exist = []
    for line in lines:
        p0, p1 = line
        # remove the replicated lines
        if repli_lines(line_exist, p0, p1) or abs(p0[1] - down_bound) < 10:
            continue
        else:
            line_exist.append(line)

    return line_exist
예제 #25
0
def get_lines(img):
    # Function that grabs all the lines from
    # the image

    # Grayscale image for skeletonize function
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Erode smaller lines
    kernel = np.ones((5, 5), np.uint8)
    erode = cv2.erode(img, kernel, iterations=1)

    ret, thresh = cv2.threshold(erode, 1, 255, cv2.THRESH_BINARY)
    thresh = (thresh / 255).astype(np.uint8)
    skeleton = skeletonize(thresh).astype(np.uint8) * 255

    temp_lines = probabilistic_hough_line(skeleton,
                                          threshold=45,
                                          line_length=30,
                                          line_gap=50)
    lines = []
    for l in temp_lines:
        lines.append(np.array(l).reshape((1, 4)).astype(np.int32))
    lines = np.array(lines)

    return lines
def count_levels(img):
    edges = canny(img, 0, 1, 200)
    n = int(img.shape[1]*0.5)
    lines = probabilistic_hough_line(edges, threshold=10, line_length=n,
                                     line_gap=3)

    # Generating figure 2
    fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)
    ax = axes.ravel()

    ax[0].imshow(img, cmap=cm.gray)
    ax[0].set_title('Input image')

    ax[1].imshow(edges, cmap=cm.gray)
    ax[1].set_title('Canny edges')

    ax[2].imshow(edges * 0)
    for line in lines:
        p0, p1 = line
        ax[2].plot((p0[0], p1[0]), (p0[1], p1[1]))
    ax[2].set_xlim((0, img.shape[1]))
    ax[2].set_ylim((img.shape[0], 0))
    ax[2].set_title('Probabilistic Hough')

    for a in ax:
        a.set_axis_off()

    plt.tight_layout()
    plt.show()
    return len(lines)/2
    
    
예제 #27
0
def _detect_edges(edges, min_edge_length, max_edge_gap, threshold,
                  intersect_tolerance_factor, network: Network):
    """
    """
    from skimage.transform import probabilistic_hough_line
    tested_angles = np.linspace(-np.pi / 2, np.pi / 2, 360, endpoint=False)
    lines = probabilistic_hough_line(edges,
                                     threshold=threshold,
                                     line_length=min_edge_length,
                                     line_gap=max_edge_gap)

    # fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10))

    # ax.imshow(img)
    # ax.set_ylim((edges.shape[0], 0))
    # ax.set_axis_off()
    # ax.set_title('Detected lines')
    # print(len(lines))
    # for line in lines:
    #     p0, p1 = line
    #     ax.plot((p0[0], p1[0]), (p0[1], p1[1]))

    # plt.tight_layout()
    # plt.show()

    # create edges
    for v in network.nodes:
        for w in network.nodes:
            connected = False
            # nodes are connected if any line intersects both nodes
            for l in lines:
                if _check_connected(l, v, w, tol=intersect_tolerance_factor):
                    connected = True
            if connected and (v.uid, w.uid) not in network.edges:
                network.add_edge(v, w)
예제 #28
0
def hough_transform(img):
    edges = canny(np.array(img), 2, 1, 25)
    lines = probabilistic_hough_line(edges, threshold=10, line_length=5,
                                 line_gap=3)


    showImage(lines)
예제 #29
0
def _extract_lines(img,
                   edges=None,
                   mask=None,
                   min_line_length=20,
                   max_line_gap=3):
    global __i__
    __i__ += 1

    if edges is None:
        edges = canny(rgb2grey(img))
    if mask is not None:
        edges = edges & mask

    # figure()
    # subplot(131)
    # imshow(img)
    # subplot(132)
    #vimshow(edges)
    # subplot(133)
    # if mask is not None:
    #     imshow(mask, cmap=cm.gray)
    # savefig('/home/shared/Projects/Facades/src/data/for-labelme/debug/foo/{:06}.jpg'.format(__i__))

    lines = np.array(
        probabilistic_hough_line(edges,
                                 line_length=min_line_length,
                                 line_gap=max_line_gap))

    return lines
예제 #30
0
def get_strip_captcha_coords(image):

    lines = probabilistic_hough_line(
        image,
        threshold=6,
        line_length=6,
        line_gap=18,
        theta=np.array([
            np.pi,
        ]),
    )

    min_y = conf.CAPTCHA_SIZE[0]
    max_y = 0
    min_x = conf.CAPTCHA_SIZE[1]
    max_x = 0

    for line in lines:
        p0, p1 = line

        X = (p1[0], p0[0])
        Y = (p1[1], p0[1])

        min_x = min([min(X), min_x])
        max_x = max([max(X), max_x])
        min_y = min([min(Y), min_y])
        max_y = max([max(Y), max_y])

    max_x += 2  # boundary conditions

    if max_x > conf.CAPTCHA_SIZE[1]:
        max_x = conf.CAPTCHA_SIZE[1]

    return min_x, max_x, min_y, max_y
예제 #31
0
def get_orientation_lines():
    '''
    Create lines array
    '''
    lines = probabilistic_hough_line(M,
                                     threshold=h_threshold,
                                     line_length=h_line_length,
                                     line_gap=h_line_gap)
    angles = []
    for line in lines:
        p0, p1 = line
        if cur_mask == 'redlines':
            num = 0 - (p1[0] - p0[0])
            den = p1[1] - p0[1]
        else:
            num = p1[1] - p0[1]
            den = p1[0] - p0[0]
        if den == 0:
            theta = 90.0
        else:
            theta = atan(1.0 * num / den) * 180.0 / pi
        angles.append(theta)
    if len(lines) == 0:
        angles = [0]
    return (lines, angles)
예제 #32
0
파일: panneaux.py 프로젝트: lgarcin/TIPE
def plot_hough(angle, precision):
    lines = probabilistic_hough_line(edges,
                                     theta=linspace(angle - precision, angle + precision, 3),
                                     line_gap=0,
                                     line_length=10)
    for line in lines:
        p0, p1 = line
        plot((p0[0], p1[0]), (p0[1], p1[1]))
예제 #33
0
def process_image(img_file):

    print("Process", img_file)

    img = io.imread(img_file)

    # Trim the edge of the page off
    img = img[100:-300, 30:-30, :]

    # Increase the contrast of the image to more easily find the black lines
    img = exposure.equalize_hist(img)

    cutoff = 0.18
    img[img < cutoff] = 0.0

    # If any channels are above zero, consider it a white pixel
    for i in range(img.shape[2]):
        img[:, :, i] = img[:, :, 0] + img[:, :, 1] + img[:, :, 2]

    img[img > 0.0] = 1.0

    masked_img = np.ones((img.shape[0], img.shape[1]))
    avg_img = np.average(img, axis=2)
    masked_img[avg_img == 1.0] = 0.0

    # Rotate image
    lines = transform.probabilistic_hough_line(masked_img,
                                               threshold=100,
                                               line_length=400,
                                               line_gap=1)

    angles = []
    for line in lines:
        p0, p1 = line
        next_angle = np.rad2deg(np.arctan2(p1[1] - p0[1], p1[0] - p0[0]))
        if abs(next_angle) < 15.0:
            angles.append(next_angle)

    if len(angles) > 0 and sum(angles) > 0:
        rotation_angle = sum(angles) / len(angles)
        img = transform.rotate(img, rotation_angle)
        img = img[5:-5, 5:-5, :]

    fpath, fname = os.path.split(img_file)
    fname = fname[:-4] + '.tif'
    img = img.astype('uint8') * 255
    io.imsave(os.path.join(fpath, fname), img)

    fname = fname[:-4] + '_lav.tif'
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if img[i, j, 0] == 0:
                img[i, j, 0] = 115
                img[i, j, 1] = 79
                img[i, j, 2] = 150
    io.imsave(os.path.join(fpath, fname), img)

    return
예제 #34
0
def HoughLines():

    dig.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
        None, "Select Image", "",
        "Image Files (*.png *.jpg *jpeg *.bmp);;All Files (*)")  # Ask for file
    if dig.fileName:
        dig.image = Image.open(dig.fileName)
        dig.pixmap = QtGui.QPixmap(
            dig.fileName)  # Setup pixmap with the provided image
        dig.pixmap = dig.pixmap.scaled(
            dig.label_lines_input.width(), dig.label_lines_input.height(),
            QtCore.Qt.KeepAspectRatio)  # Scale pixmap
        dig.label_lines_input.setPixmap(dig.pixmap)

        Shapeee = np.array(dig.image)
        edges = canny(Shapeee, 2, 1, 25)
        lines = probabilistic_hough_line(edges,
                                         threshold=10,
                                         line_length=5,
                                         line_gap=3)

        fig, axes = plt.subplots(1,
                                 3,
                                 figsize=(15, 5),
                                 sharex=True,
                                 sharey=True)
        ax = axes.ravel()

        ax[0].imshow(dig.image, cmap=cm.gray)
        ax[0].set_title('Input image')

        ax[1].imshow(edges, cmap=cm.gray)
        ax[1].set_title('Canny edges')
        #edges.save("mmmmmm.bmp")

        x = edges * 0

        ax[2].imshow(x)
        output_image1 = Image.new("RGB", dig.image.size)
        draw = ImageDraw.Draw(output_image1)
        for line in lines:
            p0, p1 = line
            draw.point((p0, p1), (255, 255, 255))

            ax[2].plot((p0[0], p1[0]), (p0[1], p1[1]))

        ax[2].set_title('Probabilistic Hough')
        #x.imsave("Hough.bmp",imgf)

        # scipy.misc.imsave('outfilerrr.bmp', edges * 0)
        output_image1.save("cannyline.bmp")
        dig.pixma = QtGui.QPixmap(
            "cannyline.bmp")  # Setup pixmap with the provided image
        dig.pixma = dig.pixma.scaled(dig.label_lines_input_2.width(),
                                     dig.label_lines_input_2.height(),
                                     QtCore.Qt.KeepAspectRatio)  # Scale pixmap
        dig.label_lines_input_2.setPixmap(dig.pixma)
        dig.label_lines_input_2.setAlignment(QtCore.Qt.AlignCenter)
예제 #35
0
def generate_plots(in_image, sigma, threshold, line_length, line_gap):
    '''
    Usage:
    generate_plots(in_image, sigma, threshold, line_width, line_gap)
    '''

    edge_image = canny(in_image, sigma)
    lines = probabilistic_hough_line(edge_image,
                                     threshold=threshold,
                                     line_length=line_length,
                                     line_gap=line_gap)
    figfile1 = StringIO()
    fig, ax = plt.subplots(1, 1)
    ax.imshow(in_image, cmap=plt.cm.gray)
    r, c = in_image.shape
    angles = []
    for line in lines:
        p0, p1 = line
        ax.plot((p0[0], p1[0]), (p0[1], p1[1]), 'r-')
        try:
            temp = np.rad2deg(np.arctan((p1[1] - p0[1]) / (p1[0] - p0[0])))
        except ZeroDivisionError:
            temp = 90
        if temp < 0:
            temp += 180
        angles.append(temp)
    ax.axis((0, c, r, 0))
    plt.savefig(figfile1, format='svg')
    figfile1_data = '<svg' + figfile1.getvalue().split('<svg')[1]
    # Let's plot the angle distribution using Bokeh
    param = stats.norm.fit(angles)
    min_x = np.min(angles)
    max_x = np.max(angles)
    axis_x = np.linspace(min_x, max_x, num=100)
    density_fun = stats.norm.pdf(axis_x, loc=param[0], scale=param[1])
    (hist_y, hist_x) = np.histogram(angles, bins=20)
    factor = np.max(hist_y) / np.max(density_fun)
    hist_bokeh = figure(title='Line Angle Distribution',
                        x_axis_label='Angles (deg)',
                        y_axis_label='Counts')
    tops = []
    bottoms = []
    lefts = []
    rights = []
    for i in range(len(hist_y)):
        tops.append(hist_y[i])
        bottoms.append(0)
        lefts.append(hist_x[i])
        rights.append(hist_x[i + 1])
    hist_bokeh.quad(top=tops,
                    bottom=bottoms,
                    left=lefts,
                    right=rights,
                    line_width=2,
                    line_color='black')
    hist_bokeh.line(axis_x, density_fun * factor, color='red')
    b_script, b_div = components(hist_bokeh)
    return figfile1_data, b_script, b_div, angles
예제 #36
0
def gridsize(original, segdst=SEGMENT_DISTANCE):
    global im
    # read the image from disk
    im = original.copy()

    add_image('Original')

    # edge detection
    im = sobel(im)
    # blurring
    im = filters.gaussian(im, sigma=5)
    # thresholding: convert to binary rage
    loc = threshold_local(im, 31)
    im = im > loc

    if (DEBUG): add_image('Threshold')

    # detect straight lines longer than 150px
    segs = probabilistic_hough_line(im,
                                    threshold=30,
                                    line_length=250,
                                    line_gap=7)

    #segs = [seg for seg in segs if vertical(seg)]

    # draw the segments
    im[:] = 0  # set image to black
    for seg in segs:
        ((x1, y1), (x2, y2)) = seg
        rr, cc = draw.line(y1, x1, y2, x2)
        im[rr, cc] = 1

    if (DEBUG): add_image('Hough Lines')
    hh, vv = process_segments(segs)

    # draw the segments
    im[:] = 0  # set image to black

    num = 0
    for yy in hh:
        for yyy in yy:
            (_, y), _ = yyy
            rr, cc = draw.line(y, 0, y, 999)
            im[rr, cc] = 1
            num += 1
    for xx in vv:
        for xxx in xx:
            (x, _), _ = xxx
            rr, cc = draw.line(0, x, 999, x)
            im[rr, cc] = 1
            num += 1

    if (DEBUG):
        add_image('Filtered Segs')
        # finally save the result
        displ()

    return len(vv) - 1, len(hh) - 1
예제 #37
0
def test_probabilistic_hough_seed():
    # Load image that is likely to give a randomly varying number of lines
    image = data.checkerboard()

    # Use constant seed to ensure a deterministic output
    lines = transform.probabilistic_hough_line(image, threshold=50,
                                               line_length=50, line_gap=1,
                                               seed=1234)
    assert len(lines) == 65
예제 #38
0
def test_probabilistic_hough_seed():
    # Load image that is likely to give a randomly varying number of lines
    image = data.checkerboard()

    # Use constant seed to ensure a deterministic output
    lines = transform.probabilistic_hough_line(image, threshold=50,
                                               line_length=50, line_gap=1,
                                               seed=1234)
    assert len(lines) == 65
예제 #39
0
def test1(derotated_croped_gray,distance_between_staves,thickness):
       
    my_copy = np.zeros(derotated_croped_gray.shape)#np.copy(derotated_croped_gray)
    my_copy = gray2rgb((my_copy*255).astype(np.uint8),3)
    
    edges = canny(derotated_croped_gray, 2, 1, 25)
    height = derotated_croped_gray.shape[0]
    width = derotated_croped_gray.shape[1]
    lines = probabilistic_hough_line(edges, threshold=10, line_length=5, line_gap=3, theta=np.arange(np.pi/4, np.pi*3/4, np.pi/90))

    lines_img = draw_hough_lines(lines, edges.shape)
    

    
    kernel_size = int(distance_between_staves*1.5)
    k = np.ones((kernel_size, kernel_size))
    k2_multiplier = 3 if np.cbrt(kernel_size) > 3 else np.cbrt(kernel_size) > 3
    k2 = np.ones((int(kernel_size*k2_multiplier), int(kernel_size*k2_multiplier)))

    musical_lines_mask = cv2.erode(cv2.dilate(lines_img, k), k2)
    
    #detach_lines_kernel = np.ones((thickness*2+1,1))
    
    #lines_img = cv2.erode(cv2.dilate(lines_img, detach_lines_kernel), detach_lines_kernel)
    
    #musical_lines_mask = cv2.erode(cv2.dilate(lines_img, k), k2)
    

    # Contours
    image, contours, hierarchy = cv2.findContours((musical_lines_mask*255).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # Contours filtered
    musical_lines_mask_width = musical_lines_mask.shape[1]
    contours_filtered = []
    
    for c in contours:
        c = cv2.convexHull(c)
        x_points = c.T[0]
        c_min_x = np.min(x_points)
        c_max_x = np.max(x_points)
        c_width = c_max_x - c_min_x
        if c_width / musical_lines_mask_width >= .75: 
            contours_filtered.append(c)
    
    for contour in contours_filtered:
        rect = cv.minAreaRect(contour)
        box = cv.boxPoints(rect)
        #print(box)
        box = np.int0(box)
        my_copy = cv.drawContours(my_copy,[box],0,(255,255,255),6)
    
        #image = cv.drawContours(gray2rgb((musical_lines_mask*255).astype(np.uint8)), contours_filtered, -1, (0,255,0))
    # Draw filtered contours
    #musical_lines_mask_contours_drawn = rgb2gray(cv.drawContours(gray2rgb((musical_lines_mask*255).astype(np.uint8)), contours_filtered, -1, (255,255,255), 3))
    return musical_lines_mask,contours_filtered
예제 #40
0
def test_probabilistic_hough():
    # Generate a test image
    img = np.zeros((100, 100), dtype=int)
    for i in range(25, 75):
        img[100 - i, i] = 100
        img[i, i] = 100

    # decrease default theta sampling because similar orientations may confuse
    # as mentioned in article of Galambos et al
    theta = np.linspace(0, np.pi, 45)
    lines = tf.probabilistic_hough_line(img, threshold=10, line_length=10, line_gap=1, theta=theta)
    # sort the lines according to the x-axis
    sorted_lines = []
    for line in lines:
        line = list(line)
        line.sort(key=lambda x: x[0])
        sorted_lines.append(line)

    assert [(25, 75), (74, 26)] in sorted_lines
    assert [(25, 25), (74, 74)] in sorted_lines

    # Execute with default theta
    tf.probabilistic_hough_line(img, line_length=10, line_gap=3)
예제 #41
0
def draw_lines(array, width=105):
    m = to_matrix(array, width=width)
    x = skeletonize(m)
    ax = plt.subplot(1, 3, 0)
    ax.imshow(m, cmap=plt.cm.gray_r, interpolation='nearest')
    ax = plt.subplot(1, 3, 1)
    ax.imshow(x, cmap=plt.cm.gray_r, interpolation='nearest')
    ax = plt.subplot(1, 3, 2)
    ax.imshow(x*0, cmap=plt.cm.gray_r, interpolation='nearest')
    lines = probabilistic_hough_line(x, threshold=10, line_length=5, line_gap=3)
    for line in lines:
        p0, p1 = line
        ax.plot((p0[0], p1[0]), (p0[1], p1[1]))
    plt.show()
예제 #42
0
    def hough_transform(self, vary=False, plot=False):
        """
        :param vary: turn edge detection tunable plotting on
        :param plot: turn plotting on
        :return: numpy array of probabilistically found straight lines
        """
        if self.name == "":
            raise ValueError('Missing image: you need to specify the image file using add_image.')

        self.edges = self._detect_edges(self.name, vary=vary, plot=plot)
        self.lines = probabilistic_hough_line(self.edges, threshold=10, line_length=5, line_gap=3)
        if plot:
            for line in self.lines:
                p0, p1 = line
                plt.plot((p0[0], p1[0]), (p0[1], p1[1]))
            plt.show()
예제 #43
0
    def __get_grid_segments__(self):
        horiz_segments = []
        vert_segments = []

        horiz_intercepts = []
        vert_intercepts = []

        print "getting edges"
        edges = cv2.Canny(self.template,25,150,apertureSize = 3)

        print "probabilistic houghes"
        lines = probabilistic_hough_line(edges, threshold=5, line_length=3,line_gap=1)
        # plt.close()
        # fig, ax1 = plt.subplots(1, 1)
        # fig.set_size_inches(52,78)
        # ax1.imshow(self.image)


        for line in lines:
            p0, p1 = line
            X = p0[0],p1[0]
            Y = p0[1],p1[1]

            if (min(X) >= self.big_lower_x) and (max(X) <= self.big_upper_x) and (min(Y) >= self.big_lower_y) and (max(Y) <= self.big_upper_y):
                d,t = hesse_line(line)
                if math.fabs(t) <= 0.1:
                    # horiz_list.append(line)
                    # hesse_list.append(hesse_line(line))

                    m = (Y[0]-Y[1])/float(X[0]-X[1])
                    b = Y[0]-m*X[0]
                    horiz_intercepts.append(b+m*big_lower_x)
                    horiz_segments.append(line)
                elif math.fabs(t-math.pi/2.) <= 0.1:
                    # vert_list.append(line)
                    m = (X[0]-X[1])/float(Y[0]-Y[1])
                    b = X[0]-m*Y[0]
                    vert_intercepts.append(b+m*big_lower_y)
                    vert_segments.append(line)
                else:
                    continue

            # ax1.plot(X, Y,color="red")
        # plt.savefig("/home/ggdhines/Databases/new.jpg",bbox_inches='tight', pad_inches=0,dpi=72)
        return horiz_segments,vert_segments,horiz_intercepts,vert_intercepts
def main():
    ground_truth = np.array([2,2,1,5,2,3,3,3,2,6,2,3,6,3,5,6,3,2,3,2,4,6,2,2,3,3,2,1,3,0,3,3,2,3,3,3,5,3,6,2,2,5,3,6,2,3,3,3,6,2,0,2,0,2,5,2,3,2,2,0,4,2,1,0,2,2,2,0,3,5,3,3,6,3,3,3,3,3,0,3,0,2,3,0,0,3,2,0,0,2,2,3,2,2,2,0,3,2,0,1,3,3,2,3,3,3,3,2,3,0,3,3,1,2,3,2,0,0,0,0,0,0,0,0,3,2,3,2,2,3,3,3,3,3,3,2,2])

    simple_ground_truth = []
    for i in np.arange(len(ground_truth)):
        if ground_truth[i] >=4:
            simple_ground_truth.append(4)
        else:
            simple_ground_truth.append(ground_truth[i])
    simple_ground_truth = np.array(simple_ground_truth)

    with open("test_fig/img_data.dat", "rb") as fin:
        img_data = cPickle.load(fin)

    img = img_data[1]

    fig = plt.figure(figsize=const.figsize)
    ax = fig.add_subplot(121, aspect='equal')
    ax.imshow(img>0, cmap='gray')
    lines = probabilistic_hough_line(img,line_length=20)
    print len(lines)
    N_BIN = 32
    theta_bins = np.arange(N_BIN)*np.pi/N_BIN
    bin_hist = np.zeros(N_BIN)

    for line in lines:
        ax.plot([line[0][0],line[1][0]],
                [line[0][1],line[1][1]],'-r')
        vec = np.array([line[1][0]-line[0][0], line[1][1]-line[0][1]])*1.0
        vec_norm = np.linalg.norm(vec)
        if vec_norm > 1.0:
            vec /= vec_norm

        cross_product = abs(np.dot(vec, np.array([1,0])))
        theta_bin_idx = int(np.arccos(cross_product) / np.pi * N_BIN)
        bin_hist[theta_bin_idx] += 1

    ax.set_xlim([0, img.shape[0]])
    ax.set_ylim([img.shape[1], 0])

    ax = fig.add_subplot(122)
    x_vals = np.arange(N_BIN)*90.0/N_BIN
    ax.plot(x_vals, bin_hist, '.-')

    plt.show()
예제 #45
0
def linesFromBinary(binaryData, minLen, debug=False):

    # find edges
    edges = filters.sobel(binaryData)

    # get directions
    lines = probabilistic_hough_line(edges, threshold=10, line_length=minLen,
                                     line_gap=3)

    if lines == []:
        if debug:
            print('No lines detected with Hough line algorithm')
        return None, None, lines

    else:
        angleArr = np.zeros(len(lines))
        for l in np.arange(len(lines)):
            p0, p1 = lines[l]

            # get the m coefficient of the lines and the angle
            try:
                m = (p1[0] - p0[0])/(p1[1] - p0[1])
                angle = (180/np.pi)*np.arctan(m)
            except ZeroDivisionError:
                angle = 90

            angleArr[l] = angle

        # Before calculating the mean angle, we have to make sure we're using
        # the same quadrant for all the angles. We refer all the angles to the
        # first one
        opt = np.array([180, 0, -180])
        for i in np.arange(1, len(angleArr)):
            dists = np.abs(angleArr[0] - (opt + angleArr[i]))
            angleArr[i] += opt[np.argmin(dists)]

        mean, std = np.mean(angleArr), np.std(angleArr)

        # We like angles in [0, 180)
        if mean < 0:
            mean += 180

        return mean, std, lines
예제 #46
0
def text_sections(im, output_height):
    im = im.convert('L')
    im_array = image_to_array(im)
    im_arary = im_array / 255

    r = range(-50,50)
    r_theta = [np.pi/2 + x*0.001 for x in r]
    theta = np.array(r_theta)

    edges = canny(im_array, 2, 1, 25)

    lines = probabilistic_hough_line(edges, threshold=5, line_length=20,
                                line_gap=20, theta=theta)

    lines_sorted = sorted(lines, cmp=cmp_lines)
    rs = regions(lines_sorted, 2)
    text_areas = [bounding_rectangle(ls, 4) for ls in rs]
    for (x0, y0), (x1, y1) in text_areas:
        width, height = x1 - x0, y1 - y0
        output_width = width * output_height // height
        yield(im.transform((output_width, output_height), Image.EXTENT,
                           (x0, y0, x1, y1)))
예제 #47
0
def hough_transform(H):
	# this function takes the 2D histogram, finds and returns lines

	print "let's do the hough and find some lines here"
	# http://scikit-image.org/docs/dev/auto_examples/plot_line_hough_transform.html
	# https://nabinsharma.wordpress.com/2012/12/26/linear-hough-transform-using-python/
	# http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html


	builder = []
	for row in H:
		temprow = []
		for i in row:
			if i < 8: # clean data so it only finds edges when above a certain threshold
				i = 0
			temprow.append(i)
		builder.append(temprow)
	H = np.asanyarray(builder) # turn this row off to use normal H, there's too much noise in floor 1 though

	edges = canny(H) # for noise set sigma=1.8; Edges also very interesting for stairs also! < not absolutely necessary

	lines = probabilistic_hough_line(H, threshold=50, line_length=30, line_gap=5) # parameters to be set # threshold=50, line_length=5, line_gap=20

	"""showme"""
	# fig, (plt1, plt2, plt3) = plt.subplots(1, 3, sharex=True, sharey=True)
	# plt1.imshow(H,cmap='spectral')
	# plt1.set_title('vert hist')
	# plt2.imshow(edges,cmap=plt.cm.gray)
	# plt2.set_title('canny edges')
	# for line in lines:
	#     startpt, endpt = line
	#     plt3.plot((startpt[0], endpt[0]), (startpt[1], endpt[1]))
	# plt3.set_title('hough lines')
	# plt.show() # can't get rid of stupid white space

	return lines
def process(filename):
    imagepath = os.path.join(os.getcwd(), filename)
    orig_img = io.imread(filename,True,'pil')
    img = orig_img > 0.9 # binary threshold
    lines = probabilistic_hough_line(hsobel(img),line_length=200)
    for l in lines:
        x0, x1 = l[0][0],l[1][0]
        y = l[0][1]
        for x in range(x0,x1):
            img[y+1,x] = 1
            img[y,x] = 1
            img[y-1,x] = 1
    erode_img = erosion(img, square(2))
    contours, lengths = compute_contours(erode_img,0.8)
    lengths = pd.Series(lengths)
    lengths = lengths[lengths > 400]
    for i in lengths.index:
        contour = contours[i]
        box = get_boundingboxes([contour])[0]
        x_sum = sum(map(abs, np.gradient(contour[:,1])))
        y_sum = sum(map(abs, np.gradient(contour[:,0])))
        area = (box[2] - box[0]) * (box[3] - box[1])
        plt.plot(contour[:,1],contour[:,0])
    contours = [contours[i] for i in lengths.index]
    newboxes = set(link_contours(contours))
    retboxes = []
    for box in newboxes:
        minx,miny,maxx,maxy = box
        x = (minx, maxx, maxx, minx, minx)
        y = (miny, miny, maxy, maxy, miny)
        area = (maxx-minx) * (maxy-miny)
        if area > 10000:
            retboxes.append(box)
            plt.plot(x, y, '-b', linewidth=2)
    imshow(erode_img)
    return retboxes, contours
imshow(data_for_skeleton, cmap=plt.cm.gray)
plt.show()

selem = disk(5) ;
closed = binary_closing(data_for_skeleton, selem) ;
imshow(closed, cmap=plt.cm.gray) ; plt.show() ;
closed[closed>0]=1 ;
skeleton = skeletonize(data_for_skeleton)
imshow(skeleton, cmap=plt.cm.gray) ; plt.show() ;



#trying to extract lines with hough transform
from skimage.transform import (hough_line, hough_line_peaks,
                               probabilistic_hough_line)
lines = probabilistic_hough_line(skeleton, threshold=10, line_length=5, line_gap=20)
for line in lines:
    p0, p1 = line ;
    plt.plot((p0[0], p1[0]), (p0[1], p1[1])) ;

imshow(skeleton, cmap=plt.cm.gray) ; plt.show() ;
#working on sidewalk :
    """
        We work on sidewalk : we use the relative height to compute the gradient 
        of it. Then we perform thresholding then closing then straight sekeleton
        NOte : the laser is approximately 2.50 meters above the street.
        We are only interested in pixel where the height is between +-50cm from the ground
            , to keep sidewalk.
    """

from skimage.morphology import disk,square
예제 #50
0
            colours[pixel_colour] = 1
        else:
            colours[pixel_colour] += 1

most_common_colour,_ = sorted(colours.items(),key = lambda x:x[1],reverse=True)[0]

image = np.zeros(img.shape[:2])
for c in range(img.shape[1]):
    for r in range(img.shape[0]):
        pixel_colour = tuple(img[r,c])
        dist = math.sqrt(sum([(int(a)-int(b))**2 for (a,b) in zip(pixel_colour,most_common_colour)]))

        if dist > 40:
            image[(r,c)] = 150

lines = probabilistic_hough_line(image, threshold=0, line_length=70,line_gap=2)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4), sharex=True, sharey=True)

ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_axis_off()
ax1.set_adjustable('box-forced')

# ax2.imshow(image, cmap=plt.cm.gray)
# ax2.set_title('Canny edges')
# ax2.set_axis_off()
# ax2.set_adjustable('box-forced')

ax2.imshow(image)
예제 #51
0
def ocr(hash):
    error = 0

    img = img_as_ubyte(data.imread(full_path(hash), True))

    start_time = timeit.default_timer()
    threshold_local = filter.threshold_adaptive(img, 201)
    elapsed = timeit.default_timer() - start_time

    print("threshold_local:", elapsed)

    # edge

    start_time = timeit.default_timer()
    edges2 = filter.canny(threshold_local, sigma=2)
    elapsed = timeit.default_timer() - start_time
    print("canny:", elapsed)

    # Deskew

    start_time = timeit.default_timer()
    theta = numpy.linspace(1.39, 1.74, 30)

    lines = probabilistic_hough_line(edges2, line_gap=50, line_length=600, theta=theta)
    print("Lines:", len(lines))

    angs = [angle(ps) for ps in lines]
    rot = numpy.mean(angs)
    ang = math.degrees(rot)
    elapsed = timeit.default_timer() - start_time
    print("deskew:", elapsed)
    print("Angle:", ang, "Degres")

    final = rotate(threshold_local, ang)
    start_time = timeit.default_timer()
    texto = pytesseract.image_to_string(Image.fromarray(numpy.uint8(final)))
    elapsed = timeit.default_timer() - start_time
    print("OCR:", elapsed)

    print(texto)
    print ('-' * 30)

    all = string.maketrans('', '')
    strdna = all.translate(all, 'acgtACGT')
    texto2 = texto.translate(all, strdna).upper()
    print (texto2)

    if (False):

        # results
        fig, ax = plt.subplots(2, 3, figsize=(8, 3))

        ax0, ax1, ax2, ax3, ax4, ax5 = ax.ravel()

        ax0.imshow(img, cmap=plt.cm.gray)
        ax0.set_title('Original')
        ax0.axis('image')

        ax1.imshow(threshold_local, cmap=plt.cm.gray)
        ax1.set_title('Local threshold (radius=%d)' % 101)
        ax1.axis('image')

        ax2.imshow(edges2, cmap=plt.cm.gray)
        ax2.set_title('Canny edges')
        ax2.axis('image')

        ax3.imshow(edges2, cmap=plt.cm.gray)

        for line in lines:
            p0, p1 = line
            ax3.plot((p0[0], p1[0]), (p0[1], p1[1]))

        ax3.set_title('Probabilistic Hough')
        ax3.axis('image')

        ax4.imshow(final, cmap=plt.cm.gray)
        ax4.set_title('Deskew')
        ax4.axis('image')

        plt.show()

    return [texto2, error]
def hough_lines(image, *args, **kwargs):
    lines = probabilistic_hough_line(image, threshold=0.5, *args, **kwargs)
    image = line_image(image.shape, lines)
    return image
def main():
    if len(sys.argv) != 2:
        print "ERROR! Correct usage is:"
        print "\tpython test_hough_transform.py [gps_point_collection.dat]"
        return
    
    GRID_SIZE = 500
    results = np.zeros((GRID_SIZE, GRID_SIZE), np.float)
    
    # Load GPS points
    with open(sys.argv[1], "rb") as fin:
        point_collection = cPickle.load(fin)
    
    for pt in point_collection:
        y_ind = math.floor((pt[0] - const.RANGE_SW[0]) / (const.RANGE_NE[0] -const.RANGE_SW[0]) * GRID_SIZE)
        x_ind = math.floor((pt[1] - const.RANGE_NE[1]) / (const.RANGE_SW[1] -const.RANGE_NE[1]) * GRID_SIZE)
        results[x_ind, y_ind] += 1.0
        if results[x_ind, y_ind] >= 64:
            results[x_ind, y_ind] = 63
    results /= np.amax(results)
    
    thresholded_results = np.zeros((GRID_SIZE, GRID_SIZE), np.bool)
    
    THRESHOLD = 0.02
    for i in range(0, GRID_SIZE):
        for j in range(0, GRID_SIZE):
            if results[i,j] >= THRESHOLD:
                thresholded_results[i,j] = 1
            else:
                thresholded_results[i,j] = 0
    box_size = 30
    
#    x_ind = random.randint(box_size, GRID_SIZE-box_size)                
#    y_ind = random.randint(box_size, GRID_SIZE-box_size)
    
    x_ind = 405
    y_ind = 373
    
    test_img = thresholded_results[(x_ind-box_size):(x_ind+box_size),\
                                     (y_ind-box_size):(y_ind+box_size)]
    print test_img.shape                                    
                
    #h, theta, d = hough_line(test_img)
#    fig = plt.figure(figsize=(30,16))
#    ax = fig.add_subplot(121, aspect='equal')
#    ax.imshow(test_img, cmap=plt.cm.gray)
#    
#    ax = fig.add_subplot(122)
#    img = skeletonize(test_img)
#    ax.imshow(img, cmap=plt.cm.gray)
#    plt.show()
#    fig = plt.figure(figsize=(30,16))
#    ax = fig.add_subplot(131, aspect='equal')
#    ax.imshow(test_img, cmap=plt.cm.gray)
#    
#    ax = fig.add_subplot(132)
#    ax.imshow(np.log(1+h),
#               extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]],
#               cmap=plt.cm.gray, aspect=1/1.5)
#    ax = fig.add_subplot(133)
#    ax.imshow(test_img, cmap=plt.cm.gray)
#    rows, cols = test_img.shape
#    for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
#        y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
#        y1 = (dist - cols * np.cos(angle)) / np.sin(angle)
#        ax.plot((0, cols), (y0, y1), '-r')
#    ax.set_xlim([0, cols])
#    ax.set_ylim([rows, 0])
#    plt.show()
    
    print "point at: ", x_ind, y_ind
    coords = [(y_ind-box_size, x_ind-box_size), (y_ind+box_size, x_ind-box_size),\
              (y_ind+box_size, x_ind+box_size), (y_ind-box_size, x_ind+box_size), \
              (y_ind-box_size, x_ind-box_size)]
    
    bound_box = Polygon(coords)
    patch = PolygonPatch(bound_box, fc='none', ec='red')
    fig = plt.figure(figsize=(30,16))
    rows, cols = thresholded_results.shape
    ax = fig.add_subplot(121, aspect='equal')
    ax.imshow(thresholded_results, cmap=plt.cm.gray)
    ax.add_patch(patch)
    ax.set_xlim([0, cols])
    ax.set_ylim([rows, 0])
    
    ax = fig.add_subplot(122)
    ax.imshow(test_img, cmap=plt.cm.gray)
    lines = probabilistic_hough_line(test_img, 
                                     threshold=20, 
                                     line_length=20, 
                                     line_gap=10)
    rows, cols = test_img.shape
    for line in lines:
        p0, p1 = line
        ax.plot((p0[0], p1[0]), (p0[1], p1[1]), '-r', linewidth=2)
    ax.set_xlim([0, cols])
    ax.set_ylim([rows, 0])
#    
#    # Compute line hough
#    line_hough = []
#    for line in lines:
#        p0, p1 = line
#        vec0 = np.array((float(p1[0]-p0[0]), float(p1[1]-p0[1]), 0.0))
#        v_norm = np.cross(vec0, np.array((0.0,0.0,1.0)))
#        v_norm /= np.linalg.norm(v_norm)
#        angle = abs(np.dot(v_norm, np.array((1.0,0,0))))
#        
#        theta = np.arccos(angle) / 0.5 / math.pi
#        
#        vec1 = np.array((p0[0], p0[1], 0.0))
#        r = abs(np.dot(vec1, v_norm)) / 140.0
#        line_hough.append((theta, r))        
#      
#    X = np.array(line_hough)
#    # Compute DBSCAN
#    db = DBSCAN(eps=0.1, min_samples=1).fit(X)
#    core_samples = db.core_sample_indices_
#    labels = db.labels_
#    
#    # Number of clusters in labels, ignoring noise if present.
#    n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
#    
#    print "clusters = ", n_clusters_
#    
#    ax = fig.add_subplot(223, aspect='equal')
#  
#    unique_labels = set(labels)
#    colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))
#    cluster_center = []
#    for k, col in zip(unique_labels, colors):
#        center_theta = 0.0
#        center_d = 0.0
#        center_count = 0
#        if k == -1:
#            # Black used for noise.
#            col = 'k'
#            markersize = 6
#        class_members = [index[0] for index in np.argwhere(labels == k)]
#        cluster_core_samples = [index for index in core_samples
#                                if labels[index] == k]
#        for index in class_members:            
#            x = X[index]
#            if index in core_samples and k != -1:
#                markersize = 14
#                center_count += 1
#                center_theta += x[0]
#                center_d += x[1]
#            else:
#                markersize = 6
#            ax.plot(x[0], x[1], 'o', markerfacecolor=col,
#                    markeredgecolor='k', markersize=markersize)
#        center_d /= center_count
#        center_d *= 140
#        center_theta /= center_count
#        center_theta *= 0.5*math.pi
#        cluster_center.append((center_theta, center_d))
#        
#    ax.set_xlim([-0.1, 1.1])
#    ax.set_ylim([-0.1, 1.1])
#    
#    ax = fig.add_subplot(224)
#    ax.imshow(test_img, cmap=plt.cm.gray)
#    
#    for angle, dist in cluster_center:
#        y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
#        y1 = (dist - cols * np.cos(angle)) / np.sin(angle)
#        ax.plot((0, cols), (y0, y1), '-r')
#    rows, cols = test_img.shape
#    ax.set_xlim([0, cols])
#    ax.set_ylim([rows, 0])

    plt.show()
예제 #54
0
파일: satdet.py 프로젝트: SaraOgaz/acstools
def _detsat_one(filename, ext, sigma=2.0, low_thresh=0.1, h_thresh=0.5,
                small_edge=60, line_len=200, line_gap=75,
                percentile=(4.5, 93.0), buf=200, plot=False, verbose=False):
    """Called by :func:`detsat`."""
    if verbose:
        t_beg = time.time()

    fname = '{0}[{1}]'.format(filename, ext)

    # check extension
    if ext not in (1, 4, 'SCI', ('SCI', 1), ('SCI', 2)):
        warnings.warn('{0} is not a valid science extension for '
                      'ACS/WFC'.format(ext), AstropyUserWarning)

    # get the data
    image = fits.getdata(filename, ext)
    #image = im.astype('float64')

    # rescale the image
    p1, p2 = np.percentile(image, percentile)

    # there should always be some counts in the image, anything lower should
    # be set to one. Makes things nicer for finding edges.
    if p1 < 0:
        p1 = 0.0

    if verbose:
        print('Rescale intensity percentiles: {0}, {1}'.format(p1, p2))

    image = exposure.rescale_intensity(image, in_range=(p1, p2))

    # get the edges
    immax = np.max(image)
    edge = filt.canny(image, sigma=sigma,
                      low_threshold=immax * low_thresh,
                      high_threshold=immax * h_thresh)

    # clean up the small objects, will make less noise
    morph.remove_small_objects(edge, min_size=small_edge, connectivity=8,
                               in_place=True)

    # create an array of angles from 0 to 180, exactly 0 will get bad columns
    # but it is unlikely that a satellite will be exactly at 0 degrees, so
    # don't bother checking.
    # then, convert to radians.
    angle = np.radians(np.arange(2, 178, 0.5, dtype=float))

    # perform Hough Transform to detect straight lines.
    # only do if plotting to visualize the image in hough space.
    # otherwise just preform a Probabilistic Hough Transform.
    if plot and plt is not None:
        h, theta, d = transform.hough_line(edge, theta=angle)
        plt.ion()

    # perform Probabilistic Hough Transformation to get line segments.
    # NOTE: Results are slightly different from run to run!
    result = transform.probabilistic_hough_line(
        edge, threshold=210, line_length=line_len,
        line_gap=line_gap, theta=angle)
    result = np.asarray(result)
    n_result = len(result)

    # initially assume there is no satellite
    satellite = False

    # only continue if there was more than one point (at least a line)
    # returned from the PHT
    if n_result > 1:
        if verbose:
            print('Length of PHT result: {0}'.format(n_result))

        # create lists for X and Y positions of lines and build points
        x0 = result[:, 0, 0]
        y0 = result[:, 0, 1]
        x1 = result[:, 1, 0]
        y1 = result[:, 1, 1]

        # set some boundries
        ymax, xmax = image.shape
        topx = xmax - buf
        topy = ymax - buf

        if verbose:
            print('min(x0)={0:4d}, min(x1)={1:4d}, min(y0)={2:4d}, '
                  'min(y1)={3:4d}'.format(min(x0), min(x1), min(y0), min(y1)))
            print('max(x0)={0:4d}, max(x1)={1:4d}, max(y0)={2:4d}, '
                  'max(y1)={3:4d}'.format(max(x0), max(x1), max(y0), max(y1)))
            print('buf={0}'.format(buf))
            print('topx={0}, topy={1}'.format(topx, topy))

        # set up trail angle "tracking" arrays.
        # find the angle of each segment and filter things out.
        # TODO: this may be wrong. Try using arctan2.
        trail_angle = np.degrees(np.arctan((y1 - y0) / (x1 - x0)))
        # round to the nearest 5 degrees, trail should not be that curved
        round_angle = (5 * np.round(trail_angle * 0.2)).astype(int)

        # take out 90 degree things
        mask = round_angle % 90 != 0

        if not np.any(mask):
            if verbose:
                print('No round_angle found')
            return np.empty(0)

        round_angle = round_angle[mask]
        trail_angle = trail_angle[mask]
        result = result[mask]

        ang, num = stats.mode(round_angle)

        # do the filtering
        truth = round_angle == ang[0]

        if verbose:
            print('trail_angle: {0}'.format(trail_angle))
            print('round_angle: {0}'.format(round_angle))
            print('mode(round_angle): {0}'.format(ang[0]))

        # filter out the outliers
        trail_angle = trail_angle[truth]
        result = result[truth]
        n_result = len(result)

        if verbose:
            print('Filtered trail_angle: {0}'.format(trail_angle))

        if n_result < 1:
            return np.empty(0)

        # if there is an unreasonable amount of points, it picked up garbage
        elif n_result > 300:
            warnings.warn(
                'Way too many segments results to be correct ({0}). Rejecting '
                'detection on {1}.'.format(n_result, fname), AstropyUserWarning)
            return np.empty(0)

        # remake the point lists with things taken out
        x0 = result[:, 0, 0]
        y0 = result[:, 0, 1]
        x1 = result[:, 1, 0]
        y1 = result[:, 1, 1]

        min_x0 = min(x0)
        min_y0 = min(y0)
        min_x1 = min(x1)
        min_y1 = min(y1)

        max_x0 = max(x0)
        max_y0 = max(y0)
        max_x1 = max(x1)
        max_y1 = max(y1)

        mean_angle = np.mean(trail_angle)

        # make decisions on where the trail went and determine if a trail
        # traversed the image
        # top to bottom
        if (((min_y0 < buf) or (min_y1 < buf)) and
              ((max_y0 > topy) or (max_y1 > topy))):
            satellite = True
            if verbose:
                print('Trail Direction: Top to Bottom')

        # right to left
        elif (((min_x0 < buf) or (min_x1 < buf)) and
              ((max_x0 > topx) or (max_x1 > topx))):
            satellite = True
            if verbose:
                print('Trail Direction: Right to Left')

        # bottom to left
        elif (((min_x0 < buf) or (min_x1 < buf)) and
              ((min_y0 < buf) or (min_y1 < buf)) and
              (-1 > mean_angle > -89)):
            satellite = True
            if verbose:
                print('Trail Direction: Bottom to Left')

        # top to left
        elif (((min_x0 < buf) or (min_x1 < buf)) and
              ((max_y0 > topy) or (max_y1 > topy)) and
              (89 > mean_angle > 1)):
            satellite = True
            if verbose:
                print('Trail Direction: Top to Left')

        # top to right
        elif (((max_x0 > topx) or (max_x1 > topx)) and
              ((max_y0 > topy) or (max_y1 > topy)) and
              (-1 > mean_angle > -89)):
            satellite = True
            if verbose:
                print('Trail Direction: Top to Right')

        # bottom to right
        elif (((max_x0 > topx) or (max_x1 > topx)) and
              ((min_y0 < buf) or (min_y1 < buf)) and
              (89 > mean_angle > 1)):
            satellite = True
            if verbose:
                print('Trail Direction: Bottom to Right')

    if satellite:
        if verbose:
            print('{0} trail segment(s) detected'.format(n_result))
            print('Trail angle list (not returned): ')
            print(trail_angle)
            print('End point list:')
            for i, ((px0, py0), (px1, py1)) in enumerate(result, 1):
                print('{0:5d}. ({1:4d}, {2:4d}), ({3:4d}, {4:4d})'.format(
                    i, px0, py0, px1, py1))

        if plot and plt is not None:
            mean = np.median(image)
            stddev = image.std()
            lower = mean - stddev
            upper = mean + stddev

            fig1, ax1 = plt.subplots()
            ax1.imshow(edge, cmap=plt.cm.gray)
            ax1.set_title('Edge image for {0}'.format(fname))

            for (px0, py0), (px1, py1) in result:  # Draw trails
                ax1.plot((px0, px1), (py0, py1), scalex=False, scaley=False)

            fig2, ax2 = plt.subplots()
            ax2.imshow(
                np.log(1 + h),
                extent=(np.rad2deg(theta[-1]), np.rad2deg(theta[0]),
                        d[-1], d[0]), aspect=0.02)
            ax2.set_title('Hough Transform')
            ax2.set_xlabel('Angles (degrees)')
            ax2.set_ylabel('Distance from Origin (pixels)')

            fig3, ax3 = plt.subplots()
            ax3.imshow(image, vmin=lower, vmax=upper, cmap=plt.cm.gray)
            ax3.set_title(fname)

            for (px0, py0), (px1, py1) in result:  # Draw trails
                ax3.plot((px0, px1), (py0, py1), scalex=False, scaley=False)

            plt.draw()

    else:  # length of result was too small
        result = np.empty(0)

        if verbose:
            print('No trail detected; found {0} segments'.format(n_result))

        if plot and plt is not None:
            fig1, ax1 = plt.subplots()
            ax1.imshow(edge, cmap=plt.cm.gray)
            ax1.set_title(fname)

            # Draw trails
            for (px0, py0), (px1, py1) in result:
                ax1.plot((px0, px1), (py0, py1), scalex=False, scaley=False)

    if verbose:
        t_end = time.time()
        print('Run time: {0} s'.format(t_end - t_beg))

    return result
def extract_line_segments(image, 
                          grid_size, 
                          loc, 
                          R, 
                          line_gap, 
                          search_range, 
                          p_removal,
                          display=True):
    """
        Extract line segments from an image file
            Args:
                - image: ndarray image data
                - grid_size: size of each pixel
                - loc: center of the actual region
                - R: radius of the actual region
                - line_gap: maximum gap in meters
                - search_range: used in pixel removal
                - p_removal: probability to remove a pixel
    """
    line_gap_in_pixel = int(line_gap/grid_size+0.5)

    all_lines = []
    lines = probabilistic_hough_line(image, 
                                     line_length=100,
                                     line_gap=line_gap_in_pixel)
   
    if display:
        fig = plt.figure(figsize=const.figsize)
        ax = fig.add_subplot(111)
        ax.imshow(image.T, cmap='gray')
        for line in lines:
            ax.plot([line[0][1], line[1][1]],
                    [line[0][0], line[1][0]], 'r-', linewidth=2)

        ax.set_xlim([0, image.shape[0]])
        ax.set_ylim([0, image.shape[1]])
        plt.show()

    all_lines.extend(lines)
    modified_img1 = remove_pixels(image, 
                                  lines, 
                                  p_removal=p_removal,
                                  search_range=search_range)
    modified_img1 = morphology.remove_small_objects(modified_img1, 10)

    new_lines1 = probabilistic_hough_line(modified_img1, 
                                          line_length=50,
                                          line_gap=line_gap_in_pixel)

    if display:
        fig = plt.figure(figsize=const.figsize)
        ax = fig.add_subplot(111)
        ax.imshow(modified_img1.T, cmap='gray')
        for line in new_lines1:
            ax.plot([line[0][1], line[1][1]],
                    [line[0][0], line[1][0]], 'r-', linewidth=2)

        ax.set_xlim([0, image.shape[0]])
        ax.set_ylim([0, image.shape[1]])
        plt.show()
 
    all_lines.extend(new_lines1)
    modified_img2 = remove_pixels(modified_img1,
                                  new_lines1,
                                  p_removal=p_removal,
                                  search_range=search_range)
    modified_img2 = morphology.remove_small_objects(modified_img2, 20)

    new_lines2 = probabilistic_hough_line(modified_img2,
                                          line_length=20,
                                          line_gap=line_gap_in_pixel)
    all_lines.extend(new_lines2)

    if display:
        fig = plt.figure(figsize=const.figsize)
        ax = fig.add_subplot(111)
        ax.imshow(modified_img2.T, cmap='gray')
        for line in new_lines2:
            ax.plot([line[0][1], line[1][1]],
                    [line[0][0], line[1][0]], 'r-', linewidth=2)

        ax.set_xlim([0, image.shape[0]])
        ax.set_ylim([0, image.shape[1]])
        plt.show()
 
    orig_lines = []
    for line in all_lines:
        line_start = line[0]
        line_end = line[1]
        start_e = line_start[1]*grid_size + loc[0] - R
        start_n = line_start[0]*grid_size + loc[1] - R

        end_e = line_end[1]*grid_size + loc[0] - R
        end_n = line_end[0]*grid_size + loc[1] - R
        
        orig_line1 = [(start_e, start_n), (end_e, end_n)]
        orig_lines.append(orig_line1)
        orig_line2 = [(end_e, end_n), (start_e, start_n)]
        orig_lines.append(orig_line2)

    return np.array(orig_lines)
예제 #56
0
파일: piro.py 프로젝트: sy9976/piro_proj1
def process_img(i):
  fig, ax = plt.subplots()
  img = io.imread(i, as_grey=True)
  white_count = np.sum(img > 0)
  simg = sobel(img)
  gauss_img = gaussian(img, sigma=1)
  contours = measure.find_contours(gauss_img, 0.3)
  int_contour = []
  for n, contour in enumerate(contours):
    for point in contour:
      int_contour.append((round(point[0]), round(point[1])))
  int_contour = list(set(int_contour))
  black_img = img[:]
  black_img[:] = 0
  for point in int_contour: #contour
    black_img[point[0]][point[1]] = 1
  black_img = dilation(black_img, diamond(1))
  coords = corner_peaks(corner_harris(img), min_distance=1)
  ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
  plt.plot(coords[:, 1], coords[:, 0], '.r', markersize=5)
  sy, sx = img.shape
  print sy, sx
  cfiltered = get_extend_coord(img.shape, sy, sx, coords) #filtrowanie najbardziej wystajacych
  tmp_perim = simg
  angles = {}
  for c in cfiltered:
    cy, cx = c
    print " "
    iter_p = get_mean_coords(black_img, cy, cx, 25)
    print "Punkty sasiadujace"
    #print len(iter_points)
    print iter_p[0]
    print iter_p[1]
    try:
      angle = get_angle(c, iter_p[0], iter_p[1])
      print "ANGLE: " + str(angle)
    except ValueError:
      print "ANGLE_ERROR"
    angles[c] = abs(95 - angle)
    #tmp_perim += c_perim
  #plt.imshow(tmp_perim, cmap=plt.get_cmap('gray'))
  #print "Base_vertices:"
  v0, v1 = get_base_vertices(angles)
  black_img_line = img[:]
  black_img_line[:] = 0
  for point in int_contour: #nakladanie konturu
    black_img_line[point[0]][point[1]] = 1
  #black_img = dilation(black_img, diamond(1))
  remove_lines = probabilistic_hough_line(black_img_line, threshold=10, line_length=15, line_gap=2)
  max_line_length = 0
  black_img_line, max_line_length = filter_contours_lines(v0, v1, remove_lines, black_img_line, 6) #filtruje kontur z linii o poczatkach w okolicach punktow
  print "MAX_LINE_LENGTH: ", max_line_length
  print "DIMENSION: ", white_count/max_line_length
  #cnt = 0
  #plt.show()
  print "HISTOGRAM"
  tmp_hist = []
  tmpR = int(math.ceil(max_line_length/40))
  print "R for image is: ", tmpR
  print type(tmpR)
  for point in int_contour: #nakladanie konturu
    if black_img_line[point[0]][point[1]] == 1:
      #tmp_mean_coords = get_mean_coords(black_img, int(point[0]), int(point[1]), 4) #pobiera srednie wspolrzedne
      #print tmpR
      tmp_mean_coords = get_mean_coords(black_img, int(point[0]), int(point[1]), tmpR) #pobiera srednie wspolrzedne
      if len(tmp_mean_coords) < 2:
        print "not enough mean cords ", tmp_mean_coords
        continue
      try:
        angle = get_angle(point, tmp_mean_coords[0], tmp_mean_coords[1])
        tmp_hist.append(angle)
      except ValueError:
        print "ANGLE_ERROR"
        #result = 0  
      #print "HIST_ANGLE: " + str(angle)
      #angles[point] = abs(95 - angle)
  #plt.hist(gaussian_numbers)
  hist, bins = np.histogram(tmp_hist, normed = True, bins = 10)
  hist_dict[i] = hist
  #plt.plot()
  #plt.show()
  #plt.hist()
  
  print "KONIEC"
예제 #57
0
def readImage(image):
    blurredImage = image.filter(ImageFilter.GaussianBlur(radius = 2))
    imageData = toMatrix(blurredImage, blurredImage.size[0], blurredImage.size[1])
    cannyEdges = canny(imageData, sigma=3)
    #print "Canny edges: ", cannyEdges
    
    #Look for the most likely edges in our diagram
    gradientEdges = findEdgePoints(imageData)
    edges = probabilistic_hough_line(gradientEdges)
    
    #Look for local maxima in intensity
    nodes1 = findNodesIntensity(imageData)
    print nodes1
    #Look for circles on the boundary of each node
    hough_radii = np.arange(3, 15, 2)
    weights, centers, radii = findNodesHoughCircles(cannyEdges, hough_radii)
    
    #Choose the closest point in nodes1 for each circle in nodes2
    finalNodes = []
    for center in centers:
        minDistSq = 1000000
        minNode = nodes1[0]
        for node in nodes1:
            newDistSq = findDistSqPoints(center[0], center[1], node.x, node.y)
            #print "Next distance: ", node, newDistSq
            if(newDistSq < minDistSq):
                minDistSq = newDistSq
                minNode = node
        #print center, minNode, minDistSq
        finalNodes.append(minNode)
        
    printTest(imageData, finalNodes, cannyEdges, gradientEdges, edges)
    
    #Find all of the nodes within maxDist of each edge
    print "Finding nodes for each edge"
    graph = nx.Graph()
    maxDist = 20
    for edge in edges:
        #print "Edge: ", edge
        edgeNodes = []
        for node in finalNodes:
            dist = findDistPointToLine(node, edge)
            #print "Node: ", node
            #print "Distance: ", dist
            if(findDistPointToLine(node, edge) < maxDist):
                edgeNodes.append(node)
        
        if(len(edgeNodes) == 2):
            if(edgeNodes[0] not in graph.nodes()):
                graph.add_node(edgeNodes[0])
            if(edgeNodes[1] not in graph.nodes()):
                graph.add_node(edgeNodes[1])
            if((edgeNodes[0], edgeNodes[1]) not in graph.edges()):
                graph.add_edge(edgeNodes[0], edgeNodes[1])
        elif(len(edgeNodes) > 2):
            #Sort the nodes by the coordinate that varies the most
            slopeComp = abs(edgeNodes[0].x - edgeNodes[1].x) - abs(edgeNodes[0].y - edgeNodes[1].y)
            if(slopeComp > 0):
                edgeNodes.sort(key = lambda node: (node.x, node.y))
            else:
                edgeNodes.sort(key = lambda node: (node.y, node.x))
                
            #for i in xrange(len(edgeNodes) - 1):
                #Check the pair of adjacent nodes along this edge
                
            
    
    return graph
  
###gradient of smoothed image###  
sobel_result = sobel(den,height_nan_mask)  
#imshow(sobel_result, cmap=plt.cm.gray,interpolation="none")  
#viewer.ImageViewer(sobel_result).show()  

#threshold :
sobel_thres = sobel_result 
sobel_thres[sobel_thres<0.05] = 0 
imshow( sobel_thres, cmap=plt.cm.gray,interpolation="none")  



####line detection###

lines = probabilistic_hough_line(sobel_thres, threshold=10, line_length=6, line_gap=3)
len(lines)

for line in lines:
    p0, p1 = line 
    plt.plot((p0[0], p1[0]), (p0[1], p1[1]),linewidth = 4) 

imshow(sobel_thres, cmap=plt.cm.gray) ; plt.show() 



###line clustering###
"""We need to merge the lines to find the finale ones.
Fro this we want to compute angle of the liresult_clustering = DBSCAN(eps=10, min_samples=5, metric='euclidean', algorithm='auto', leaf_size=30, p=None, random_state=None).fit(line_array)nes (compared ot origin axisfor instance)
, then cluster on middle points coordinate + angle 
We need to perform some operation on angle so that some known angles comes together ()
for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
    y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
    y1 = (dist - image.shape[1] * np.cos(angle)) / np.sin(angle)
    ax[2].plot((0, image.shape[1]), (y0, y1), '-r')
ax[2].set_xlim((0, image.shape[1]))
ax[2].set_ylim((image.shape[0], 0))
ax[2].set_axis_off()
ax[2].set_title('Detected lines')

plt.tight_layout()
plt.show()

# Line finding using the Probabilistic Hough Transform
image = data.camera()
edges = canny(image, 2, 1, 25)
lines = probabilistic_hough_line(edges, threshold=10, line_length=5,
                                 line_gap=3)

# Generating figure 2
fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)
ax = axes.ravel()

ax[0].imshow(image, cmap=cm.gray)
ax[0].set_title('Input image')

ax[1].imshow(edges, cmap=cm.gray)
ax[1].set_title('Canny edges')

ax[2].imshow(edges * 0)
for line in lines:
    p0, p1 = line
    ax[2].plot((p0[0], p1[0]), (p0[1], p1[1]))
def main():
    tracks = gps_track.load_tracks(sys.argv[1])

    # Write 3D for Yangyan: skeleton
    #delta_easting = const.RANGE_NE[0] - const.RANGE_SW[0]
    #delta_northing = const.RANGE_NE[1] - const.RANGE_SW[1]
    #f = open("test_region_3D.txt", "w")
    #for track in tracks:
    #    for pt in track.utm:
    #        #if pt[0]<=const.RANGE_SW[0]+3000 and pt[0]>=const.RANGE_SW[0]+2000:
    #        #    if pt[1]<=const.RANGE_SW[1]+3000 and pt[1]>=const.RANGE_SW[1]+2000:
    #        pe = (pt[0] - const.RANGE_SW[0]) / delta_easting * 10
    #        pn = (pt[1] - const.RANGE_SW[1]) / delta_northing * 10
    #        f.write("%.6f %.6f %.6f\n"%(pe,pn,0.01*np.random.rand()))

    #f.close()
    #return

    N_ROW = 1000 # Divide northing
    N_COL = 1000 # Divide southing

    """
        test case index:
            0: Beijing
            1: SF small
    """
    test_case = 0

    if test_case == 0:
        rasterized_tracks, point_count_array, track_indexing_hash =\
                                    rasterize_tracks(tracks,
                                                     [const.RANGE_SW, const.RANGE_NE],
                                                     (N_ROW, N_COL)) 

    else:
        rasterized_tracks, point_count_array, track_indexing_hash =\
                                        rasterize_tracks(tracks,
                                                     [const.SF_small_RANGE_SW, const.SF_small_RANGE_NE],
                                                     (N_ROW, N_COL)) 


    dense_array = np.array(point_count_array.todense())

    lines = probabilistic_hough_line(dense_array,line_length=50)
    print len(lines)

    fig = plt.figure(figsize=const.figsize)
    ax = fig.add_subplot(111, aspect='equal')
    
    ax.imshow(dense_array>0, cmap='gray')

    for line in lines:
        ax.plot([line[0][0],line[1][0]],
                [line[0][1],line[1][1]],'-r')
    ax.set_xlim([0, N_ROW])
    ax.set_ylim([N_COL, 0])
    plt.show()
    return

    intersections = []
    angle_threshold = 0.71
    for line_i in range(0, len(lines)):
        for line_j in range(line_i+1, len(lines)):
            line1 = lines[line_i]
            line2 = lines[line_j]
            vec1 = 1.0*np.array([line1[1][0]-line1[0][0], line1[1][1]-line1[0][1]]) 
            vec2 = 1.0*np.array([line2[1][0]-line2[0][0], line2[1][1]-line2[0][1]]) 
            
            vec1 /= np.linalg.norm(vec1)
            vec2 /= np.linalg.norm(vec2)

            if abs(np.dot(vec1, vec2)) < angle_threshold:
                pc = line_segment_intersection(line1, line2)
                if pc[0] != np.inf:
                    intersections.append(pc)

    new_img = np.zeros((N_ROW, N_COL))

    for itr in intersections:
        new_img[itr[0],itr[1]] += 1
    
    peaks = corner_peaks(new_img, min_distance=20)

    ax = fig.add_subplot(122, aspect='equal')
    ax.imshow(dense_array>0, cmap='gray')
    for peak in peaks:
        ax.plot(peak[0], peak[1], '.r', markersize=12)
    ax.set_xlim([0, N_ROW])
    ax.set_ylim([N_COL, 0])
    plt.show()
    return


    window_size = 40
   
    i = 0

    img_data = []
    hog_features = []
    hog_imgs = []
    for peak in peaks:
        if peak[0]-window_size<0 or peak[0]+window_size>N_ROW or\
                peak[1]-window_size<0 or peak[1]+window_size>N_COL:
            continue
            
        fig = plt.figure(figsize=const.figsize)
        ax = fig.add_subplot(111, aspect='equal')
        
        ax.imshow(dense_array>0, cmap='gray')
        ax.plot(peak[0], peak[1], 'rx', markersize=12)

        ax.set_xlim([peak[0]-window_size, peak[0]+window_size])
        ax.set_ylim([peak[1]+window_size, peak[1]-window_size])

        plt.savefig("test_fig/fig_%d.png"%i)
        plt.close()

        new_img = dense_array[(peak[1]-window_size):(peak[1]+window_size), \
                              (peak[0]-window_size):(peak[0]+window_size)]
        img_data.append(new_img) 
        hog_array, hog_image = hog(np.array(new_img>0), pixels_per_cell=(4, 4), visualise=True)
        hog_features.append(hog_array)
        hog_imgs.append(hog_image)

        i += 1

    with open("test_fig/img_data.dat", "wb") as fout:
        cPickle.dump(img_data, fout, protocol=2 )
    with open("test_fig/hog_features.dat", 'wb') as fout:
        cPickle.dump(hog_features, fout, protocol=2)
    with open("test_fig/hog_imgs.dat", 'wb') as fout:
        cPickle.dump(hog_imgs, fout, protocol=2)

    return
    colors = cycle('bgrcmybgrcmybgrcmykbgrcmy')

    #ax.imshow(dense_array>0, cmap='gray')


    window_size = 80
    chosen_ij = (752, 814)
    #chosen_ij = (370, 408)
    search_range = 4
    G = nx.Graph()

    active_track_idxs = {}
    for i in range(chosen_ij[1]-window_size, chosen_ij[1]+window_size):
        for j in range(chosen_ij[0]-window_size, chosen_ij[0]+window_size):
            if dense_array[i,j] > 0:
                # Add graph nodes
                G.add_node((i,j))
                # Add edge to nearby nodes
                for k in range(i-search_range, i+search_range+1):
                    if k < chosen_ij[1]-window_size or k >= chosen_ij[1]+window_size:
                        continue
                    for l in range(j-search_range, j+search_range+1):
                        if l < chosen_ij[0]-window_size or l >= chosen_ij[0]+window_size:
                            continue
                        if dense_array[k,l] > 0:
                            G.add_edge((i,j),(k,l),{'w':1.0})

                for idx in track_indexing_hash[(i,j)].keys():
                    active_track_idxs[idx] = 1
  
    ax.set_xlim([chosen_ij[0]-window_size, chosen_ij[0]+window_size])
    ax.set_ylim([chosen_ij[1]-window_size, chosen_ij[1]+window_size])

    # Iterate over active tracks to add constraints
    to_break = False
    count = 0
    preserved_edges = {}
    for idx in active_track_idxs.keys():
        # Iterate over it's nodes
        for loc_idx in range(0, len(rasterized_tracks[idx])-1):
            cur_loc = rasterized_tracks[idx][loc_idx]
            nxt_loc = rasterized_tracks[idx][loc_idx+1]

            if abs(cur_loc[0]-nxt_loc[0])+abs(cur_loc[1]-nxt_loc[1])<2*search_range:
                continue
            cur_loc_ok = False
            nxt_loc_ok = False
            
            if cur_loc[0]>=chosen_ij[1]-window_size and cur_loc[0]<chosen_ij[1]+window_size:
                if cur_loc[1]>=chosen_ij[0]-window_size and\
                        cur_loc[1]<chosen_ij[0]+window_size:
                    cur_loc_ok = True
            if nxt_loc[0]>=chosen_ij[1]-window_size and nxt_loc[0]<chosen_ij[1]+window_size:
                if nxt_loc[1]>=chosen_ij[0]-window_size and\
                        nxt_loc[1]<chosen_ij[0]+window_size:
                    nxt_loc_ok = True
            
            if cur_loc_ok and nxt_loc_ok: 
                can_be_connected = nx.algorithms.has_path(G, cur_loc, nxt_loc)
                if can_be_connected:
                    count += 1
                    path = nx.shortest_path(G, source=cur_loc, target=nxt_loc, weight='w')
                    # Record edge
                    for node_idx in range(0,len(path)-1):
                        edge = (path[node_idx],path[node_idx+1])
                        preserved_edges[edge] = 1
                        # Reduce edge weight
                        G[path[node_idx]][path[node_idx+1]]['w'] /= 1.05 
                    #ax.plot([cur_loc[1],nxt_loc[1]],
                    #        [cur_loc[0],nxt_loc[0]],
                    #        'rx-')
        if to_break:
            break
    print "Count = ",count

    for edge in preserved_edges.keys():
        ax.plot([edge[0][1],edge[1][1]],
                [edge[0][0],edge[1][0]],'-r')

    plt.show()
    return
    chosen_i = np.random.randint(window_size, N_ROW-window_size)
    chosen_j = np.random.randint(window_size, N_COL-window_size)
    test_image = np.array(dense_array[chosen_ij[1]-window_size:chosen_ij[1]+window_size,\
                             chosen_ij[0]-window_size:chosen_ij[0]+window_size] > 0)

    fig = plt.figure(figsize=const.figsize)
    ax = fig.add_subplot(111, aspect='equal')
    ax.imshow(test_image>0, cmap='gray')

    plt.show()