python 이미지 외부 경계 추적 작업 실현

share 일부 python 구현 코드

#!/usr/bin/env python
#coding=utf-8
 
import cv2
 
img = cv2.imread("trace_border2.bmp")
[img_h, img_w, img_channel] = img.shape
 
trace = []
start_x = 0
start_y = 0
 
gray = img[:,:,1]
for h in range(img_h):
  for w in range(img_w):
    if (gray[h,w] > 128):
      gray[h,w] = 255
    else:
      gray[h,w] = 0
 
#python       
#https://www.cnblogs.com/xiaojiayu/p/5195316.html
class getoutofloop(Exception): pass
try:
  for h in range(img_h - 2):
    for w in range(img_w - 2):
      if gray[h,w] == 0:
        start_x = w
        start_y = h
        raise getoutofloop
except getoutofloop:
  pass
 
print("Start Point (%d %d)"%(start_x, start_y))
trace.append([start_x, start_y])
 
# 8          
neighbor = [[-1,-1],[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0]]
neighbor_len = len(neighbor)
 
#           ,
#          (   ):
#              90 i-=2
#   :
#              45 i+=1
i = 0
cur_x = start_x + neighbor[i][0]
cur_y = start_y + neighbor[i][1]
 
is_contour_point = 0
 
try:
  while not ((cur_x == start_x) and (cur_y == start_y)):
    is_contour_point = 0
    while is_contour_point == 0:
      #neighbor_x = cur_x +
      if gray[cur_y, cur_x] == 0:
        is_contour_point = 1
        trace.append([cur_x, cur_y])
        i -= 2
        if i < 0:
          i += neighbor_len
      else:
        i += 1
        if i >= neighbor_len:
          i -= neighbor_len
      #print(i)
      cur_x = cur_x + neighbor[i][0]
      cur_y = cur_y + neighbor[i][1]
except:
  print("throw error")
 
for i in range(len(trace)-1):
  cv2.line(img,(trace[i][0],trace[i][1]), (trace[i+1][0], trace[i+1][1]),(0,0,255),3)
  cv2.imshow("img", img)
  cv2.waitKey(10)
 
cv2.rectangle(img,(start_x, start_y),(start_x + 20, start_y + 20),(255,0,0),2)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyWindow("img")
검색 과정 에서 빨간색 표시 선 은 다음 과 같 습 니 다.

추가 지식:python 목표 추적 실현(opencv)
1.단일 목표 추적

import cv2
import sys
 
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
print(major_ver, minor_ver, subminor_ver)
 
if __name__ == '__main__':
  #      
  tracker_type = 'MIL'
  tracker = cv2.TrackerMIL_create()
  #     
  video = cv2.VideoCapture("./data/1.mp4")
  #      
  ok, frame = video.read()
  if not ok:
    print('Cannot read video file')
    sys.exit()
  #     bounding box
  bbox = (287, 23, 86, 320)
  bbox = cv2.selectROI(frame, False)
  #        
  ok = tracker.init(frame, bbox)
 
  while True:
    ok, frame = video.read()
    if not ok:
      break
    # Start timer
    timer = cv2.getTickCount()
    # Update tracker
    ok, bbox = tracker.update(frame)
    # Cakculate FPS
    fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
    # Draw bonding box
    if ok:
      p1 = (int(bbox[0]), int(bbox[1]))
      p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
      cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
    else:
      cv2.putText(frame, "Tracking failed detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
    #   tracker  
    cv2.putText(frame, tracker_type+"Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
    #   FPS
    cv2.putText(frame, "FPS:"+str(fps), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
    # Result
    cv2.imshow("Tracking", frame)
 
    # Exit
    k = cv2.waitKey(1) & 0xff
    if k ==27 : break
2.다목 적 추적
GOTURN 을 추적 기로 사용 할 때 는 goturn.cafemodel 과 goturn.prototxt 를 작업 디 렉 터 리 에 넣 어야 실행 할 수 있 습 니 다.문제 해결 링크https://stackoverflow.com/questions/48802603/getting-deep-learning-tracker-goturn-to-run-opencv-python

import cv2
import sys
 
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
print(major_ver, minor_ver, subminor_ver)
 
if __name__ == '__main__':
  #      
  # 'BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE'
  tracker_type = 'MIL'
  tracker = cv2.MultiTracker_create()
  #     
  cv2.namedWindow("Tracking")
  #     
  video = cv2.VideoCapture("./data/1.mp4")
  #      
  ok, frame = video.read()
  if not ok:
    print('Cannot read video file')
    sys.exit()
  #     bounding box
  box1 = cv2.selectROI("Tracking", frame)
  box2 = cv2.selectROI("Tracking", frame)
  box3 = cv2.selectROI("Tracking", frame)
  #        
  ok = tracker.add(cv2.TrackerMIL_create(), frame, box1)
  ok1 = tracker.add(cv2.TrackerMIL_create(), frame, box2)
  ok2 = tracker.add(cv2.TrackerMIL_create(), frame, box3)
  while True:
    ok, frame = video.read()
    if not ok:
      break
    # Start timer
    timer = cv2.getTickCount()
    # Update tracker
    ok, boxes = tracker.update(frame)
    print(ok, boxes)
    # Cakculate FPS
    fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
    for box in boxes:
      # Draw bonding box
      if ok:
        p1 = (int(box[0]), int(box[1]))
        p2 = (int(box[0] + box[2]), int(box[1] + box[3]))
        cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)
      else:
        cv2.putText(frame, "Tracking failed detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255),2)
    #   tracker  
    cv2.putText(frame, tracker_type+"Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
    #   FPS
    cv2.putText(frame, "FPS:"+str(fps), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
    # Result
    cv2.imshow("Tracking", frame)
 
    # Exit
    k = cv2.waitKey(1) & 0xff
    if k ==27 : break
이상 의 python 이 이미지 외부 경계 추적 작업 을 실현 하 는 것 은 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 께 참고 가 되 고 저 희 를 많이 사랑 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기