日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

基于OpenCV的车辆计数(二)

發布時間:2024/3/24 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于OpenCV的车辆计数(二) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

代碼全部

圖像上的這個綠色面具是出口區,是我們計算車輛的地方。例如,我們只計算長度大于3個點的路徑(去除一些噪聲)和綠色區域中的第四個路徑。
我們使用掩碼的原因是它的許多操作比矢量算法有效和簡單。只需使用“二進制”和“操作”來檢查該區域中的那個點,就可以了。下面是我們如何設置:

EXIT_PTS = np.array([[[732, 720], [732, 590], [1280, 500], [1280, 720]],[[0, 400], [645, 400], [645, 0], [0, 0]] ])base = np.zeros(SHAPE + (3,), dtype='uint8') exit_mask = cv2.fillPoly(base, EXIT_PTS, (255, 255, 255))[:, :, 0]

連接點:

new_pathes = []for path in self.pathes:_min = 999999_match = Nonefor p in points:if len(path) == 1:# distance from last point to currentd = utils.distance(p[0], path[-1][0])else:# based on 2 prev points predict next point and calculate# distance from predicted next point to currentxn = 2 * path[-1][0][0] - path[-2][0][0]yn = 2 * path[-1][0][1] - path[-2][0][1]d = utils.distance(p[0], (xn, yn),x_weight=self.x_weight,y_weight=self.y_weight)if d < _min:_min = d_match = pif _match and _min <= self.max_dst:points.remove(_match)path.append(_match)new_pathes.append(path)# do not drop path if current frame has no matchesif _match is None:new_pathes.append(path)self.pathes = new_pathes# add new pathes if len(points):for p in points:# do not add points that already should be countedif self.check_exit(p[1]):continueself.pathes.append([p])# save only last N points in path for i, _ in enumerate(self.pathes):self.pathes[i] = self.pathes[i][self.path_size * -1:]

在第一幀上。我們只是把所有的點作為新的路徑。
接下來,如果len(path) == 1,對于高速緩存中的每個路徑,我們試圖從新檢測的對象中找到點(質心),該對象將具有最小的歐幾里得距離到路徑的最后一點。
如果len(path) >1,則在路徑中的最后兩點,我們在同一行上預測新點,并且在它與當前點之間找到最小距離。
具有最小距離的點添加到當前路徑的末尾并從列表中移除。
如果在此之后留下一些點,我們將它們作為新路徑添加。
我們也限制了路徑中的點的數量。

# count vehicles and drop counted pathes: new_pathes = [] for i, path in enumerate(self.pathes):d = path[-2:]if (# need at list two points to countlen(d) >= 2 and# prev point not in exit zonenot self.check_exit(d[0][1]) and# current point in exit zoneself.check_exit(d[1][1]) and# path len is bigger then minself.path_size <= len(path)):self.vehicle_count += 1else:# prevent linking with path that already in exit zoneadd = Truefor p in path:if self.check_exit(p[1]):add = Falsebreakif add:new_pathes.append(path)self.pathes = new_pathescontext['pathes'] = self.pathes context['objects'] = objects context['vehicle_count'] = self.vehicle_countself.log.debug('#VEHICLES FOUND: %s' % self.vehicle_count)return context

現在,我們將嘗試計數進入出口區的車輛。為此,我們只需在路徑中取最后2個點,并檢查它們在退出區域中的最后一個點,以及前面的NOT,也檢查LeN(PATH)應該大于限制。
后面的部分是防止將新的點連接到出口區域中的點。
最后兩個處理器是CSV編寫器,生成報表CSV文件,并進行可視化調試,畫面美觀。

class CsvWriter(PipelineProcessor):def __init__(self, path, name, start_time=0, fps=15):super(CsvWriter, self).__init__()self.fp = open(os.path.join(path, name), 'w')self.writer = csv.DictWriter(self.fp, fieldnames=['time', 'vehicles'])self.writer.writeheader()self.start_time = start_timeself.fps = fpsself.path = pathself.name = nameself.prev = Nonedef __call__(self, context):frame_number = context['frame_number']count = _count = context['vehicle_count']if self.prev:_count = count - self.prevtime = ((self.start_time + int(frame_number / self.fps)) * 100 + int(100.0 / self.fps) * (frame_number % self.fps))self.writer.writerow({'time': time, 'vehicles': _count})self.prev = countreturn contextclass Visualizer(PipelineProcessor):def __init__(self, save_image=True, image_dir='images'):super(Visualizer, self).__init__()self.save_image = save_imageself.image_dir = image_dirdef check_exit(self, point, exit_masks=[]):for exit_mask in exit_masks:if exit_mask[point[1]][point[0]] == 255:return Truereturn Falsedef draw_pathes(self, img, pathes):if not img.any():returnfor i, path in enumerate(pathes):path = np.array(path)[:, 1].tolist()for point in path:cv2.circle(img, point, 2, CAR_COLOURS[0], -1)cv2.polylines(img, [np.int32(path)], False, CAR_COLOURS[0], 1)return imgdef draw_boxes(self, img, pathes, exit_masks=[]):for (i, match) in enumerate(pathes):contour, centroid = match[-1][:2]if self.check_exit(centroid, exit_masks):continuex, y, w, h = contourcv2.rectangle(img, (x, y), (x + w - 1, y + h - 1),BOUNDING_BOX_COLOUR, 1)cv2.circle(img, centroid, 2, CENTROID_COLOUR, -1)return imgdef draw_ui(self, img, vehicle_count, exit_masks=[]):# this just add green mask with opacity to the imagefor exit_mask in exit_masks:_img = np.zeros(img.shape, img.dtype)_img[:, :] = EXIT_COLORmask = cv2.bitwise_and(_img, _img, mask=exit_mask)cv2.addWeighted(mask, 1, img, 1, 0, img)# drawing top block with countscv2.rectangle(img, (0, 0), (img.shape[1], 50), (0, 0, 0), cv2.FILLED)cv2.putText(img, ("Vehicles passed: {total} ".format(total=vehicle_count)), (30, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 1)return imgdef __call__(self, context):frame = context['frame'].copy()frame_number = context['frame_number']pathes = context['pathes']exit_masks = context['exit_masks']vehicle_count = context['vehicle_count']frame = self.draw_ui(frame, vehicle_count, exit_masks)frame = self.draw_pathes(frame, pathes)frame = self.draw_boxes(frame, pathes, exit_masks)utils.save_frame(frame, self.image_dir +"/processed_%04d.png" % frame_number)return context

?

總結

以上是生活随笔為你收集整理的基于OpenCV的车辆计数(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。