python实现寻迹功能
生活随笔
收集整理的這篇文章主要介紹了
python实现寻迹功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python 使用CV2庫 實現尋跡功能
參考博客:https://blog.csdn.net/yzy_1996/article/details/85318179#commentsedit
"""使用python實現:尋跡的功能背景:可以用于小車的尋跡功能,賽道是白色部分,其余是黑色參考文獻:https://blog.csdn.net/yzy_1996/article/details/85318179#commentsedit返回值:停車 0, 右轉 1, 左轉 -1 """ import cv2 import numpy as npdef change_direct(temp):"""改變方向函數"""if temp > 250:print("停車")return 0elif temp > 0:print("右轉")return 1else:print("左轉")return -1def trace_fun():"""尋跡函數:保持"""cap = cv2.VideoCapture(1)result = Nonewhile(cap.isOpened()):# Capture frame-by-frame ret, frame = cap.read()# 真實圖# cv2.imshow('real_img', frame)# 轉化為灰度圖gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# cv2.imshow("gray_img", gray)# 大津法二值化retval, dst = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)# cv2.imshow("dst_img", dst)# 單單看第240行的像素color = dst[400]# 找到白色的像素點個數white_count = np.sum(color == 255)# 找到白色的像素點索引white_index = np.where(color == 255)# 防止white_count=0的報錯if white_count == 0:continue# 找到白色像素的中心點位置center = (white_index[0][white_count - 1] + white_index[0][0]) / 2# 計算出center與標準中心點的偏移量,因為攝像頭的像素為:480x640,寬度的一半direction = center - 320# 畫線 圖像,起點坐標,終點坐標,線的顏色, 線的大小cv2.line(frame, (320, 120), (320, 350), (0, 255, 0), 1, 4)cv2.line(frame, (300, 200), (300, 280), (0, 255, 0), 1, 4)cv2.line(frame, (340, 200), (340, 280), (0, 255, 0), 1, 4)print(direction)cv2.line(frame, (int(center), 200), (int(center), 280), (0, 0, 255), 1, 4)# 添加文字 圖像,文字內容, 坐標 ,字體,大小,顏色,字體厚度cv2.putText(frame, 'distance:%s' % direction, (int(center)-40, 220), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)cv2.imshow("frame", frame)# 判斷方向的下一步操作result = change_direct(direction)if cv2.waitKey(1) & 0xFF == ord('q'):breakcap.release()cv2.destroyAllWindows()if __name__ == '__main__':trace_fun()效果:
總結
以上是生活随笔為你收集整理的python实现寻迹功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux的 ls 和 ll 的使用发放
- 下一篇: 网络爬虫设计中需要注意的几个问题