python - 如何使用鼠标功能将复杂或不规则形状用作我的投资返回率,以进行图像检测和跟踪?

标签 python opencv image-processing object-detection

我目前正在尝试创建形状复杂/不规则的roi以进行检测和跟踪。但是无法创建它。

我可以使用鼠标回调函数围绕复杂形状绘制一条曲线,但是我不知道如何使用封闭曲线进行roi。

这是我正在处理的视频中的帧。

图片1

图片2

image2中的形状是我希望我的roi进行跟踪的区域。我不希望我的roi为矩形,因为它无法跟踪我的roi。 image2中的形状实际上是我要在视频中跟踪的对象。

以下是使用矩形roi进行跟踪的代码。

import cv2
import sys
from matplotlib import pyplot as plt

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')



# Set up tracker.
# Instead of MIL, you can also use

tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
tracker_type = tracker_types[1]


if tracker_type == 'BOOSTING':
    tracker = cv2.TrackerBoosting_create()
elif tracker_type == 'MIL':
    tracker = cv2.TrackerMIL_create()
elif tracker_type == 'KCF':
    tracker = cv2.TrackerKCF_create()
elif tracker_type == 'TLD':
    tracker = cv2.TrackerTLD_create()
elif tracker_type == 'MEDIANFLOW':
    tracker = cv2.TrackerMedianFlow_create()
elif tracker_type == 'GOTURN':
    tracker = cv2.TrackerGOTURN_create()
elif tracker_type == 'MOSSE':
    tracker = cv2.TrackerMOSSE_create()
elif tracker_type == "CSRT":
    tracker = cv2.TrackerCSRT_create()

# Read video
video = cv2.VideoCapture("3umresize4.avi")


# Exit if video not opened.
if not video.isOpened():
    print "Could not open video"
    sys.exit()

# Read first frame.
ok, frame = video.read()
if not ok:
    print 'Cannot read video file'
    sys.exit()

# Define an initial bounding box
bbox = (287, 23, 86, 320)

# Uncomment the line below to select a different bounding box
bbox = cv2.selectROI(frame, False)

# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)

while True:
    # Read a new frame
    ok, frame = video.read()
    if not ok:
        break

    # Start timer
    timer = cv2.getTickCount()

    # Update tracker
    ok, bbox = tracker.update(frame)

    # Calculate Frames per second (FPS)
    fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);

    # Draw bounding box
    if ok:
        # Tracking success
        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 :
        # Tracking failure
        cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

    # Display tracker type on frame
    cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);

    # Display FPS on frame
    cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);


    # Display result
    cv2.namedWindow("Tracking",cv2.WINDOW_NORMAL)
    cv2.imshow("Tracking", frame)

    # Exit if ESC pressed
    k = cv2.waitKey(1) & 0xff
    if k == 27 :

        break



cv2.destroyAllWindows()

下面是用于创建image2的鼠标回调,在该代码中,我希望轮廓下的区域成为上面代码中的roi。
import cv2
import numpy as np 

drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve

# mouse callback function
def drawcurve(event,former_x,former_y,flags,param):
    global current_former_x,current_former_y,drawing, mode


    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        current_former_x,current_former_y=former_x,former_y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
                current_former_x = former_x
                current_former_y = former_y
                #print former_x,former_y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
            current_former_x = former_x
            current_former_y = former_y
    return former_x,former_y    

im = cv2.imread("sampleuct.bmp")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',drawcurve)
while(1):
    cv2.imshow('Bill BEGUERADJ OpenCV',im)
    k=cv2.waitKey(1)&0xFF
    if k==27:
        break
cv2.destroyAllWindows()

您能帮我解决它吗,将我的投资返回率与跟踪结合起来。或其他任何我可以追踪的方式。

最佳答案

OpenCV的功能不会直接为您提供所需的东西,所有这些跟踪器都是专门用来做特定的事情的,这些事情最终会跟踪一个本地化的区域,即一个盒子。

由于要跟踪形状,可以考虑使用基于卡尔曼滤波器的跟踪,实际上是在跟踪点。您可以选择感兴趣的点,并在每一帧中将它们连接起来,并仅跟踪这些点。您可能也想自己实现一个。您可以将此link作为教程直接使用OpenCV的卡尔曼滤波器跟踪实现。

您还可以考虑通过使用语义网络(Semantic Networks)来基于深度学习的方法,在该框架中,在每个帧处分割感兴趣的区域。

一个肮脏的技巧是按原样创建roi,并且每次检测到盒子时,都可以根据需要将roi大小调整为盒子大小并使用它。

关于python - 如何使用鼠标功能将复杂或不规则形状用作我的投资返回率,以进行图像检测和跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398486/

相关文章:

python - django 'str' 对象没有属性 'get' 错误,for forms.py

Python - 如何修复 “ValueError: not enough values to unpack (expected 2, got 1)”

opencv - 理解 solvePnP 算法

c++ - OpenCV 错误 : Assertion Failed in MixChannels(.。)

python - 用python从数据库中读取图像

android - 位图 sameAs 如何工作?

python - 在 python 中使用\n 分隔的 JSON 发布请求

python - 传递多个参数以应用(Python)

c++ - OpenCV 错误 : Sizes of input arguments do not match (The operation is neither 'array op array' )

image-processing - 在 SIMD 中矢量化直方图的方法?