How to measure the angle between 2 lines in a same image using python opencv?

2024/10/10 5:25:44

I have detected a lane boundary line which is not straight using hough transform and then extracted that line separately. Then blended with another image that has a straight line. Now I need to calculate the angle between those two lines, but I do not know the coordinates of those lines. So I tried with code that gives the coordinates of vertical lines, but it can not specifically identify those coordinates. Is there a way to measure the angle between those lines? Here is my coordinate calculation code and blended image with two lines

import cv2 as cv
import numpy as npsrc = cv.imread("blended2.png", cv.IMREAD_COLOR)if len(src.shape) != 2:gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
else:gray = srcgray = cv.bitwise_not(gray)
bw = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 15, -2)horizontal = np.copy(bw)
vertical = np.copy(bw)cols = horizontal.shape[1]
horizontal_size = int(cols / 30)horizontalStructure = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1))
horizontal = cv.erode(horizontal, horizontalStructure)
horizontal = cv.dilate(horizontal, horizontalStructure)cv.imwrite("img_horizontal8.png", horizontal)h_transpose = np.transpose(np.nonzero(horizontal))
print("h_transpose")
print(h_transpose[:100])rows = vertical.shape[0]
verticalsize = int(rows / 30)
verticalStructure = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize))
vertical = cv.erode(vertical, verticalStructure)
vertical = cv.dilate(vertical, verticalStructure)cv.imwrite("img_vertical8.png", vertical)v_transpose = np.transpose(np.nonzero(vertical))print("v_transpose")
print(v_transpose[:100])img = src.copy()# edges = cv.Canny(vertical,50,150,apertureSize = 3)
minLineLength = 100
maxLineGap = 200
lines = cv.HoughLinesP(vertical,1,np.pi/180,100,minLineLength,maxLineGap)
for line in lines:for x1,y1,x2,y2 in line:cv.line(img,(x1,y1),(x2,y2),(0,255,0),2)cv.imshow('houghlinesP_vert', img)
cv.waitKey(0)

enter image here

Answer

One approach is to use the Hough Transform to detect the lines and obtain the angle of each line. The angle between the two lines can then be found by subtracting the difference between the two lines.

We begin by performing an arithmetic average using np.mean to essentially threshold the image which results in this.

image = cv2.imread('2.png')# Compute arithmetic mean
image = np.mean(image, axis=2)

enter image description here

Now we perform skimage.transform.hough_line to detect lines

# Perform Hough Transformation to detect lines
hspace, angles, distances = hough_line(image)# Find angle
angle=[]
for _, a , distances in zip(*hough_line_peaks(hspace, angles, distances)):angle.append(a)

enter image description here

Next we obtain the angle for each line and find the difference to obtain our result

# Obtain angle for each line
angles = [a*180/np.pi for a in angle]# Compute difference between the two lines
angle_difference = np.max(angles) - np.min(angles)
print(angle_difference)

16.08938547486033

Full code

from skimage.transform import (hough_line, hough_line_peaks)
import numpy as np
import cv2image = cv2.imread('2.png')# Compute arithmetic mean
image = np.mean(image, axis=2)# Perform Hough Transformation to detect lines
hspace, angles, distances = hough_line(image)# Find angle
angle=[]
for _, a , distances in zip(*hough_line_peaks(hspace, angles, distances)):angle.append(a)# Obtain angle for each line
angles = [a*180/np.pi for a in angle]# Compute difference between the two lines
angle_difference = np.max(angles) - np.min(angles)
print(angle_difference)
https://en.xdnf.cn/q/69931.html

Related Q&A

How to modify variables in another python file?

windows 10 - python 3.5.2Hi, I have the two following python files, and I want to edit the second files variables using the code in the first python file.firstfile.pyfrom X.secondfile import *def edit(…

SciPy optimizer ignores one of the constraints

I am trying to solve an optimization problem where I need to create a portfolio that with a minimum tracking error from benchmark portfolio and its subject to some constraints:import scipy.optimize as …

How can one use HashiCorp Vault in Airflow?

I am starting to use Apache Airflow and I am wondering how to effectively make it use secrets and passwords stored in Vault. Unfortunately, search does not return meaningful answers beyond a yet-to-be-…

List all words in a dictionary that start with user input

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?Ex: User: "abd" Program:abdicate, abdomen, abduct..…

Python version of C#s conditional operator (?)

I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test.I have this code in Python:if self.trait == self.spouse.trait:trait = self.trait else:trait…

Python String Replace Error

I have a python script that keeps returning the following error:TypeError: replace() takes at least 2 arguments (1 given)I cannot for the life of me figure out what is causing this.Here is part of my c…

How to run two modules at the same time in IDLE

I am working on a super simple socket program and I have code for the client and code for the server. How do I run both these .py files at the same time to see if they work ?

Passing 2 dimensional C array to python numpy

I need some help regarding passing C array to python(numpy). I have 2d array of doubles NumRows x NumInputs, it seems that PyArray_SimpleNewFromData does not convert it right way - it is hard to see be…

Best way to implement numpy.sin(x) / x where x might contain 0

What I am doing now is:import numpy as npeps = np.finfo(float).epsdef sindiv(x):x = np.abs(x)return np.maximum(eps, np.sin(x)) / np.maximum(eps, x)But there is quite a lot of additional array operation…

Scrapy process.crawl() to export data to json

This might be a subquestion of Passing arguments to process.crawl in Scrapy python but the author marked the answer (that doesnt answer the subquestion im asking myself) as a satisfying one.Heres my pr…