# get file names of the framescol_frames = os.listdir('frames/') # sort file namescol_frames.sort(key=lambda f: int(re.sub('\D', '', f))) # empty list to store the framescol_images=[] for i in col_frames: # read the frames img = cv2.imread('frames/'+i) # append the frames to the list col_images.append(img)
数据探索
让我们显示两个连续的帧:
# plot 13th framei = 13 for frame in [i, i+1]: plt.imshow(cv2.cvtColor(col_images[frame], cv2.COLOR_BGR2RGB)) plt.title('frame: '+str(frame)) plt.show()
# kernel for image dilationkernel = np.ones((4,4),np.uint8) # font stylefont = cv2.FONT_HERSHEY_SIMPLEX # directory to save the ouput framespathIn = 'contour_frames_3/' for i in range(len(col_images)-1): # frame differencing grayA = cv2.cvtColor(col_images[i], cv2.COLOR_BGR2GRAY) grayB = cv2.cvtColor(col_images[i+1], cv2.COLOR_BGR2GRAY) diff_image = cv2.absdiff(grayB, grayA) # image thresholding ret, thresh = cv2.threshold(diff_image, 30, 255, cv2.THRESH_BINARY) # image dilation dilated = cv2.dilate(thresh,kernel,iterations = 1) # find contours contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) # shortlist contours appearing in the detection zone valid_cntrs = [] for cntr in contours: x,y,w,h = cv2.boundingRect(cntr) if (x <= 200) & (y >= 80) & (cv2.contourArea(cntr) >= 25): if (y >= 90) & (cv2.contourArea(cntr) < 40): break valid_cntrs.append(cntr) # add contours to original frames dmy = col_images[i].copy() cv2.drawContours(dmy, valid_cntrs, -1, (127,200,0), 2) cv2.putText(dmy, 'vehicles detected: ' + str(len(valid_cntrs)), (55, 15), font, 0.6, (0, 180, 0), 2) cv2.line(dmy, (0, 80),(256,80),(100, 255, 255)) cv2.imwrite(pathIn+str(i)+'.png',dmy)
准备视频
在这里,我们为所有帧中的所有移动车辆添加了轮廓。现在是时候堆叠帧并创建视频了:
# specify video namepathOut = 'vehicle_detection_v3.mp4' # specify frames per secondfps = 14.0
接下来,我们将阅读列表中的最后一帧:
frame_array = []files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]files.sort(key=lambda f: int(re.sub('\D', '', f)))
for i in range(len(files)): filename=pathIn + files[i] #read frames img = cv2.imread(filename) height, width, layers = img.shape size = (width,height) #inserting the frames into an image array frame_array.append(img)
最后,我们将使用以下代码制作目标检测视频:
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size) for i in range(len(frame_array)): # writing to a image array out.write(frame_array[i]) out.release()
恭喜你学会了车辆目标检测!
结尾
在本教程中,我们学习了如何使用帧差分技术在视频中执行移动目标检测,讨论了目标检测和图像处理的一些概念,然后用OpenCV建立了自己的运动目标检测系统。根据本文中学习的技术和方法,试试构建自己版本的目标检测系统吧!原文链接:https://www./blog/2020/04/vehicle-detection-opencv-python/ ☆ END ☆