You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于颜色的轮廓检测Python代码运行报错,寻求技术支持

问题排查:Python颜色检测代码运行语法错误

错误信息

>> & 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

涉事代码

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() 

错误原因与解决方法

核心错误原因

你在Python交互式解释器(>>>提示符)中直接输入了Windows终端的运行命令,Python解释器无法识别系统级命令,因此抛出语法错误。

解决步骤

  1. 退出当前Python交互窗口(输入exit()回车,或直接关闭窗口)。
  2. 打开Windows命令提示符(CMD)或PowerShell。
  3. 直接输入以下命令运行代码(无需加>>>和&):
    C:/Users/admin/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/admin/Desktop/object detection/cam.py"
    
    若已将Python添加到系统环境变量,可直接进入代码所在文件夹,输入更简洁的命令:
    python cam.py
    

代码潜在问题修复

原代码存在逻辑漏洞:当画面中无红色目标时,contours为空列表,x_medium变量未定义会触发NameError。可添加默认值规避:

# 在for循环前添加默认值
x_medium = 240  # 默认取画面中线位置
for cnt in contours:
    (x,y,w,h)=cv2.boundingRect(cnt)
    x_medium=int((x+x+w)/2)
    break

内容的提问来源于stack exchange,提问作者JEREMIAH RANEN RAJESH GEORGE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 02:30:03