OPENCV3 Computer Vision +python (i.)

Source: Internet
Author: User
Tags flv file

Basic I/O script read/write image file

OPENCV's imread functions and Imwrite functions can support a variety of static image file formats. The file formats supported by different systems are not the same, but they all support the BMP format and generally should also support PNG, JPEG, and TIFF formats.

Most of the commonly used OPENCV functions are in the CV2 module. You may also encounter other OPENCV help based on CV or CV2.CV modules, which are traditional versions. The Python module, known as CV2, does not indicate that the module is for the opencv2.x.x version

Parameters of the Imread () function:

1.imread_anycolor=4

2.imread_anydepth=2

3.imread_color=1

4.imread_grayscale=0

5imread_load_gdal=8

6.imread_unchanged=-1

Cv.imshow (' Window name ', IMG) #必须要加上窗口名

and must be added

Cv2.waitkey (0)
Cv2.destroyallwindows () otherwise it will blink.

Conversion between the image and the original byte

A OPENCV image is a two-dimensional or three-dimensional array of. Array types.

A 8-bit grayscale image is a two-dimensional array that contains bytes worth. A 24-dimensional RGB image is a three-dimensional array that also contains the byte values. You can use an expression to access these values, such as image[0,0] or image[0,0,0]. The first value represents the pixel y-coordinate or line, 0 represents the top, the second value is the pixel x-coordinate or column, 0 is the leftmost, and the third value, if available, represents the color channel.

If an image has 8 bits per channel, the display can be converted to a standard one-dimensional python bytearray format:

Bytearray=bytearray (image)

Conversely, ByteArray contains the appropriate sequence of bytes, which can be obtained by explicit conversion and refactoring to obtain an image in Numpy.array form:

Grayimage=numpy.array (Graybytearray). Reshape (Height,width)

Bgrimage=numpy.array (Bgrbytearray). Reshape (height,width,3)

Read/write video files

OPENCV provides videocapture classes and Videowriter classes to support video files in a variety of formats. The supported format types may vary depending on the system, but the AVI format should be supported. Before the end of the video file is reached, the Videocapture class can obtain a new frame through the read () function, each frame is a pair of images based on the BGR format

An image can be passed to the write () function of the Videowriter class, which adds the image to the file pointed to by the Videowriter class.

Special NOTE: You must specify a video file name for the constructor of the Videowriter class, which will overwrite the file name if it exists. You must also specify a video codec. The availability of codecs differs depending on the system. The following are common options:

Cv2. VIDEOWRITER_FOURCC (' I ', ' 4 ', ' 2 ', ' 0 '): This option is an uncompressed YUV color coding, which is a 4:2:0 chroma sub-sample. This encoding has good compatibility, but produces large files with the. avi file name extension.

Cv2. VIDEOWRITER_FOURCC (' P ', ' I ', ' M ', ' 1 '): This option is a MPEG-1 encoding type with a. avi file extension.

Cv2. VIDEOWRITER_FOURCC (' X ', ' V ', ' I ', ' D '): This option is the MPEG-4 encoding type, and if you want to get the average video size, this option is recommended, with the file extension. avi

Cv2. VIDEOWRITER_FOURCC (' F ', ' L ', ' V ', ' 1 '): This option is a flash video with a. flv file name extension.

Capturing the camera's frame

The Videocapture class can get the frame stream of the camera. For cameras, however, the Videocapture class is not usually constructed with the file name of the video, but rather the device index that needs to pass the camera

Unlike before, however, the Get () method of the Videocapture class cannot return the exact value of the camera frame rate (fps), which always returns 0

Import Cv2import NumPy asnpcameracapture=cv2. Videocapture (0) #调用摄像头fps= -size=(int(Cameracapture.Get(Cv2. Cap_prop_frame_width)),int(Cameracapture.Get(Cv2. Cap_prop_frame_height )) Videowriter=cv2. Videowriter ('4.avi', Cv2. VIDEOWRITER_FOURCC ('X','V','I','D'), fps,size) Success,frame=cameracapture.read () numframesremaining=Ten*fps-1#倒计时 whileSuccess and Numframesremaining>0: Videowriter.write (frame) Success,frame=cameracapture.read () numframesremaining-=1cameracapture.release ()

The number and order of the cameras is determined by the system. However, OPENCV does not provide any method for querying the number and attributes of cameras. If you construct the Videocapture class with an invalid index, you do not get the frame, and the videocapture read () function returns (False,none). To keep the read () function from getting data from the Videocapture class that did not open correctly, you can use the Videocapture.isopened method to make a decision after executing the function, which returns a Boolean value.

The read () method is no longer suitable when a group of cameras or a multi-camera is required, and can be replaced by the grab () and retrive () methods. For a group of cameras, you can use the following code

success0=cameracapture0.grab () success1=cameracapture1.grab ()if  success0 and Success1:     FRAME0=cameracapture0.retrieve ()     frame1=cameracapture1.retrieve ()
Display an image in a window

Cv.imshow (' Window name ', IMG) #必须要加上窗口名

and must be added

Cv2.waitkey (0)
Cv2.destroyallwindows () otherwise it will blink.

Show camera frame in window

OpenCV's Namedwindow (), Imshow (), and DestroyWindow () functions allow you to specify windows to create, display, and Destroy (Destroy) windows. In addition, the Waitkey () function can be used to get the keyboard input under any window, and the Setmousecallback () function to get the mouse input.

Import cv2clicked=falsedef Onmouse (Event, X,y,flags,param):Globalclickedif Event==Cv2. Event_lbuttonup:clicked=truecameracapture=cv2. Videocapture (0) Cv2.namedwindow ('Mywindow') Cv2.setmousecallback ('Mywindow', Onmouse) print ('Showing camera feed. Click window or Press any key to stop') Success,frame=Cameracapture.read () whileSuccess and Cv2.waitkey (1)==-1and not clicked: #要么键盘输入要么鼠标输入, or the camera gets the frame is unsuccessful, otherwise it will continue Cv2.imshow ('Mywindow', frame) Success,frame=Cameracapture.read () Cv2.destroywindow ('Mywindow') cameracapture.release ()

OpenCV's window functions and Waitkey () functions depend on each other. The OpenCV window is updated only when the Waitkey () function is called, and the Waitkey () function captures the input information only when the OpenCV window becomes the active window.

The mouse callback function Setmousecallback () has 5 parameters, as shown in the previous example code. Param is an optional parameter, which is the third parameter of the Setmousecallback () function, which, by default, is 0. callback event arguments can take the following values, which correspond to different mouse events.

Cv2. Event_mousemove: The event corresponds to mouse movement

Cv2. Event_lbuttondown: The event corresponds to the left mouse button pressed

Cv2. Event_rbuttondown: The event corresponds to the right mouse button press

Cv2. Event_mbuttondown: This event corresponds to the middle mouse button press

Cv2. Event_lbuttonup: The event corresponds to the left mouse button release

Cv2. Event_rbuttonup: The event corresponds to the right mouse button release

Cv2. Event_mbuttonup: This event corresponds to the middle mouse button release

Cv2. EVENT_LBUTTONDBLCLK: The event corresponds to double-click the left mouse button

Cv2. EVENT_RBUTTONDBLCLK: The event corresponds to double-click the right mouse button

Cv2. EVENT_MBUTTONDBLCLK: The event corresponds to double-clicking the middle mouse button

The flag parameter of the mouse callback may be a bitwise combination of the following events:

Cv2. Event_flag_lbutton: This event corresponds to pressing the left mouse button

Cv2. Event_flag_rbutton: This event corresponds to pressing the right mouse button

Cv2. Event_flag_mbutton: This event corresponds to pressing the middle mouse button

Cv2. Event_flag_ctrlkey: The event corresponds to pressing the CTRL key

Cv2. Event_flag_shiftkey: This event corresponds to holding down the SHIFT key

Cv2. Event_flag_altkey: The event corresponds to pressing the ALT key

However, OPENCV does not provide any way to handle window events. For example, you cannot close an application when you click the Close button of a window. Due to OpenCV limited event handling and GUI processing power.

cameo--Object-oriented design

Python's applications can be implemented purely in a process-oriented language, as is often the case with small applications such as the basic I/O scripts discussed earlier. However, in order to improve modularity and scalability, the following will be implemented in an object-oriented manner.

With the OpenCV I/O function described earlier, all images are actually similar, although the source or destination of the images is different. The same logic can be applied to every frame in the image stream, regardless of where the image stream is obtained or where it is to be exported. Separating I/O code from application code can be particularly handy in an app, such as cameo using multiple I/O streams

You can create Capturemanager classes and WindowManager classes as advanced I/O stream interfaces. In your application's code, you can use Capturemanager to read new frames and to assign frames to one or more outputs, including still image files, video files, and Windows (which can be implemented through the WindowManager class). The WindowManager class enables application code to handle Windows and events in an object-oriented manner.

Both Capturemanager and WindowManager are extensible, so they can be implemented without relying on OPENCV I/O.

Use managers. Capturemanager Extracting video streams

Whether the image stream comes from a video file or a webcam, OpenCV can capture, display, and record the image stream, but there are a few places in each case that require special consideration. The Capturemanager class abstracts some differences and provides a more advanced interface to allocate images from the fetch stream, and then divide the images into one or more outputs (like files, video files, or Windows).

Initializing the Capturemanager class in the Videocapture class, The Enterframe () and Exitframe () functions of the Capturemanager class should normally be called in every iteration of the application's main loop. Between calling the Enterframe () and Exitframe () functions, the application may set the channel properties and get the frame properties. The initial value of the channel attribute is 0, and the initial value of the channel attribute is not 0, only in the case of a multi-camera. The Frame property is the image that corresponds to the current channel state when the Enterframe () function is called.

The Writeimage (), Startwritingvideo (), and Stopwritingvideo () functions of the Capturemanager class may be called frequently. The file is deferred until the Existframe () function is called. Also, in the process of calling the Existframe () function, the frame properties may be displayed in the window, depending on the application code that uses the WindowManager class as the constructor parameter of the Capturemanager. or set the Previewwindowmanager property.

If the application code handles the frame properties, it will be reflected in the log files and Windows. The Capturemanager class has a constructor parameter and property called Shouldmirrorpreview, if you want the frame to mirror in the window (flip horizontally), but not in the file, You can set Shouldmirrorpreview to true. Usually, when facing the camera, the user likes the camera to return the mirror image.

The Videowriter class requires a frame rate, but OpenCV does not provide an accurate frame rate for the camera, and the way to solve this problem is to estimate the frame rate through the frame counter and the Python standard Time.time () function, but these methods are problematic. Because the frame rate is unstable and the time.time () function needs to rely on the system implementation, sometimes the estimated accuracy may be poor. However, if you run the application on an unknown hardware platform, the estimated frame rate will be better than assuming a camera's frame rate at random.

Cameo. The powerful implementation of cameo

The Cameo class provides two ways to start the application: Run () and onkeypress (). At initialization time, the Cameo class creates the WindowManager class with onkeypress () as the callback function, and the Capturemanager class uses the camera and WindowManager classes. When the run () function is called, the application executes the main loop-processing frame and event, and the application calls the onkeypress () function to handle the event. Press the SPACEBAR to get information, press the TAB key to start/Stop the screenshot (a video recording), press ESC to eject the application.

OPENCV3 Computer Vision +python (i.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.