Сохранить местоположения нескольких точек первого кадра - PullRequest
0 голосов
/ 27 апреля 2019

У меня есть видео о коровнике. Я хочу, чтобы углы контейнера с едой были посередине этого. Я пытался выполнить задачу в следующих шагах -

1. Freeze the video into the first frame (done using waitkey set to 0)
2. Pass the first frame into draw_circle function to get the corners
3. Play the video regularly after the first frame (done using changing waitkey value)

Однако я не могу достичь второй цели. Когда рамка замерзает, я нажимаю несколько точек, но список мыши по-прежнему пуст. Есть ли способ сделать это? Коды приведены ниже -

# import libraries
import cv2, numpy as np

# the point location will be saved into the mouse list
mouse = []

# define the function to get point location
def draw_circle(event,x,y,flags,param):
    global ix,iy
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),100,(255,0,0),-1)
        ix,iy = x,y
        mouse.append([x,y])

# waitKey to freeze the video into the first frame
waitKey = 0


cap = cv2.VideoCapture("L2_clip2_16s.m4v")
while(True):
    ret, frame = cap.read()
    if ret:
        cv2.imshow("res",frame)

        # the first frame will be freezed and go through the draw_circle function
        if waitKey ==0:
            cv2.setMouseCallback("imshow",draw_circle)

        key = cv2.waitKey(waitKey)

        # when done taking point - click c to assign the value to waitkey and play the video normally
        if key == ord("c"):
            waitKey = 1

        elif key== ord('q'):
            break
    else:
        break
cv2.destroyAllWindows()

print (mouse)

1 Ответ

0 голосов
/ 27 апреля 2019

Процесс выглядит следующим образом:
- создать новое окно
- прикрепить mouseCallback
- нарисовать кадры в этом окне
- при нажатии в окне вызывается функция draw_circle
- для обработки фрейма используйте переменную фрейма
- чтобы увидеть изменения, перерисовать фрейм

MouseCallback необходимо подключить только один раз.
Примечание: print (mouse) в вашем коденикогда не достигнуто из-за цикла while.

Я изменил ваш код, чтобы он работал.Я только оставил комментарии, где я изменил код.

import cv2, numpy as np

mouse = []

def draw_circle(event,x,y,flags,param):
    global ix,iy
    if event == cv2.EVENT_LBUTTONDBLCLK:
        # draw dot where double clicked
        cv2.circle(frame,(x,y),5,(0,0,255),-1)
        ix,iy = x,y
        mouse.append([x,y])
        # redraw frame to screen - with circle
        cv2.imshow("Video",frame)
        # print coordinates
        print (mouse)


waitKey = 0
# open a window named 'video'
cv2.namedWindow("Video")
# attach mouseCallback to the window named 'video'
cv2.setMouseCallback("Video",draw_circle)

cap = cv2.VideoCapture("L2_clip2_16s.m4v")
while(True):
    ret, frame = cap.read()
    if ret:
        # draw the frame in the window named 'Video'
        cv2.imshow("Video",frame)

        key = cv2.waitKey(waitKey)

        if key == ord("c"):
            waitKey = 1
        elif key== ord('q'):
            break
    else:
        break
cv2.destroyAllWindows()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...