The below question gives an error for color detection(contours)

24 Views Asked by At
import cv2
import numpy as np

cap=cv2.VideoCapture(0)

position=90 #degrees

while True:
    ret,frame=cap.read()
    hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

    #red color-LOWER BOUNDS AND UPPER BOUNDS(INDICES)
    low_red=np.array([161,155,84])
    high_red=np.array([179,255,255])

    red_mask=cv2.inRange(hsv,low_red,high_red)
    #red-white , other colors outside range-black
    contours,_=cv2.findContours(red_mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    #RETR_TREE - RETRIEVES ALL NODES
    #CHAIN_APPROX_SIMPLE- returns only the endpoints of the contour. 
    contours=sorted(contours,key=lambda x:cv2.contourArea(x),reverse=True)

    for cnt in contours:
        (x,y,w,h)=cv2.boundingRect(cnt)

        #cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        x_medium=int((x+x+w)/2)
        break
    
    cv2.line(frame,(x_medium,0),(x_medium,480),(0,255,0),2)
    
    cv2.imshow("Frame",frame)
    #cv2.imshow("mask",red_mask)

    cv2.imshow("Frame",frame)

    if cv2.waitKey(1) & 0xFF == ord(" "):
        break

cap.release()
cv2.destroyAllWindows() 

This is a code for contour detection based on color of a object. I have a created a binary mask for a object that is in red color. My code is not running and it gives the following error:

>>> & C:/Users/admin/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/admin/Desktop/object detection/cam.py"   File "<stdin>", line 1
    & C:/Users/admin/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/admin/Desktop/object detection/cam.py"
    ^ SyntaxError: invalid syntax

I do not know what does this mean? Please help me out?

0

There are 0 best solutions below