基于python-opencv实时识别黑线并返回黑线中心位置(一)

import cv2
import numpy as np
# center定义
center = 320

# 打开摄像头,图像尺寸640*480(长*高),opencv存储值为480*640(行*列)
cap = cv2.VideoCapture(0)
while (1):
    ret, frame = cap.read()
    # 转化为灰度图
    if ret == False:  # 如果是最后一帧这个值为False
       break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 大津法二值化
    retval, dst = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
    # 膨胀,白区域变大
    dst = cv2.dilate(dst, None, iterations=2)
    # # 腐蚀,白区域变小
    # dst = cv2.erode(dst, None, iterations=6)
    cv2.imshow("dst",dst)
    # 单看第400行的像素值
    color = dst[400]
    # 找到白色的像素点个数
    white_count = np.sum(color == 0)
    # 找到白色的像素点索引
    white_count_judge = np.sum(color == 255)#利用这个变量来查找摄像头是否观察到黑色
    if white_count_judge == 640:
        print("黑色像素点为0")
        pass
    else:
        white_index = np.where(color == 0)
        # 防止white_count=0的报错
        if white_count == 0:
            white_count = 1

        # 找到白色像素的中心点位置
        center = (white_index[0][white_count - 1] + white_index[0][0]) / 2
        direction = center - 320
        print(direction)
        # 计算出center与标准中心点的偏移量
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放清理
cap.release()
cv2.destroyAllWindows()


本代码适用于循下图所示的赛道,也就是单轨道黑线

声明:本代码为树莓派Opencv小车循迹专用,进阶版本代码可以看我这篇博客

电赛总结之上位机(树莓派python-opencv实时识别黑线)_孙启尧的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/weixin_51651698/article/details/126150109