Как реализовать обнаружение движения и отслеживание для обнаружения живого края на пи-камере - PullRequest
0 голосов
/ 05 марта 2019

В настоящее время я пытаюсь реализовать обнаружение и отслеживание движения в написанной мной программе обнаружения краев. Однако, когда я пытаюсь внедрить свой код в заранее написанный скелет для обнаружения и отслеживания движения с веб-сайта: https://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/,

Я получаю эту ошибку:

VIDEOIO ERROR: V4L2: Pixel format of incoming image is unsupported by OpenCV
Unable to stop the stream: Device or resource busy
Traceback (most recent call last):
  File "newedge.py", line 33, in <module>
    while(cap.isOpened()):
AttributeError: 'WebcamVideoStream' object has no attribute 'isOpened'

У меня следующий код для обнаружения острых кромок, который прекрасно работает:

Define the codec and create VideoWriter object
# Remember, you might need to change the XVID codec to something else (MPEG?)
#frame = cv2.Canny(frame,300,200)

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('triale.avi',fourcc, 30.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        frame = cv2.GaussianBlur(frame, (3, 3), 0)
        v = np.median(frame)
        sigma=0.15
        lower = int(max(0, (1.0 - sigma) * v))
        upper = int(min(255, (1.0 + sigma) * v))
        frame = cv2.Canny(frame,lower,upper)
        frame = np.expand_dims(frame, axis=-1)
        frame = np.concatenate((frame, frame, frame), axis=2)


        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

Однако я получаю вышеупомянутую ошибку, когда внедряю свой код в код с веб-сайта, и реализованный код выглядит следующим образом:

# import the necessary packages
from imutils.video import VideoStream
import argparse
import datetime
import imutils
import time
import numpy as np
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the video file")
ap.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size")
args = vars(ap.parse_args())

cap = cv2.VideoCapture(0)

# if the video argument is None, then we are reading from webcam
if args.get("video", None) is None:
    cap = VideoStream(src=0).start()
    time.sleep(2.0)

# otherwise, we are reading from a video file
else:
    cap = cv2.VideoCapture(args["video"])

# initialize the first frame in the video stream
firstFrame = None
#Me:
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('triale.avi',fourcc, 30.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        frame = cv2.GaussianBlur(frame, (3, 3), 0)
        v = np.median(frame)
        sigma=0.15
        lower = int(max(0, (1.0 - sigma) * v))
        upper = int(min(255, (1.0 + sigma) * v))
        frame = cv2.Canny(frame,lower,upper)
        frame = np.expand_dims(frame, axis=-1)
        frame = np.concatenate((frame, frame, frame), axis=2)

# loop over the frames of the video
while True:
    # grab the current frame and initialize the occupied/unoccupied
    # text
    frame = cap.read()
    frame = frame if args.get("video", None) is None else frame[1]
    text = "No Track"

    # if the frame could not be grabbed, then we have reached the end
    # of the video
    if frame is None:
        break

    # resize the frame, convert it to grayscale, and blur it
    frame = imutils.resize(frame, width=500)


    # if the first frame is None, initialize it
    if firstFrame is None:
        firstFrame = frame
        continue

# compute the absolute difference between the current frame and
    # first frame
    frameDelta = cv2.absdiff(firstFrame, frame)
    thresh = cv2.threshold(frameDelta, lower, upper, cv2.THRESH_BINARY)[1]

    # dilate the thresholded image to fill in holes, then find contours
    # on thresholded image
    thresh = cv2.dilate(thresh, None, iterations=2)
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)

    # loop over the contours
    for c in cnts:
        # if the contour is too small, ignore it
        if cv2.contourArea(c) < args["min_area"]:
            continue

        # compute the bounding box for the contour, draw it on the frame,
        # and update the text
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        text = "Track"

# draw the text and timestamp on the frame
    cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
        (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)

    # show the frame and record if the user presses a key
    cv2.imshow("Security Feed", frame)
    cv2.imshow("Thresh", thresh)
    cv2.imshow("Frame Delta", frameDelta)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key is pressed, break from the lop
    if key == ord("q"):
        break

# cleanup the camera and close any open windows
cap.stop() if args.get("video", None) is None else cap.release()
cv2.destroyAllWindows()

Поскольку я новичок в кодировании, я не слишком уверен, как решить эту проблему, так как я все еще пытаюсь научить себя python и opencv. Я был бы очень признателен, если бы кто-нибудь мог объяснить, как я могу исправить свой код, возможно, как его улучшить и где именно добавить или удалить строки кода. Большое вам спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...