如何在pi相机上实现运动检测和跟踪以进行实时边缘检测

时间:2019-03-05 18:06:19

标签: python opencv edge-detection motion-detection event-tracking

我目前正在尝试将运动检测和跟踪实现到我编写的Canny Edge检测程序中。但是,当我尝试将代码实现到预先编写的框架中以从网站https://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/进行运动检测和跟踪时,

我收到此错误:

class Mapping(models.Model):
    id = models.AutoField(primary_key=True)
    video = models.ForeignKey(Videos, to_field='videoid', db_column='videoid', on_delete=models.DO_NOTHING,blank=False,null=True,)
    keyword = models.ForeignKey(Keywords, to_field='keyword', db_column='keyword', on_delete=models.DO_NOTHING, blank=False, null=True,)

我的canny边缘检测代码如下,它可以很好地工作:

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。如果有人能解释我如何修正我的代码,也许如何对其进行改进以及在何处添加或删除代码行,我将不胜感激。非常感谢。

0 个答案:

没有答案