In order to define a ROI (Region Of Interest) that might change depending on the input video, I'm using the following approach:
Create a blank black image
Subtract the background using opencv function
Copy the white pixels (foreground) to the blank image for 5min
Problem: Under the 2 for loops, the if statement and the instruction inside it are slowing down the process time:
if opening[i][j] == 255 or opening[i][j] == 127:
blank_image[i][j] = [255, 255, 255]
I'm not familiar with opencv and I'm new to this stuff so I don't know if there is a better way to do it.
import numpy as np
import cv2
import sys
import time
from PIL import Image
fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows = 0)
video = 'C:/Users/HP/Desktop/sentdex/testLongVideo.mp4'
cap = cv2.VideoCapture(video)
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) #get the frame height
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) #get the frame width
x = 0
start = time.process_time() #start time
while(1 and time.process_time() - start < 300):
ret,frame = cap.read()
fgmask = fgbg.apply(frame) #apply the MOG2 mask on the video
erode = cv2.erode(fgmask, None, iterations = 1) #erosion to erase unwanted small contours
opening = cv2.morphologyEx(erode, cv2.MORPH_OPEN, None) #eliminate false positive on erosion
if x < 5: #this condition is used because if the creation of the black image starts at the same time as the video all the pixels will be white
blank_image = np.zeros((frame_height,frame_width,3), np.uint8) #create a black image with the same height and width of the video
x += 1
else:
for i in range(len(opening)):
for j in range(len(opening[i])):
if [i,j] not in checked and opening[i][j] == 255 or opening[i][j] == 127: #skip the treated pixels and check which pixels of the treated frame are white or gray (moving objects and their shadows)
blank_image[i][j] = [255, 255, 255] #turn the pixels in the black image to white from the treated video by the X and Y
checked.append([i,j]) #treated pixels
cv2.imwrite('backgroundMask.png', blank_image) #saving the background treated
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
I tried to run the loops without anything inside and it run just fine:
for i in range(len(opening)):
for j in range(len(opening[i])):
continue
When I add an instruction without an if statement it's pretty slow:
for i in range(len(opening)):
for j in range(len(opening[i])):
blank_image[i][j] = [255, 255, 255]
But when I add the if statement, even if there's no instruction in it, it's even slower:
for i in range(len(opening)):
for j in range(len(opening[i])):
if opening[i][j] == 255:
continue