1+ import cv2 as cv
2+ import numpy as np
3+
4+
5+ URL = "udp://<192.168.1.10>:8554"
6+
7+ cap = cv .VideoCapture (URL )
8+ while (True ):
9+ # Take each frame
10+ _ , frame = cap .read ()
11+ # Convert BGR to HSV
12+ hsv = cv .cvtColor (frame , cv .COLOR_BGR2HSV )
13+
14+ # define range of blue color in HSV
15+
16+ # upper and lower bounds for red color
17+ lower_red1 = np .array ([0 , 120 , 70 ])
18+ upper_red1 = np .array ([10 , 255 , 255 ])
19+
20+ lower_red2 = np .array ([170 , 120 , 70 ])
21+ upper_red2 = np .array ([180 , 255 , 255 ])
22+
23+ # upper and lower bounds for green color
24+ lower_green = np .array ([40 , 40 , 40 ])
25+ upper_green = np .array ([90 , 255 , 255 ])
26+
27+ # Threshold the HSV image to get only blue colors
28+
29+ # Create a red mask
30+ mask1 = cv .inRange (hsv , lower_red1 , upper_red1 )
31+ mask2 = cv .inRange (hsv , lower_red2 , upper_red2 )
32+
33+ # Bitwise-OR the masks
34+ maskRed = mask1 | mask2
35+
36+ # Create a green mask
37+ maskGreen = cv .inRange (hsv , lower_green , upper_green )
38+ #Bitwise-OR the masks
39+ mask = maskRed | maskGreen
40+
41+ # Bitwise-AND mask and original image
42+ res = cv .bitwise_and (frame ,frame , mask = mask )
43+
44+ # Find contours
45+ contours_green , _ = cv .findContours (maskGreen , cv .RETR_EXTERNAL , cv .CHAIN_APPROX_SIMPLE )
46+ contours_red , _ = cv .findContours (maskRed , cv .RETR_EXTERNAL , cv .CHAIN_APPROX_SIMPLE )
47+
48+ if contours_green and contours_red :
49+ # Assume the largest contour for each color is the wall
50+ green_contour = max (contours_green , key = cv .contourArea )
51+ red_contour = max (contours_red , key = cv .contourArea )
52+
53+ # Compute the centroids using image moments
54+ M_green = cv .moments (green_contour )
55+ M_red = cv .moments (red_contour )
56+
57+ if M_green ["m00" ] > 0 and M_red ["m00" ] > 0 :
58+ cx_green = int (M_green ["m10" ] / M_green ["m00" ])
59+ cx_red = int (M_red ["m10" ] / M_red ["m00" ])
60+
61+ # Check if the green (left wall) is to the left of the red (right wall)
62+ if cx_green < cx_red :
63+ print ("right direction" )
64+ else :
65+ print ("wrong direction" )
66+
67+
68+ # Show the images
69+ cv .imshow ('frame' ,frame )
70+ cv .imshow ('mask' ,mask )
71+ cv .imshow ('res' ,res )
72+
73+ # press q to close the window
74+ if cv .waitKey (5 ) & 0xFF == ord ('q' ):
75+ break
76+
77+ cap .release ()
78+ cv .destroyAllWindows ()
0 commit comments