joonsu0109's picture
Upload folder using huggingface_hub
4f85997 verified
"""
**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 tkinter import Tk # from tkinter import Tk for Python 3.x
# from tkinter.filedialog import askopenfilename
from tqdm import tqdm
# Helper functions
import copy
# 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):
# Implementation is based on workshop material
cv2.circle(image,point,3,(0,255,0), thickness=3)
cv2.imwrite("/root/data2/joonsu0109/project/naive_vp/vanishing_point.png", 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
### 2. Locate the vanishing point
### Use RANSAC to locate the vanishing point from the detected lines.
#### 2.1 RANSAC functions
#### Define two fuctions required by RANSAC: a function to find the point where lines intersect, and a function to compute the distance from a point to a line.
# 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
def find_vanishing_point(img, grid_size, intersections):
# Image dimensions
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)
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)
# center = (int(best_cell[0]), int(best_cell[1]))
# cv2.circle(img,center,5,(255,0,0), thickness=5)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# cv2.imwrite(save_path, img)
else:
raise ValueError("No best cell found!: ", save_path)
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"
output_folder = "/root/data2/joonsu0109/dataset/SemanticKITTI/grid_vp"
os.makedirs(output_folder, exist_ok=True)
input_dir_list = os.listdir(input_folder)
input_dir_list.sort()
edge = []
seq_list = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
for dirname in seq_list:
print("Processing folder: ", dirname)
file_list = os.listdir(os.path.join(input_folder, dirname, "image_2"))
file_list.sort()
vp_dict = dict()
for filename in tqdm(file_list):
idx = filename.split(".")[0]
if int(idx) % 5 == 0:
print("Processing: ", filename)
file_path = os.path.join(input_folder, dirname, "image_2", filename)
# Read images from folder
image = cv2.imread(file_path)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Task1: Detect lines using Canny + Hough
image_copy = image.copy()
blur_image, edge_image, lines = detect_lines(image)
if len(lines) > 100:
lines = sample_lines(lines, 100)
else:
pass
intersections = find_intersections(lines)
best_cell = find_vanishing_point(image, 50, intersections)
print("Best cell: ", best_cell)
save_key = os.path.join("SemanticKITTI/dataset/sequences", dirname, "image_2", filename)
vp_dict[save_key] = [best_cell]
print("Edge images: ", len(edge))
save_path = os.path.join(output_folder, f'ransac_vp_seq_{dirname}.json')
with open(save_path, 'w') as f:
json.dump(vp_dict, f)
print("Edge images: ", edge)
print("Edge images num: ", len(edge))
"""
Hyper parameters tunning
Note: the following code is not expected to run while marking. It will take hours to run.
In addition, tuning for Canny edge detection and Hough Transform are done as well. They are described in the report.
"""
"""
# Use grid search to tune hyperparameters for RANSAC
best_result = 10000
best_model = None
for ransac_iterations in range (150,351,50):
for ransac_threshold in range (10,15,1):
for ransac_ratio in np.arange(0.81,1,0.02):
sum_mse = 0
# Run 10 times to alleviate the effect of stochasticity
for it in range(0,10):
vanishing_points = RANSAC(lines_all,ransac_iterations,ransac_threshold,ransac_ratio)
single_mse = MSE(ground_truth, vanishing_points)
sum_mse += single_mse
mse_avg = sum_mse/10
if mse_avg < best_result:
best_result = mse_avg
best_model = ransac_iterations,ransac_threshold,ransac_ratio
print("Best model is:"+
"ransac_iterations="+str(best_model[0])+
", ransac_threshold="+str(best_model[1])+
", ransac_ratio="+str(best_model[2])+
", which give MSE "+str(best_result))
"""