Example #1
0
def find_Lines(im):
    out = cv.CreateImage(cv.GetSize(im), 8, 1)
    tmp = cv.CreateImage(cv.GetSize(im), 8, 3)
    storage = cv.CreateMemStorage(0)
    cv.Canny(im, out, 50, 200, 3)
    cv.CvtColor(out, tmp, cv.CV_GRAY2BGR)
    return cv.HoughLines2(out, storage, cv.CV_HOUGH_STANDARD, 1, pi / 180, 100,
                          0, 0)
Example #2
0
 def find_lines_in_map_probabilistic(self, map_img):
     #Finds lines in the image using the probabilistic hough transform
     lines=cv.CreateMemStorage(0)
     line_img=cv.CreateMat(map_img.height, map_img.width, cv.CV_8UC1)
     cv.Set(line_img, 255)
     lines = cv.HoughLines2(map_img,cv.CreateMemStorage(), cv.CV_HOUGH_PROBABILISTIC, self.hough_rho,np.pi/2,self.hough_threshold)
     np_line=np.asarray(lines)
     print "list of probabilistic lines: ", np_line
Example #3
0
def lines2():
    im = cv.LoadImage('roi_edges.jpg', cv.CV_LOAD_IMAGE_GRAYSCALE)
    pi = math.pi
    x = 0
    dst = cv.CreateImage(cv.GetSize(im), 8, 1)
    cv.Canny(im, dst, 200, 200)
    cv.Threshold(dst, dst, 100, 255, cv.CV_THRESH_BINARY)
    color_dst_standard = cv.CreateImage(cv.GetSize(im), 8, 3)
    cv.CvtColor(im, color_dst_standard,
                cv.CV_GRAY2BGR)  #Create output image in RGB to put red lines
    lines = cv.HoughLines2(dst, cv.CreateMemStorage(0), cv.CV_HOUGH_STANDARD,
                           1, pi / 100, 71, 0, 0)
    klsum = 0
    klaver = 0
    krsum = 0
    kraver = 0

    #global k
    #k=0
    for (rho, theta) in lines[:100]:
        kl = []
        kr = []
        a = math.cos(theta)
        b = math.sin(theta)
        x0 = a * rho
        y0 = b * rho
        pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a)))
        pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a)))
        k = ((y0 - 1000 * (a)) - (y0 + 1000 * (a))) / ((x0 - 1000 * (-b)) -
                                                       (x0 + 1000 * (-b)))

        if abs(k) < 0.4:
            pass
        elif k > 0:
            kr.append(k)
            len_kr = len(kr)
            for i in kr:
                krsum = krsum + i
                kraver = krsum / len_kr

                cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2,
                        4)
        elif k < 0:
            kr.append(k)
            kl.append(k)
            len_kl = len(kl)
            for i in kl:
                klsum = klsum + i
                klaver = klsum / len_kl
                cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2,
                        4)
        #print k
    #  cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4)
    cv.SaveImage('lane.jpg', color_dst_standard)
    print '左车道平均斜率:', klaver, '  右车道平均斜率:', kraver
    cv.ShowImage("Hough Standard", color_dst_standard)
    cv.WaitKey(0)
    def process(self):
        range_x = np.ceil((self.maxx - self.minx) * (1. / self.resolution)) + 1
        range_y = np.ceil((self.maxy - self.miny) * (1. / self.resolution)) + 1

        np_src = np.zeros((range_x, range_y), dtype=np.uint8)
        for el in self.xy.T:
            el_x = np.ceil((el[0] - self.minx) * (1. / self.resolution))
            el_y = np.ceil((el[1] - self.miny) * (1. / self.resolution))
            np_src[el_x, el_y] = 255

        src = cv.fromarray(np_src)
        storage = cv.CreateMemStorage(0)
        self.lines = 0
        self.lines = cv.HoughLines2(src, storage, cv.CV_HOUGH_PROBABILISTIC,
                               self.pixel_res, self.theta_res,
                               threshold=self.accum_thresh,
                               param1=self.min_length,
                               param2=self.gap_length)
Example #5
0
    if tracking == 0:
        detected = 0
        cv.Smooth(grey, dst2, cv.CV_GAUSSIAN, 3)
        cv.Laplace(dst2, d)
        cv.CmpS(d, 8, d2, cv.CV_CMP_GT)

        if onlyBlackCubes:
            #can also detect on black lines for improved robustness
            cv.CmpS(grey, 100, b, cv.CV_CMP_LT)
            cv.And(b, d2, d2)

        #these weights should be adaptive. We should always detect 100 lines
        if lastdetected > dects: THR = THR + 1
        if lastdetected < dects: THR = max(2, THR - 1)
        li = cv.HoughLines2(d2, cv.CreateMemStorage(),
                            cv.CV_HOUGH_PROBABILISTIC, 1, 3.1415926 / 45, THR,
                            10, 5)

        #store angles for later
        angs = []
        for (p1, p2) in li:
            #cv.Line(sg,p1,p2,(0,255,0))
            a = atan2(p2[1] - p1[1], p2[0] - p1[0])
            if a < 0: a += pi
            angs.append(a)

        #lets look for lines that share a common end point
        t = 10
        totry = []
        for i in range(len(li)):
            p1, p2 = li[i]
def extract_features(filename, is_url=False):
    '''Extracts features to be used in text image classifier.
    :param filename: input image
    :param is_url: is input image a url or a file path on disk
    :return: tuple of features:
    (average_slope, median_slope, average_tilt, median_tilt, median_differences, average_differences, nr_straight_lines)
    Most relevant ones are average_slope, average_differences and nr_straight_lines.
    '''

    if is_url:
        filedata = urllib2.urlopen(filename).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        src = cv.DecodeImageM(imagefiledata, cv.CV_LOAD_IMAGE_GRAYSCALE)
    else:
        src = cv.LoadImage(filename, cv.CV_LOAD_IMAGE_GRAYSCALE)

    # normalize size
    normalized_size = 400

    # smaller dimension will be 400, longer dimension will be proportional
    orig_size = cv.GetSize(src)

    max_dim_idx = max(enumerate(orig_size), key=lambda l: l[1])[0]
    min_dim_idx = [idx for idx in [0, 1] if idx != max_dim_idx][0]
    new_size = [0, 0]
    new_size[min_dim_idx] = normalized_size
    new_size[max_dim_idx] = int(
        float(orig_size[max_dim_idx]) / orig_size[min_dim_idx] *
        normalized_size)
    dst = cv.CreateImage(new_size, 8, 1)
    cv.Resize(src, dst)
    # cv.SaveImage("/tmp/resized.jpg",dst)
    src = dst

    dst = cv.CreateImage(cv.GetSize(src), 8, 1)
    color_dst = cv.CreateImage(cv.GetSize(src), 8, 3)
    storage = cv.CreateMemStorage(0)

    cv.Canny(src, dst, 50, 200, 3)
    cv.CvtColor(dst, color_dst, cv.CV_GRAY2BGR)

    slopes = []
    # difference between xs or ys - variant of slope
    tilts = []
    # x coordinates of horizontal lines
    horizontals = []
    # y coordinates of vertical lines
    verticals = []

    if USE_STANDARD:
        coords = cv.HoughLines2(dst, storage, cv.CV_HOUGH_STANDARD, 1,
                                pi / 180, 50, 50, 10)
        lines = []
        for coord in coords:
            (rho, theta) = coord
            a = cos(theta)
            b = sin(theta)
            x0 = a * rho
            y0 = b * rho
            pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a)))
            pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a)))
            lines += [(pt1, pt2)]

    else:
        lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_PROBABILISTIC, 1,
                               pi / 180, 50, 50, 10)

    # eliminate duplicates - there are many especially with the standard version
    # first round the coordinates to integers divisible with 5 (to eliminate different but really close ones)
    # TODO
    # lines = list(set(map(lambda l: tuple([int(p) - int(p)%5 for p in l]), lines)))

    nr_straight_lines = 0
    for line in lines:
        (pt1, pt2) = line

        # compute slope, rotate the line so that the slope is smallest
        # (slope is either delta x/ delta y or the reverse)
        # add smoothing term in denominator in case of 0
        slope = min(
            abs(pt1[1] - pt2[1]),
            (abs(pt1[0] - pt2[0]))) / (max(abs(pt1[1] - pt2[1]),
                                           (abs(pt1[0] - pt2[0]))) + 0.01)
        # if slope < 0.1:
        # if slope < 5:
        if slope < 0.05:
            if abs(pt1[0] - pt2[0]) < abs(pt1[1] - pt2[1]):
                # means it's a horizontal line
                horizontals.append(pt1[0])
            else:
                verticals.append(pt1[1])
        if slope < 0.05:
            # if slope < 5:
            # if slope < 0.1:
            nr_straight_lines += 1
        slopes.append(slope)
        tilts.append(min(abs(pt1[1] - pt2[1]), (abs(pt1[0] - pt2[0]))))
        # print slope
    average_slope = sum(slopes) / float(len(slopes))
    median_slope = npmedian(nparray(slopes))
    average_tilt = sum(tilts) / float(len(tilts))
    median_tilt = npmedian(nparray(tilts))
    differences = []
    horizontals = sorted(horizontals)
    verticals = sorted(verticals)
    print "x_differences:"
    for (i, x) in enumerate(horizontals):
        if i > 0:
            # print abs(horizontals[i] - horizontals[i-1])
            differences.append(abs(horizontals[i] - horizontals[i - 1]))
    print "y_differences:"
    for (i, y) in enumerate(verticals):
        if i > 0:
            # print abs(verticals[i] - verticals[i-1])
            differences.append(abs(verticals[i] - verticals[i - 1]))

    print filename
    print "average_slope:", average_slope
    print "median_slope:", median_slope
    print "average_tilt:", average_tilt
    print "median_tilt:", median_tilt
    median_differences = npmedian(nparray(differences))
    print "median_differences:", median_differences
    if not differences:
        # big random number for average difference
        average_differences = 50
    else:
        average_differences = sum(differences) / float(len(differences))
    print "average_differences:", average_differences
    print "nr_lines:", nr_straight_lines

    # print "sorted xs:", sorted(lines)

    return (average_slope, median_slope, average_tilt, median_tilt,
            median_differences, average_differences, nr_straight_lines)
Example #7
0
        cv.SetData(imagefiledata, filedata, len(filedata))
        src = cv.DecodeImageM(imagefiledata, cv.CV_LOAD_IMAGE_GRAYSCALE)

    cv.NamedWindow("Source", 1)
    cv.NamedWindow("Hough", 1)

    while True:
        dst = cv.CreateImage(cv.GetSize(src), 8, 1)
        color_dst = cv.CreateImage(cv.GetSize(src), 8, 3)
        storage = cv.CreateMemStorage(0)
        lines = 0
        cv.Canny(src, dst, 50, 200, 3)
        cv.CvtColor(dst, color_dst, cv.CV_GRAY2BGR)

        if USE_STANDARD:
            lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_STANDARD, 1,
                                   pi / 180, 100, 0, 0)
            for (rho, theta) in lines[:100]:
                a = cos(theta)
                b = sin(theta)
                x0 = a * rho
                y0 = b * rho
                pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a)))
                pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a)))
                cv.Line(color_dst, pt1, pt2, cv.RGB(255, 0, 0), 3, 8)
        else:
            lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_PROBABILISTIC, 1,
                                   pi / 180, 50, 50, 10)
            for line in lines:
                cv.Line(color_dst, line[0], line[1], cv.CV_RGB(255, 0, 0), 3,
                        8)
Example #8
0
            cv.DestroyAllWindows()
            sys.exit(-1)

        cv.NamedWindow("Source", 1)
        cv.NamedWindow("Hough", 1)

    while True:
        dst = cv.CreateImage(cv.GetSize(src), 8, 1)
        color_dst = cv.CreateImage(cv.GetSize(src), 8, 3)
        storage = cv.CreateMemStorage(0)
        lines = 0
        cv.Canny(src, dst, 50, 200, 3)
        cv.CvtColor(dst, color_dst, cv.CV_GRAY2BGR)

        if USE_STANDARD:
            lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_STANDARD, 1,
                                   pi / 180, 100, 0, 0)
            for (rho, theta) in lines[:100]:
                a = cos(theta)
                b = sin(theta)
                x0 = a * rho
                y0 = b * rho
                pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a)))
                pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a)))
                cv.Line(color_dst, pt1, pt2, cv.RGB(255, 0, 0), 3, 8)
                print('detected line at(' + str(x0) + ',' + str(y0) + ')')
                print('(' + str(pt1) + ',' + str(pt2) + ')')
        else:
            deltaRho = float(1)
            deltaTheta = float(pi / 2)
            minVote = 20
            minLength = 50
im = cv.LoadImage('14_108_eae2591dbc033d9.jpg', cv.CV_LOAD_IMAGE_GRAYSCALE)

pi = math.pi  #Pi value

dst = cv.CreateImage(cv.GetSize(im), 8, 1)

cv.Canny(im, dst, 200, 200)
cv.Threshold(dst, dst, 100, 255, cv.CV_THRESH_BINARY)

#---- Standard ----
color_dst_standard = cv.CreateImage(cv.GetSize(im), 8, 3)
cv.CvtColor(im, color_dst_standard,
            cv.CV_GRAY2BGR)  #Create output image in RGB to put red lines

lines = cv.HoughLines2(dst, cv.CreateMemStorage(0), cv.CV_HOUGH_STANDARD, 1,
                       pi / 180, 100, 0, 0)
for (rho, theta) in lines[:100]:
    a = math.cos(theta)  #Calculate orientation in order to print them
    b = math.sin(theta)
    x0 = a * rho
    y0 = b * rho
    pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a)))
    pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a)))
    cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2,
            4)  #Draw the line

#---- Probabilistic ----
color_dst_proba = cv.CreateImage(cv.GetSize(im), 8, 3)
cv.CvtColor(im, color_dst_proba, cv.CV_GRAY2BGR)  # idem

rho = 1
Example #10
0
import time
import math
import matplotlib.pyplot as plt
import cv2.cv as cv2
import numpy as np

# Foto con fondo cuadrado
img = Image('/home/pi/Documents/Lab3/foto4.png')
(r, g, b) = img.splitChannels(False)

r.save('/home/pi/Documents/Lab3/red4.png')
g.save('/home/pi/Documents/Lab3/green4.png')
b.save('/home/pi/Documents/Lab3/blue4.png')

img = cv2.LoadImage('/home/pi/Documents/Lab3/foto4.png',
                    cv2.CV_LOAD_IMAGE_GRAYSCALE)

pi = math.pi

dst = cv2.CreateImage(cv2.GetSize(img), 8, 1)
cv2.Canny(img, dst, 100, 200)
cv2.Threshold(dst, dst, 100, 255, cv2.CV_THRESH_BINARY)
color_dst_standard = cv2.CreateImage(cv2.GetSize(img), 8, 3)
cv2.CvtColor(img, color_dst_standard, cv2.CV_GRAY2BGR)
lines = cv2.HoughLines2(dst, cv2.CreateMemStorage(0), cv2.CV_HOUGH_STANDARD, 1,
                        pi / 180, 100, 0, 0)
cv2.ShowImage('Image', img)
cv2.ShowImage("Cannied", dst)

cv2.WaitKey(0)
Example #11
0
    def find_lines_in_map(self, map_img):
        #Finds lines in the image
        lines=cv.CreateMemStorage(0)
        line_img=cv.CreateMat(map_img.height, map_img.width, cv.CV_8UC1)
        cv.Set(line_img, 255)
        lines = cv.HoughLines2(map_img,cv.CreateMemStorage(), cv.CV_HOUGH_MULTI_SCALE, self.hough_rho,np.pi/2,self.hough_threshold)
        np_line=np.asarray(lines)
        print
        x0=[]#A vector of all the X0
        y0=[]#A vector of all the Y0
        theta0=[]
        n=0
        #Print the lines so that we can see what is happening
        for rho,theta in np_line:
            a = np.cos(theta)
            b = np.sin(theta)
            x0.append(a*rho)
            y0.append(b*rho)
            theta0.append(theta)
            x1 = int(x0[n] + 3000*(-b))
            y1 = int(y0[n] + 3000*(a))
            x2 = int(x0[n] - 3000*(-b))
            y2 = int(y0[n] - 3000*(a))
            cv.Line(map_img,(x1,y1),(x2,y2),0,1)
            cv.Line(line_img,(x1,y1),(x2,y2),0,1)
            n = n+1

        #create two lists with the x coordinate of vertical lines and y coordinate of horixontal lines.
        theta_rounded = np.round(theta0, 1)
        y_sorted = np.sort(np.round(y0,0))
        ylist=[]
        xlist=[]
        n=0
        for element in theta_rounded:
            if element == 0:#Horizontal line
                xlist.append(x0[n])
            else:
                ylist.append(y0[n])
            n=n+1

        Ym=[]
        Xm=[]
        ordered_y = np.sort(ylist)
        ordered_x = np.sort(xlist)
        print ordered_x
        last_element =0

        #Find middle points between lines
        for element in ordered_y:
            delta_element = element - last_element
            Ym.append(last_element+(delta_element)/2)
            last_element = deepcopy(element)
        last_element =0
        for element in ordered_x:
            delta_element = element - last_element
            Xm.append(last_element+(delta_element)/2)
            last_element = deepcopy(element)

        #Printing the points in a map
        for yi in Ym:
            for xi in Xm:
                if self.map_img[yi,xi] >= 250: #If free space
                    self.goal_list.append([yi,xi])
                    map_img[yi,xi]=255
                    self.goal_map[yi,xi]=0


        return map_img