一、题目:
利用摄像头进行寻迹是常用的运动检测,如下图为小车跑道。请设计一个方案,能够检测出视野内(320*240)黑线偏离图像中心平均值(以中心为0,左为负值,右为正值,单位为像素)。(以某自定义静态图作为目标,如下)
二、本程序实现功能
三、建议及注意事项
四、文件夹目录
五、源代码:
Check.py包依赖
文件名:requirements.txt
numpy==1.19.5
opencv-python==3.4.1.15
Check.py
import cv2
import numpy as np
img1 = cv2.imread("Img\img1.jpg")
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)# 转化为灰度图
retval, dst = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)#二值化
dst = cv2.dilate(dst, None, iterations=2)# 膨胀,白区域变大
color = dst[120]# 单看第120行的像素值(图片长320,高240。用240/2)
black_count = np.sum(color == 0)#第120行像素中黑色的像素点个数
black_index = np.where(color == 0)#第120行像素中黑色的像素点的索引值,
center_now = (black_index[0][black_count - 1] + black_index[0][0]) / 2 #打印(black_index)就明白black_index[0][0]是什么了
#black_index[0][0]不就是第一个黑像素点的位置吗,假设5个黑像素点
#black_index[0][5-1]不就是最后一个黑像素点的位置吗
direction = center_now - 160 #减去长的一半,得到据中心的距离。 假如求点(0,6)(0,8)到x=4的距离,不就是(6+8)/2吗
print(direction)
cv2.waitKey(0)
cv2.destroyAllWindows()
六、源代码运行过程说明