Showing
1 changed file
with
54 additions
and
0 deletions
etc/motion_crop.py
0 → 100644
| 1 | +import cv2 | ||
| 2 | +import numpy as np | ||
| 3 | + | ||
| 4 | +cap = cv2.VideoCapture('./videos/test.mp4') #load video | ||
| 5 | +count1 = 0 #counts number of frames | ||
| 6 | + | ||
| 7 | +#capture two frames | ||
| 8 | +rval, frame1 = cap.read() | ||
| 9 | +rval, frame2 = cap.read() | ||
| 10 | + | ||
| 11 | +while cap.isOpened(): | ||
| 12 | + | ||
| 13 | + diff = cv2.absdiff(frame1, frame2) #difference of two frames | ||
| 14 | + gray = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY) #convert diff into greyscale | ||
| 15 | + | ||
| 16 | + blur = cv2.GaussianBlur(gray, (5,5), 0) #blur image to reduce noise | ||
| 17 | + _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) #set threshold | ||
| 18 | + dilated = cv2.dilate(thresh, None, iterations=3) #fill holes in the thresholded image | ||
| 19 | + | ||
| 20 | + #find contour | ||
| 21 | + contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) | ||
| 22 | + | ||
| 23 | + count2 = 0 #counts number of motions in a frame | ||
| 24 | + | ||
| 25 | + #further implementation(removing, rectangle) | ||
| 26 | + for contour in contours: | ||
| 27 | + (x, y, w, h) = cv2.boundingRect(contour) #values of contour | ||
| 28 | + | ||
| 29 | + if cv2.contourArea(contour) < 7000: #to remove small unnecessary contours, (modify number for better results) | ||
| 30 | + continue | ||
| 31 | + | ||
| 32 | + filename = "clip{}-{}.jpg".format(count1,count2) | ||
| 33 | + | ||
| 34 | + motion = frame1[y:y+h, x:x+w] | ||
| 35 | + cv2.imwrite(filename, motion) | ||
| 36 | + | ||
| 37 | + count2 += 1 | ||
| 38 | + #cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 0, 255), 2) #draw rectangle on frame1 | ||
| 39 | + | ||
| 40 | + count1 += 1 | ||
| 41 | + | ||
| 42 | + #show results | ||
| 43 | + #cv2.imshow("feed", frame1) | ||
| 44 | + | ||
| 45 | + #change to next frame | ||
| 46 | + frame1 = frame2 | ||
| 47 | + rval, frame2 = cap.read() | ||
| 48 | + | ||
| 49 | + #incase of error | ||
| 50 | + if cv2.waitKey(40) == 27: | ||
| 51 | + break | ||
| 52 | + | ||
| 53 | +cap.release() | ||
| 54 | +cv2.destroyAllWindows() | ||
| ... | \ No newline at end of file | ... | \ No newline at end of file |
-
Please register or login to post a comment