To detect both yellow and white lines on the road, you will need to create an additional mask for the white color and then combine it with the mask for the yellow color. This combined mask will then be used for edge detection and line detection.
User
give mw the entire code
Assistant
User
still cannot detect the white line]
Assistant
User
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\design_project\melame.py", line 144, in
mask = cv2.bitwise_or(yellow_mask, white_mask)
cv2.error: OpenCV(4.8.1) :-1: error: (-5:Bad argument) in function 'bitwise_or'
Overload resolution failed:
src2 is not a numerical tuple
Expected Ptrcv::UMat for argument 'src2'
Assistant
def checker(self, line_new, groups, min_distance_to_merge, min_angle_to_merge):
for group in groups:
for line_old in group:
if self.get_distance(line_old, line_new) < min_distance_to_merge:
orientation_new = self.get_orientation(line_new)
orientation_old = self.get_orientation(line_old)
if abs(orientation_new - orientation_old) < min_angle_to_merge:
group.append(line_new)
return False
return True
def DistancePointLine(self, point, line):
px, py = point
x1, y1, x2, y2 = line
def lineMagnitude(x1, y1, x2, y2):
lineMagnitude = math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))
return lineMagnitude
LineMag = lineMagnitude(x1, y1, x2, y2)
if LineMag < 0.00000001:
DistancePointLine = 9999
return DistancePointLine
u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
u = u1 / (LineMag * LineMag)
if (u < 0.00001) or (u > 1):
ix = lineMagnitude(px, py, x1, y1)
iy = lineMagnitude(px, py, x2, y2)
if ix > iy:
DistancePointLine = iy
else:
DistancePointLine = ix
else:
ix = x1 + u * (x2 - x1)
iy = y1 + u * (y2 - y1)
DistancePointLine = lineMagnitude(px, py, ix, iy)
return DistancePointLine
def get_distance(self, a_line, b_line):
dist1 = self.DistancePointLine(a_line[:2], b_line)
dist2 = self.DistancePointLine(a_line[2:], b_line)
dist3 = self.DistancePointLine(b_line[:2], a_line)
dist4 = self.DistancePointLine(b_line[2:], a_line)
return min(dist1, dist2, dist3, dist4)
def merge_lines_pipeline_2(self, lines):
groups = []
min_distance_to_merge = 30
min_angle_to_merge = 30
groups.append([lines[0]])
for line_new in lines[1:]:
if self.checker(line_new, groups, min_distance_to_merge, min_angle_to_merge):
groups.append([line_new])
return groups
def merge_lines_segments1(self, lines):
orientation = self.get_orientation(lines[0])
if len(lines) == 1:
return [lines[0][:2], lines[0][2:]]
points = []
for line in lines:
points.append(line[:2])
points.append(line[2:])
if 45 < orientation < 135:
points = sorted(points, key=lambda point: point[1])
else:
points = sorted(points, key=lambda point: point[0])
return [points[0], points[-1]]
def process_lines(self, lines, img):
lines_x = []
lines_y = []
for line_i in [l[0] for l in lines]:
orientation = self.get_orientation(line_i)
if 45 < orientation < 135:
lines_y.append(line_i)
else:
lines_x.append(line_i)
lines_y = sorted(lines_y, key=lambda line: line[1])
lines_x = sorted(lines_x, key=lambda line: line[0])
merged_lines_all = []
for i in [lines_x, lines_y]:
if len(i) > 0:
groups = self.merge_lines_pipeline_2(i)
merged_lines = []
for group in groups:
merged_lines.append(self.merge_lines_segments1(group))
merged_lines_all.extend(merged_lines)
return merged_lines_all
while video.isOpened():
ret, orig_frame = video.read()
if not ret:
video = cv2.VideoCapture("road_car_view.mp4")
continue
frame = cv2.GaussianBlur(orig_frame, (5, 5), 0)
This Python script uses OpenCV to detect and draw lane lines on a video of a road from a car's perspective. Let me summarize what takes place in the code:
The video "road_car_view.mp4" is opened and read frame by frame.
A class HoughBundler is defined to process detected lines with the following methods:
get_orientation(line): calculates the orientation of a line in degrees.
checker(line_new, groups, min_distance_to_merge, min_angle_to_merge): checks whether a new line should be added to an existing group based on distance and angle criteria.
DistancePointLine(point, line): computes the minimum distance from a point to a line.
get_distance(a_line, b_line): calculates the smallest distance between any end points of two line segments.
merge_lines_pipeline_2(lines): groups lines that are close in distance and angle.
merge_lines_segments1(lines): merges a group of lines into a single line segment based on their orientation.
process_lines(lines, img): processes all lines, classifying them by orientation and merging them into line segments.
The region_of_interest(image) function is defined to apply a mask to the input image and keep only the pixels within a predefined polygon. Here the region of interest is the lane in front of the vehicle.
The script enters a while loop that runs as long as the video is open. It reads each frame, applies a Gaussian blur, and converts it from BGR to HSV color space.
A mask is applied to detect yellow color in the frame.
Canny edge detection is used to find edges.
The edges are cropped to the region of interest for the Hough transform.
The cv2.HoughLinesP() function is used to detect line segments in the cropped image that potentially represent the lane's edges.
If lines are detected, they're processed by the HoughBundler to merge them into longer segments representing the full extent of the lane lines.
The merged lines are drawn onto the original frame with a green color.
The modified original frame and the cropped edges image are shown in separate windows.
The script waits for a key press; if Esc (key == 27) is pressed, the video and windows are closed.
There are some placeholder commented-out lines (# lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50, maxLineGap=50)) that don't affect the script and can be removed for clarity.
Before running this code, you should ensure that the video "road_car_view.mp4" exists in the same directory as your script or provide the correct path. Additionally, make sure that OpenCV (cv2) and NumPy (np) have been installed in your Python environment.
If you encounter any specific questions or issues while running the code, please feel free to ask for help!
Here is how you can modify the code to include white line detection:
After obtaining the yellow mask (mask = cv2.inRange(hsv, low_yellow, up_yellow)), create a mask to detect white lines by using appropriate thresholds for white color in the same HSV color space or in the original BGR color space.
Combine the masks for yellow and white using the cv2.bitwise_or function.
Continue with edge detection, line detection, and processing using the combined mask.
Here is the modified code section within the while loop that includes white line detection:
python
# Existing code for yellow detection
low_yellow = np.array([18, 94, 140])
up_yellow = np.array([48, 255, 255])
yellow_mask = cv2.inRange(hsv, low_yellow, up_yellow)
# New code for white detection
# You may need to adjust the lower and upper thresholds for white depending on the video
low_white = np.array([0, 0, 168])
up_white = np.array([172, 111, 255])
white_mask = cv2.inRange(frame, low_white, up_white)
# Combine the two masks
mask = cv2.bitwise_or(yellow_mask, white_mask)
# Continue with edge detection on the combined mask
edges = cv2.Canny(mask, 75, 150)
# Apply region of interest masking on the edges
cropped_image = region_of_interest(edges)
# Perform Hough Transform line detection as before
lines = cv2.HoughLinesP(cropped_image, 1, np.pi / 180, 50, maxLineGap=50)
Please note that for white color detection in the RGB or BGR color space, high values for each channel are often indicative of white. However, the exact thresholds for white may vary depending on the lighting conditions and quality of the video. You may need to experiment with different threshold values to achieve the best results for your specific video.
Once you have added the code for white line detection as shown above, the rest of the processing will remain the same. The script will now detect both yellow and white lines and draw them on the road as it did previously. Make sure to test the new code and adjust the white color thresholds if necessary to improve detection accuracy.
Certainly! Here's the updated version of the code with white line detection included:
python
import cv2
import numpy as np
import math
# ... (The HoughBundler class definition remains the same)
# Function to apply a mask within a specified region of interest
def region_of_interest(image):
height = image.shape[0]
polygons = np.array([
[(200, height), (1000, height), (700, 400), (500, 400)]
])
mask = np.zeros_like(image)
cv2.fillPoly(mask, polygons, 255)
masked_image = cv2.bitwise_and(image, mask)
return masked_image
# Load the video
video = cv2.VideoCapture("road_car_view.mp4")
# Process video frames
while video.isOpened():
ret, orig_frame = video.read()
if not ret:
video = cv2.VideoCapture("road_car_view.mp4")
continue
frame = cv2.GaussianBlur(orig_frame, (5, 5), 0)
# Convert frame to HSV color space
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Create mask for yellow color
low_yellow = np.array([18, 94, 140])
up_yellow = np.array([48, 255, 255])
yellow_mask = cv2.inRange(hsv, low_yellow, up_yellow)
# Create mask for white color (tuned for the BGR color space)
low_white = np.array([0, 0, 168])
up_white = np.array([172, 111, 255])
white_mask = cv2.inRange(frame, low_white, up_white)
# Combine yellow and white masks
mask = cv2.bitwise_or(yellow_mask, white_mask)
# Apply Canny edge detection
edges = cv2.Canny(mask, 75, 150)
# Crop edges to region of interest
cropped_image = region_of_interest(edges)
# Detect lines using Hough Transform
lines = cv2.HoughLinesP(cropped_image, 1, np.pi / 180, 50, maxLineGap=50)
# Merge and process lines
if lines is not None:
bundler = HoughBundler()
merged_lines = bundler.process_lines(lines, edges)
# Draw merged lines on the original frame
for line in merged_lines:
x1, y1 = map(int, line[0])
x2, y2 = map(int, line[1])
cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 0), 5)
# Display frames
cv2.imshow("frame", frame)
cv2.imshow("cropped_image", cropped_image)
# Check for Esc key press to exit
key = cv2.waitKey(1)
if key == 27:
break
# Release video and destroy windows
video.release()
cv2.destroyAllWindows()
The adjustments include the detection of white lines in addition to yellow lines by creating two separate masks for yellow and white colors and then combining them. The merged mask is used further for edge detection and the rest of the processing.
Ensure that the video "road_car_view.mp4" is available in your working directory or change the path to the correct location of the file. Also, make sure to adjust the color thresholds for white detection as lighting conditions in your video might be different.
To detect the white lines more robustly, we can use different color space thresholds and combine them if necessary. One common method is to look at the grayscale image directly because white lines will usually stand out due to their brightness. We'll add this to the original mask that was designed to detect yellow lines.
Here's the updated code that includes the grayscale-based white line detection:
python
import cv2
import numpy as np
import math
# ... (The HoughBundler class definition remains the same)
def region_of_interest(image):
# ... (This function remains the same)
# Load the video
video = cv2.VideoCapture("road_car_view.mp4")
# Process video frames
while video.isOpened():
ret, orig_frame = video.read()
if not ret:
video = cv2.VideoCapture("road_car_view.mp4")
continue
frame = cv2.GaussianBlur(orig_frame, (5, 5), 0)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Create a mask for yellow lines
low_yellow = np.array([18, 94, 140])
up_yellow = np.array([48, 255, 255])
yellow_mask = cv2.inRange(hsv, low_yellow, up_yellow)
# Create a mask for white lines based on the grayscale image
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, white_mask = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
# Combine yellow and white masks
mask = cv2.bitwise_or(yellow_mask, white_mask)
# Apply Canny edge detection
edges = cv2.Canny(mask, 75, 150)
cropped_image = region_of_interest(edges)
# Detect lines using Hough Transform
lines = cv2.HoughLinesP(cropped_image, 1, np.pi / 180, 50, maxLineGap=50)
# Merge and process lines
if lines is not None:
bundler = HoughBundler()
merged_lines = bundler.process_lines(lines, edges)
# Draw merged lines on the original frame
for line in merged_lines:
x1, y1 = map(int, line[0])
x2, y2 = map(int, line[1])
cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 0), 5)
# Display frames
cv2.imshow("frame", frame)
cv2.imshow("edges", edges)
# Check for Esc key press to exit
key = cv2.waitKey(1)
if key == 27:
break
# Release video and destroy windows
video.release()
cv2.destroyAllWindows()
These lines convert the blurred frame to grayscale and then use a threshold to create a binary mask where the pixels that are likely to be white (high intensity) are set to 255 (white) and all others are set to 0 (black). Note that the threshold value 200 may need to be adjusted based on the actual brightness of the white lines in your video.
This new white_mask is then combined with the yellow_mask to get a final mask where both yellow and white lines are included. The Canny edge detector and the Hough line transform will then work on this combined mask.
Make sure that the lighting conditions of your video are not washed out or underexposed; otherwise, the threshold may need fine-tuning. Additionally, ensure the road's region of interest is correctly specified in the region_of_interest function.
The error you're encountering suggests that there is a problem with the types or contents of yellow_mask and white_mask when you're trying to combine them with cv2.bitwise_or.
One possible issue could be that the shapes or data types of yellow_mask and white_mask are not the same. Both masks should be the same shape and should ideally be of type unsigned 8-bit integer (np.uint8).
Let's verify that both masks have the same dimensions and correct them if necessary, by adding a check before combining them:
python
# Ensure the white_mask and yellow_mask are of the same size and type
if yellow_mask.shape == white_mask.shape and yellow_mask.dtype == white_mask.dtype:
# Combine yellow and white masks
mask = cv2.bitwise_or(yellow_mask, white_mask)
else:
raise ValueError("The shape or dtype of yellow_mask and white_mask do not match")
If the masks don't match, an error will be raised, helping you to diagnose the problem.
Additionally, make sure that the cv2.threshold function, which creates white_mask, indeed returns a binary image with the same size as the original frame. The error src2 is not a numerical tuple indicates that the second argument white_mask may somehow not be correct. It's essential that the variable white_mask is assigned from the cv2.threshold correctly, like so:
Check the shapes of both masks using print statements for debugging:
python
print(yellow_mask.shape, yellow_mask.dtype) # Should output something like (height, width) uint8
print(white_mask.shape, white_mask.dtype) # Should output something like (height, width) uint8
Here's a possible fix by ensuring that both masks are the same size and type using the cv2.cvtColor utility function:
python
# Use a range of thresholds for white color in grayscale
low_white = 200
high_white = 255
# Detect white lines by thresholding the grayscale image
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, white_mask = cv2.threshold(gray, low_white, high_white, cv2.THRESH_BINARY)
# Ensure `white_mask` has the same number of channels as `yellow_mask`
white_mask = cv2.cvtColor(white_mask, cv2.COLOR_GRAY2BGR)
# Combine the yellow and white masks
mask = cv2.bitwise_or(yellow_mask, white_mask)
# Convert combined mask back to single channel for edge detection
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
# Do Canny edge detection
edges = cv2.Canny(mask, 75, 150)
Now, white_mask is converted to a 3-channel image so it can be bitwise OR-ed with yellow_mask, which is already a 3-channel image if using cv2.bitwise_or without errors. Once that's done, you can convert it back into grayscale for edge detection.
Ensure all the modifications fit into your existing code where appropriate, and this should address the problem!