Python轮廓追踪【OpenCV形态学操作】

文章目录

概要

一些理论知识

OpenCV形态学操作理论1
OpenCV形态学操作理论2
OpenCV轮廓操作|轮廓类似详解

代码

代码如下,可以直接运行

python 复制代码
import cv2 as cv

# 定义结构元素
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
# print kernel

capture = cv.VideoCapture(0)
print (capture.isOpened())
ok, frame = capture.read()
lower_b = (65, 43, 46)
upper_b = (110, 255, 255)

height, width = frame.shape[0:2]
screen_center = width / 2
offset = 50

while ok:
    # 将图像转成HSV颜色空间
    hsv_frame = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
    # 基于颜色的物体提取
    mask = cv.inRange(hsv_frame, lower_b, upper_b)
    mask2 = cv.morphologyEx(mask, cv.MORPH_OPEN, kernel)
    mask3 = cv.morphologyEx(mask2, cv.MORPH_CLOSE, kernel)

    # 找出面积最大的区域
    contours,_ = cv.findContours(mask3, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    maxArea = 0
    maxIndex = 0
    for i, c in enumerate(contours):
        area = cv.contourArea(c)
    if area > maxArea:
        maxArea = area
    maxIndex = i
    # 绘制
    cv.drawContours(frame, contours, maxIndex, (255, 255, 0), 2)
    # 获取外切矩形
    x, y, w, h = cv.boundingRect(contours[maxIndex])
    cv.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
    # 获取中心像素点
    center_x = int(x + w / 2)
    center_y = int(y + h / 2)
    cv.circle(frame, (center_x, center_y), 5, (0, 0, 255), -1)

    # 简单的打印反馈数据,之后补充运动控制
    if center_x < screen_center - offset:
        print ("turn left")
    elif screen_center - offset <= center_x <= screen_center + offset:
        print ("keep")
    elif center_x > screen_center + offset:
        print ("turn right")

    cv.imshow("mask4", mask3)
    cv.imshow("frame", frame)
    cv.waitKey(1)
    ok, frame = capture.read()

运行结果



相关推荐
东风破_1 小时前
《LangGraph Memory:为什么 Agent 需要 Checkpointer?》
人工智能
锋行天下1 小时前
LangGraph 同级节点之间修改数据先后问题
人工智能
2601_962078191 小时前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
u1301301 小时前
AI 日报(2026年9月12日)
人工智能
东风破_1 小时前
《LangGraph Human-in-the-loop:Interrupt 如何让 Agent 等待人工确认》
人工智能
2601_962218611 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_966949651 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
智塑未来1 小时前
中文短剧出海翻译工具横评:VMEG AI、鬼手、Vozo AI、ElevenLabs怎么选?
人工智能
东风破_1 小时前
《LangGraph 条件路由与循环:如何让 Agent 自己决定下一步?》
人工智能
我爱吃土豆11 小时前
AI 编程工具远程开发指南:Codex 桌面版与 WorkBuddy 通过 SSH 连接云服务器实践
服务器·人工智能·ssh