Question: Please run this code on python and give me output of it i couldnt managed that Code:import cv 2 import numpy as np # Define

Please run this code on python and give me output of it i couldnt managed that
Code:import cv2
import numpy as np
# Define color ranges for segmentation (in HSV color space)
color_ranges ={
'red': [(0,70,50),(10,255,255),(170,70,50),(180,255,255)], # Red has two ranges in HSV
'yellow': [(20,100,100),(30,255,255)]
}
def color_segmentation(frame):
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = np.zeros(hsv.shape[:2], dtype=np.uint8)
for color, ranges in color_ranges.items():
for i in range(0, len(ranges),2):
mask += cv2.inRange(hsv, np.array(ranges[i]), np.array(ranges[i +1]))
return mask
#code for edge detection
def edge_detection(roi):
return cv2.Canny(roi,100,200)
# Load template images and convert them to grayscale
templates ={
'stop': cv2.imread('stop_template.jpg', cv2.IMREAD_GRAYSCALE),
'caution': cv2.imread('caution_template.jpg', cv2.IMREAD_GRAYSCALE)
}
#code for Task3: template matching
# Resize templates for scale invariance
for key in templates:
templates[key]= cv2.resize(templates[key],(50,50))
def template_matching(edges):
matches =[]
for label, template in templates.items():
res = cv2.matchTemplate(edges, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(res >=0.5) # Adjust threshold as needed
for pt in zip(*loc[::-1]):
matches.append((label, pt, res[pt[1], pt[0]]))
return matches
#code for Task4: shape analysis
def shape_analysis(contour):
approx = cv2.approxPolyDP(contour,0.02* cv2.arcLength(contour, True), True)
if len(approx)==8:
return 'stop'
elif len(approx)==4:
return 'caution'
return None
# Main code for real-time detection
def main():
cap = cv2.VideoCapture(0) # Capture video from the first camera
while True:
ret, frame = cap.read()
if not ret:
break
mask = color_segmentation(frame)
contours, _= cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
roi = frame[y:y+h, x:x+w]
edges = edge_detection(roi)
matches = template_matching(edges)
for label, pt, score in matches:
if shape_analysis(contour)== label:
cv2.rectangle(frame,(x, y),(x + w, y + h),(0,255,0),2)
cv2.putText(frame, label, (x, y -10), cv2.FONT_HERSHEY_SIMPLEX, 0.9,(36,255,12),2)
cv2.imshow('Traffic Sign Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__=="__main__":
main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!