Tag Archives: python study notes

Python+OpenCV: How to Use Background Subtraction Methods

Python+OpenCV:How to Use Background Subtraction Methods
Background subtraction (BS) is a common and widely used technique for generating a foreground mask (namely, a binary image containing the pixels belonging to moving objects in the scene) by using static cameras. As the name suggests, BS calculates the foreground mask performing a subtraction between the current frame and a background model, containing the static part of the scene or, more in general, everything that can be considered as background given the characteristics of the observed scene.

Background modeling consists of two main steps:

    Background Initialization;Background Update.

In the first step, an initial model of the background is computed, while in the second step that model is updated in order to adapt to possible changes in the scene.
Background Subtraction in OpenCV

####################################################################################################
# 图像背景减法(Background Subtraction Methods)
def lmc_cv_background_subtraction():
    """
        Function: Background Subtraction Methods.
    """"

    # Read the vide
    parser = argparse.ArgumentParser(description='This program shows how to use background subtraction methods\
                                                provided by OpenCV. You can process both videos and images.')
    parser.add_argument('--input', type=str, help='Path to a video or a sequence of image.',
                        default='D:/99-Research/Python/Image/box.mp4')
    parser.add_argument('--algo', type=str, help='Background subtraction method (KNN, MOG2).', default='MOG2')
    args = parser.parse_args()
    # A lmc_cv::BackgroundSubtractor object will be used to generate the foreground mask.
    if args.algo == 'MOG2':
        back_sub = lmc_cv.createBackgroundSubtractorMOG2()
    else:
        back_sub = lmc_cv.createBackgroundSubtractorKNN()
    # A lmc_cv::VideoCapture object is used to read the input video or input images sequence.
    capture = lmc_cv.VideoCapture(lmc_cv.samples.findFileOrKeep(args.input))
    if not capture.isOpened:
        print('Unable to open: ' + args.input)
        exit(0)
    while True:
        ret, frame = capture.read()
        if frame is None:
            break
        # Every frame is used both for calculating the foreground mask and for updating the background.
        fg_mask = back_sub.apply(frame)
        # get the frame number and write it on the current frame
        lmc_cv.rectangle(frame, (10, 2), (100, 20), (255, 255, 255), -1)
        lmc_cv.putText(frame, str(capture.get(lmc_cv.CAP_PROP_POS_FRAMES)), (15, 15),
                       lmc_cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
        # show the current frame and the ForeGround masks
        lmc_cv.imshow('Original Frame', frame)
        lmc_cv.imshow('ForeGround Mask', fg_mask)
        # quit
        keyboard = lmc_cv.waitKey(30)
        if keyboard == 'q' or keyboard == 27:
            break
    return

Python problem: indenta tionError:expected an Error resolution of indented block

The original address: http://hi.baidu.com/delinx/item/1789d38eafd358d05e0ec1df
   
Python is a very sensitive language for indentation, causing confusion for beginners and even experienced Python programmers, who can fall into the trap. The most common situation is that mixing tabs and Spaces causes errors, or indenting incorrectly, which is impossible to distinguish with the naked eye.
This fault occurs on compile IndentationError: expected an indented block here need to indent, you as long as there is an error in the line, press the space or Tab (but you can’t mix) key indentation.
Often some people will question: I did not indent how or wrong, wrong, the place where the indent should be indent, not indent will be wrong, such as:
If XXXXXX:
(space) XXXXX
or
Def XXXXXX:
(space) XXXXX
There are
For XXXXXX:
(space) XXXXX
The next line of a sentence with a colon is often indented

Python error unhandled exception in thread started by error in sys.excepthook

import time
import thread
def timer(no, interval):
 cnt = 0
 while cnt<10:
 print 'Thread:(%d) Time:%s/n'%(no, time.ctime())
 time.sleep(interval)
 cnt+=1
 thread.exit_thread()
 
def test(): #Use thread.start_new_thread() to create 2 new threads
 thread.start_new_thread(timer, (1,1))
 thread.start_new_thread(timer, (2,2))
 
if __name__=='__main__':
 test()

There is an error
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
Solution: Change the main function to

<pre>if __name__=='__main__':
 test()
time.sleep(3)

As for why sleep for a few seconds, not clear

The message on the Web is that threading is not recommended, use the threading.thread class instead

Python installation problem: error: Command erred out with exit status 1:

Try to run this command from the system terminal. Make sure that you use the correct version of ‘PIP’ installed for your Python interpreter located at “C: \ Users \ \ PycharmProjects \ pythonProject \ 123 venv \ Scripts \ python exe. ‘

this problem occurs because the Python version installed is relatively new and there is no PIP for the corresponding version. The solution is to install the older version. The author installed version 3.9, and the problem of installing version 3.8 is solved.

Python global variables and global keywords

Python global variables

and the global keyword

in Python variable usage, this error is often encountered :

local variable 'a' referenced before assignment

means that the local variable “a” is referenced before assignment.
such as running the following code will cause this problem:

a = 3
def Fuc():
    print (a)
    a = a + 1
Fuc()

, but if you delete a = a + 1, the above problem will not occur.

a = 3
def Fuc():
    print (a)
Fuc()

it turns out that in Python, a = 3 defines the global variable a, scope to the end of the code from the definition, in a = 3 of the following functions can be cited the global variable a, but if you want to modify the functions and global variables with the same name, the function of the variable will become a local variable, before the change of the variable reference nature presents undistributed or undefined error.

if you are sure to reference and modify global variables you must add the global keyword

a = 3
def Fuc():
    global a
    print (a)
    a=a+1
Fuc()

note: which function needs to modify the global variable, just declare it in the function.

but there is a special function, and that is the main function:

a = 3
def Fuc():
    global a
    print (a)  # 1
    a = a + 1
if __name__ == "__main__":
    print (a)  # 2
    a = a + 1
    Fuc()
    print (a)  # 3

output is as follows (in Python3) :

3
4
5

three prints are executed in the order of 2, 1, 3. You can see that there is no global declared variable A in the main function, but you can still modify the global variable A. In a normal function, the global variable A needs to be declared globally in order to modify it.

life is short, I use Python~