程序在运行过程中会缺少一些步骤,是我延迟给的少了吗?希望大家指出我的问题,应该要像图中那样,输出一个图片加上它的转弯判定再进入下一张图片,但是现在他有的时候会跳过判定,如图,编码如下:
# -*- coding: UTF-8 -*-
import os,random,shutil,cv2,glob
import numpy as np
def copyfile(file,tar):
path=os.listdir(file) #找路径
num=20 #抽取数量
sample=random.sample(path,num)
for name in sample:
shutil.copy(file+name,tar+name)
def handle(tu):
if True:
#图片灰度化
tu_grey=cv2.cvtColor(tu,cv2.COLOR_BGR2GRAY)
#大津法二值化
retval,er=cv2.threshold(tu_grey,0,255,cv2.THRESH_OTSU)
#膨胀
er=cv2.dilate(er,None,iterations=2)
#腐蚀
er=cv2.erode(er,None,iterations=6)
#窗口自适应大小
cv2.namedWindow('er_grey',cv2.WINDOW_FREERATIO)
#展示图片
cv2.imshow('er_grey',er)
#取出途中第400行的像素值
line_400=er[400]
line_100=er[100]
#开始寻找黑线中心点
try:
#查看黑色总个数用作偏移量计数
count1=np.sum(line_400==0)
count2=np.sum(line_100==0)
#查找黑色像素点的偏移量
index1=np.where(line_400==0)
index2=np.where(line_100==0)
#个数不能为0,防止报错
if count1==0:
count1=1
if count2==0:
count2=1
#用二分法找到黑线一行上的中心像素点
center1=(index1[0][count1-1]+index1[0][0])/2
center2=(index2[0][count2-1]+index2[0][0])/2
#计算偏移
dire=center2-center1
#判断方向
if dire>0:
print('右转')
if dire<0:
print('左转')
if dire==0:
print('直行')
except:
pass
#延迟3秒
cv2.waitKey(3000)
#销毁当前窗口
cv2.destroyWindow('er_grey')
#读取依次读取抽样文件夹下的内容
def bianli(file_path):
#读取图片位置
images_path=glob.glob(os.path.join(file_path+'*.png'))
#遍历图片位置信息
for i in images_path:
print(i)
tu=cv2.imread(i)
handle(tu)
cv2.waitKey(2000)
#主函数
if __name__=='__main__':
#给出图源路径
file='D:/pingan/shiyan1/guidao/'
#图应该复制到的路径文件夹
tar='D:/pingan/shiyan1/chouyang/'
copyfile(file,tar)
cv2.waitKey(5000)
#抽样的图片内容位置
file_path='D:/pingan/shiyan1/chouyang/'
bianli(file_path)
补充一下报错信息,是try函数的
index 0 is out of bounds for axis 0 with size 0