Last active
March 9, 2016 19:47
-
-
Save VolgaStack/cfa32f7d85f0957c4c23 to your computer and use it in GitHub Desktop.
fuction that returns most occuring parallel lines in set of lines.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def parallel_lines(line_array, min_lines_num=5): | |
| """ Returns numpy_array with only min_lines_num parallel lines left. | |
| returns parallel lines with most occurring slopes | |
| :param line_array: np.array generated via cv2.HoughTransformP() | |
| :param min_lines_num: amount of lines that will be analyzed, pass odd numbers. | |
| :return: line array with only parallel lines or array with only first line | |
| """ | |
| def calc_slope(p1_x, p1_y, p2_x, p2_y): | |
| def round_down(num, divisor): | |
| num[num < 0] *= -1 | |
| return num - num % divisor | |
| delta_y = p2_y - p1_y | |
| delta_x = p2_x - p1_x | |
| # masking to prevent zero division error | |
| delta_x[delta_x == 0] = 1 | |
| return round_down(delta_y / delta_x, 10) | |
| array_len = len(line_array) | |
| # if len of incoming array is 1 just return it | |
| split = min(min_lines_num, array_len if array_len % 2 else array_len - 1) | |
| if split == 1: | |
| return line_array | |
| # numpy fancy indexing to get array of all values in column | |
| x1, y1, x2, y2 = [line_array[:array_len, 0, x] for x in (0, 1, 2, 3)] | |
| slope = calc_slope(x1, y1, x2, y2) | |
| slopes = Counter(slope) | |
| # if slopes are same for every element in array just return array with only first element | |
| slopes_values = slopes.values() | |
| if min(slopes_values) == max(slopes_values): | |
| return line_array[:1] | |
| # get indexes of most occurring slope and use "numpy magic" to return array based on those indexes | |
| key = slopes.most_common(1)[0][0] | |
| item_index = np.where(slope == key) | |
| return line_array[item_index] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment