I wish to train a background region with 50 frames and use this pre-trained model for background subtraction. Model stops updating after training.
Here is my code
import cv2
print "This program is for background subtraction with pre-trained model\n"
Training_Floder = "/Users/yuyang/Desktop/img1/"
Start_Frame_Num = 1
End_Frame_Num = 51
cv2.namedWindow("BG_IMAGE")
fgbg = cv2.createBackgroundSubtractorMOG2(50, 16, False)
font = cv2.FONT_HERSHEY_SIMPLEX
for index in range(Start_Frame_Num, End_Frame_Num):
Img_File_Name = Training_Floder + str(index) + ".jpg"
Img = cv2.imread(Img_File_Name)
fgmask = fgbg.apply(Img, -1)
BG_IMG = fgbg.getBackgroundImage()
#######
cv2.putText(BG_IMG,str(index),(10,500), font, 1,(255,255,255),2)
cv2.imshow("BG_IMAGE", BG_IMG)
#######
cv2.waitKey(0)
Testing_Floder = "/Users/yuyang/Desktop/New/"
Test_Start = 1
Test_End = 100
for index in range(Test_Start, Test_End):
Img_File_Name = Testing_Floder + str(index) + ".jpg"
Img = cv2.imread(Img_File_Name)
fgmask1 = fgbg.apply(Img, 0)
BG_IMG1 = fgbg.getBackgroundImage()
cv2.putText(BG_IMG1,str(index),(10,500), font, 1,(255,255,255),2)
cv2.imshow("BG_IMAGE", BG_IMG1)
cv2.waitKey(0)
Based on the comments
The learning rate parameter is in the function "apply()".
@param learningRate
The value between 0 and 1 that indicates how fast the background
model is learnt. Negative parameter value makes the algorithm to
use some automatically chosen learning rate. 0 means that the
background model is not updated at all, 1 means that the background
model is completely reinitialized from the last frame.
CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0;"
However, I tried several learning rate here:
fgmask = fgbg.apply(Img, -1) or
fgmask = fgbg.apply(Img, 0) or
fgmask = fgbg.apply(Img, 1) or
fgmask = fgbg.apply(Img, 0.00001)
The training Background result does not change. This means I CANNOT keep pre-trained model unchanged while testing!
Is there anything wrong with my code? Is there any way to change the learning rate?
Here are some results
Background subtraction result of Testing image #1
Background subtraction result of Testing image #40
From the result above, it is clear that the trained background image changes while testing, although I set learning rate as 0.
fgmask1 = fgbg.apply(Img, 0)
So the correct way to use the python implementation is
fgbg = cv2.createBackgroundSubtractorMOG2(50, 16, False)
fgbg.apply(input, output, learning_rate)
Exactly as in the c++ implementation. The learning rate must be the third parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With