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

运行结果



相关推荐
风象南7 小时前
普通人用AI加持赚到的第一个100块
人工智能·后端
牛奶8 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶8 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
罗西的思考11 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
冬奇Lab11 小时前
OpenClaw 源码精读(2):Channel & Routing——一条消息如何找到它的 Agent?
人工智能·开源·源码阅读
冬奇Lab11 小时前
一天一个开源项目(第38篇):Claude Code Telegram - 用 Telegram 远程用 Claude Code,随时随地聊项目
人工智能·开源·资讯
孟健12 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
格砸13 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
可观测性用观测云13 小时前
可观测性 4.0:教系统如何思考
人工智能
sunny86513 小时前
Claude Code 跨会话上下文恢复:从 8 次纠正到 0 次的工程实践
人工智能·开源·github