File size: 12,077 Bytes
4f85997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
**Author:** Kuoyuan Li
"""
import itertools
import random
from itertools import starmap
# Import needed libraries
import matplotlib.pyplot as plt
import cv2  
import os
import numpy as np
import pandas as pd
import random
import math
from tqdm import tqdm
# Helper functions

# Show images given a list of images
def show_images(image):
    plt.figure()
    plt.imshow(image,cmap='gray')

# Load images from a folder given their filenames
def load_images(filename):
    try:
        img = cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB)
        return img
    except IOError:
        print("File is not an image\n")
        exit()

# Plot lines on original images 
def show_lines(image,lines):
    # Implementation is based on workshop material
    for line in lines:
        rho,theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        pt1 = (int(x0 + 1000*(-b)),int(y0 + 1000*(a)))
        pt2 = (int(x0 - 1000*(-b)),int(y0 - 1000*(a)))
        # Draws a line segment connecting two points, colour=(255,0,0) and thickness=2.
        cv2.line(image,pt1,pt2,(255,0,0),1)
    cv2.imwrite("/root/data2/joonsu0109/project/naive_vp/vanishing_lines.png", image)
    # plt.imshow(image)
    # plt.axis('off')
    # plt.show()



# Plot lines and points on original images 
def show_point(image, point, save_paths):
    # Implementation is based on workshop material
    cv2.circle(image,point,3,(255,0,0), thickness=3)
    cv2.imwrite(save_paths, image)
    # plt.imshow(image)
    # plt.axis('off')
    # plt.show()

## 1. Detect lines in the image
## Use the Canny edge detector and Hough transform to detect lines in the image.

def detect_lines(image):
    """
    Use Canny edge detection and Hough transform to get selected lines 
    (which are useful for locating vanishing point) for all images
    
    Args: images: a list of original images
    
    Return: blur_images: Blurred images (for report)
    edge_images: Edge images (for report)
    valid_lines_all: Detected lines
    """
    # Do blurry to smooth the image, try to remove edges from textures
    gau_kernel = cv2.getGaussianKernel(70,4)# 1d gaussian kernel (size, sigma)
    gau_kern2d = np.outer(gau_kernel, gau_kernel)
    gau_kern2d = gau_kern2d/gau_kern2d.sum() # 2d gaussian kernel to do blurry
    # Apply blurry filter
    blur_image = cv2.filter2D(image,-1,gau_kern2d)
    # Canny edge detection with OpenCV for all blurry images
    edge_image = cv2.Canny(blur_image,40,70,apertureSize=3,L2gradient=True)
    # Use hough transform to detect all lines
    lines=cv2.HoughLines(edge_image, 1, np.pi/120, 55)
    valid_lines = []
    # Remove horizontal and vertical lines as they would not converge to vanishing point
    for line in lines:
        rho,theta = line[0]
        if (theta>0.4 and theta < 1.47) or (theta > 1.67 and theta < 2.74):
            valid_lines.append(line)
    
    return blur_image,edge_image,valid_lines

# Find the intersection point
def find_intersection_point(line1,line2):
    """Implementation is based on code from https://stackoverflow.com/questions/46565975
    Original author: StackOverflow contributor alkasm 
    Find an intercept point of 2 lines model
    
    Args: line1,line2: 2 lines using rho and theta (polar coordinates) to represent
    
    Return: x0,y0: x and y for the intersection point
    """
    # rho and theta for each line
    rho1, theta1 = line1[0]
    rho2, theta2 = line2[0]
    # Use formula from https://stackoverflow.com/a/383527/5087436 to solve for intersection between 2 lines 
    A = np.array([
        [np.cos(theta1), np.sin(theta1)],
        [np.cos(theta2), np.sin(theta2)]
    ]) 
    b = np.array([[rho1], [rho2]])
    det_A = np.linalg.det(A)
    if det_A != 0:
        x0, y0 = np.linalg.solve(A, b)
        # Round up x and y because pixel cannot have float number
        x0, y0 = int(np.round(x0)), int(np.round(y0))
        return x0, y0
    else:
        return None
        
    
# Find the distance from a point to a line
def find_dist_to_line(point,line):
    """Implementation is based on Computer Vision material, owned by the University of Melbourne
    Find an intercept point of the line model with a normal from point to it, to calculate the
    distance betwee point and intercept
    
    Args: point: the point using x and y to represent
    line: the line using rho and theta (polar coordinates) to represent
    
    Return: dist: the distance from the point to the line
    """
    x0,y0 = point
    rho, theta = line[0]
    m = (-1*(np.cos(theta)))/np.sin(theta)
    c = rho/np.sin(theta)
    # intersection point with the model
    x = (x0 + m*y0 - m*c)/(1 + m**2)
    y = (m*x0 + (m**2)*y0 - (m**2)*c)/(1 + m**2) + c
    dist = math.sqrt((x - x0)**2 + (y - y0)**2)
    return dist



def RANSAC(lines,ransac_iterations,ransac_threshold,ransac_ratio):
    """Implementation is based on code from Computer Vision material, owned by the University of Melbourne
    Use RANSAC to identify the vanishing points for all images
    
    Args: lines_all: The lines for all images
    ransac_iterations,ransac_threshold,ransac_ratio: RANSAC hyperparameters
    
    Return: vanishing_points: Estimated vanishing points for all images
    """
    # Store vanishing point for the image
    inlier_count_ratio = 0.
    vanishing_point = (0,0)
    # perform RANSAC iterations for each set of lines
    print("NRANSAC")
    for iteration in range(ransac_iterations):
        # randomly sample 2 lines
        n = 2
        selected_lines = random.sample(lines,n)
        line1 = selected_lines[0]
        line2 = selected_lines[1]
        intersection_point = find_intersection_point(line1,line2)
        if intersection_point is not None:
            # count the number of inliers num
            inlier_count = 0
            # inliers are lines whose distance to the point is less than ransac_threshold
            for line in lines:
                # find the distance from the line to the point
                dist = find_dist_to_line(intersection_point,line)
                # check whether it's an inlier or not
                if dist < ransac_threshold:
                    inlier_count += 1

            # If the value of inlier_count is higher than previously saved value,
            # save it, and save the current point
            if inlier_count/float(len(lines)) > inlier_count_ratio:
                inlier_count_ratio = inlier_count/float(len(lines))
                vanishing_point = intersection_point

            # We are done in case we have enough inliers
            if inlier_count > len(lines)*ransac_ratio:
                break
    return vanishing_point

def find_vanishing_point(img, grid_size, intersections):
    # Image dimensions
    print("img.shape: ",img.shape)
    image_height = img.shape[0]
    image_width = img.shape[1]

    # Grid dimensions
    grid_rows = (image_height // grid_size) + 1
    grid_columns = (image_width // grid_size) + 1

    # Current cell with most intersection points
    max_intersections = 0
    best_cell = (0.0, 0.0)

    for i, j in itertools.product(range(grid_columns),range(grid_rows)):

        cell_left = i * grid_size
        cell_right = (i + 1) * grid_size
        cell_bottom = j * grid_size
        cell_top = (j + 1) * grid_size
        
        center_cell = ((cell_left + cell_right) / 2, (cell_bottom + cell_top) / 2)
 
        cv2.rectangle(img, (cell_left, cell_bottom), (cell_right, cell_top), (0, 0, 255), 5)

        current_intersections = 0  # Number of intersections in the current cell
        for x, y in intersections:
            if cell_left < x < cell_right and cell_bottom < y < cell_top:
                current_intersections += 1

        # Current cell has more intersections that previous cell (better)
        if current_intersections > max_intersections:
            max_intersections = current_intersections
            best_cell = ((cell_left + cell_right) / 2, (cell_bottom + cell_top) / 2)
            print("Best Cell:", best_cell)

    if best_cell[0] != None and best_cell[1] != None:
        rx1 = int(best_cell[0] - grid_size / 2)
        ry1 = int(best_cell[1] - grid_size / 2)
        rx2 = int(best_cell[0] + grid_size / 2)
        ry2 = int(best_cell[1] + grid_size / 2)
        cv2.rectangle(img, (rx1, ry1), (rx2, ry2), (0, 255, 0), 10)
        cv2.imwrite('/root/data2/joonsu0109/project/naive_vp/vanishing-point-detection/outputs/result.png', img)

    return best_cell

### 3. Main function
### Run your vanishing point detection method on a folder of images, return the (x,y) locations of the vanishing points


# RANSAC parameters:

def line_intersection(line1, line2):
    """
    Computes the intersection point of two lines in polar coordinates (rho, theta).

    Args:
        line1 (np.ndarray): First line, represented as (rho, theta).
        line2 (np.ndarray): Second line, represented as (rho, theta).

    Returns:
        tuple or None: Intersection point (x, y), or None if lines are parallel.
    """
    # Extract (rho, theta) for each line
    rho1, theta1 = line1[0]
    rho2, theta2 = line2[0]

    # Represent lines in the form: a1*x + b1*y = c1
    a1, b1 = np.cos(theta1), np.sin(theta1)
    c1 = rho1
    a2, b2 = np.cos(theta2), np.sin(theta2)
    c2 = rho2

    # Solve the system of linear equations
    A = np.array([[a1, b1], [a2, b2]])
    C = np.array([c1, c2])

    # Check if determinant is close to zero (parallel lines)
    det = np.linalg.det(A)
    if abs(det) < 1e-6:
        return None

    # Find the intersection point
    x, y = np.linalg.solve(A, C)
    return x, y


def find_intersections(lines):
    """
    Finds intersections between pairs of lines.
    
    Args:
        lines (np.ndarray): Array of lines in the format (n, 1, 2),
                            where each line is represented as (rho, theta).
    
    Returns:
        list: List of intersection points [(x, y), ...].
    """
    intersections = []
    for i, line_1 in enumerate(lines):
        for line_2 in lines[i + 1:]:
            intersection = line_intersection(line_1, line_2)
            if intersection is not None:  # If lines intersect, add the point
                intersections.append(intersection)
    return intersections

def sample_lines(lines, size):
    if size > len(lines):
        size = len(lines)
    return random.sample(lines, size)

if __name__ == "__main__":
    # Tk().withdraw()  # we don't want a full GUI, so keep the root window from appearing
    # filename = askopenfilename()  # show an "Open" dialog box and return the path to the selected file
    """For the image, Use Canny+Hough to detect edges, use RANSAC to identify the vanishing points
    """
    input_folder = "/root/data2/joonsu0109/dataset/SemanticKITTI/dataset/sequences/08/image_2"
    output_folder = "/root/data2/joonsu0109/project/naive_vp/outputs_ransac"
    os.makedirs(output_folder, exist_ok=True)
    file_list = os.listdir(input_folder)
    detected_list = os.listdir(output_folder)
    for filename in tqdm(file_list):
        # Read images from folder
        if filename not in detected_list:
            try:
                print("Processing image: ",filename)
                file_path = os.path.join(input_folder, filename)
                save_paths = os.path.join(output_folder, filename)
                image = cv2.imread(file_path)
                # Task1: Detect lines using Canny + Hough
                blur_image, edge_image, lines = detect_lines(image)
                print("Number of lines detected: ",len(lines))
                # Show lines on the original images
                # show_lines(image, lines)
                
                ransac_iterations,ransac_threshold,ransac_ratio = 50,10,0.93
                vanishing_point = RANSAC(lines, ransac_iterations, ransac_threshold, ransac_ratio)

                show_point(image, vanishing_point, save_paths)
            except:
                print("Error processing image: ",filename)
                continue