5649浏览
查看: 5649|回复: 0

[教程] 【Mind+python】追光

[复制链接]

【Mind+python】追光图1【追光】

在Mind+Python模式中检测图像中灯光亮点(图像中最亮点)的教程

【Mind+python】追光图2
【python代码】
已注释的比较详细。
  1. from imutils import contours
  2. from skimage import measure#安装scikit-image库
  3. import numpy as np
  4. import argparse
  5. import imutils
  6. import cv2
  7. cap = cv2.VideoCapture(0)
  8. while True:
  9.    ret, img = cap.read()
  10.    # 生成灰度图,提高检测效率  
  11.    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  12.    #gray = cv2.resize(gray,(320,240))
  13.    #平滑滤波
  14.    blurred = cv2.GaussianBlur(gray, (11, 11), 0)
  15.    #阈值化处理,为了显示模糊图像中最亮的区域,将像素值p >= 200,设置为255(白色),像素值< 200,设置为0(黑色)
  16.    thresh = cv2.threshold(blurred, 240, 255, cv2.THRESH_BINARY)[1]
  17.    #图像中存在噪声(小斑点),所以需要通过腐蚀和膨胀操作来清除
  18.    thresh = cv2.erode(thresh, None, iterations=2)
  19.    thresh = cv2.dilate(thresh, None, iterations=4)
  20.    # 对阈值图像执行连接组件分析,然后初始化遮罩以仅存储“大”组件
  21.    labels = measure.label(thresh, connectivity =2, background=0)
  22.    mask = np.zeros(thresh.shape, dtype="uint8")
  23.    # 开始循环遍历每个label中的正整数标签
  24.    for label in np.unique(labels):
  25.   # 如果标签为零,则表示正在检测背景并可以安全的忽略它否则,为当前区域构建一个掩码。
  26.     if label == 0:
  27.      continue
  28.   # 否则,构建标签掩码并计算像素数
  29.     labelMask = np.zeros(thresh.shape, dtype="uint8")
  30.     labelMask[labels == label] = 255
  31.     numPixels = cv2.countNonZero(labelMask)
  32.   #对labelMask中的非零像素进行计数。如果numPixels超过了一个预先定义的阈值(在本例中,总数为300像素),那么认为这个斑点“足够大”,并将其添加到掩膜中。
  33.     if numPixels > 300:
  34.       mask = cv2.add(mask, labelMask)
  35.    #在遮罩中找到轮廓,然后从左到右排序
  36.    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,  cv2.CHAIN_APPROX_SIMPLE)
  37.    cnts = imutils.grab_contours(cnts)
  38.    if len(cnts)>0:
  39.      cnts = contours.sort_contours(cnts)[0]
  40.      #在轮廓上打圈
  41.      maxwh=0
  42.      for (i, c) in enumerate(cnts):
  43.      #在图像上画出亮点
  44.        (x, y, w, h) = cv2.boundingRect(c)
  45.        if w*h>maxwh:
  46.         maxwh=w*h
  47.         cmax=c
  48.      ((cX, cY), radius) = cv2.minEnclosingCircle(cmax)
  49.      cv2.circle(img, (int(cX), int(cY)), int(radius),(0, 0, 255), 3)
  50.      #cv2.putText(img, "#{}".format(i + 1), (x, y - 15),cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
  51.    cv2.imshow('video',img)
  52.    k = cv2.waitKey(30) & 0xff
  53.    if k == 27: # press 'ESC' to quit
  54.         break
  55. cap.release()
  56. cv2.destroyAllWindows()
复制代码




您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail