1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-29 15:23:05 +04:00

python: 'cv2.' -> 'cv.' via 'import cv2 as cv'

This commit is contained in:
Alexander Alekhin
2017-12-11 12:55:03 +03:00
parent 9665dde678
commit 5560db73bf
162 changed files with 2083 additions and 2084 deletions
@@ -5,8 +5,8 @@ Goal
----
- Learn to draw different geometric shapes with OpenCV
- You will learn these functions : **cv2.line()**, **cv2.circle()** , **cv2.rectangle()**,
**cv2.ellipse()**, **cv2.putText()** etc.
- You will learn these functions : **cv.line()**, **cv.circle()** , **cv.rectangle()**,
**cv.ellipse()**, **cv.putText()** etc.
Code
----
@@ -19,7 +19,7 @@ In all the above functions, you will see some common arguments as given below:
- thickness : Thickness of the line or circle etc. If **-1** is passed for closed figures like
circles, it will fill the shape. *default thickness = 1*
- lineType : Type of line, whether 8-connected, anti-aliased line etc. *By default, it is
8-connected.* cv2.LINE_AA gives anti-aliased line which looks great for curves.
8-connected.* cv.LINE_AA gives anti-aliased line which looks great for curves.
### Drawing Line
@@ -27,27 +27,27 @@ To draw a line, you need to pass starting and ending coordinates of line. We wil
image and draw a blue line on it from top-left to bottom-right corners.
@code{.py}
import numpy as np
import cv2
import cv2 as cv
# Create a black image
img = np.zeros((512,512,3), np.uint8)
# Draw a diagonal blue line with thickness of 5 px
cv2.line(img,(0,0),(511,511),(255,0,0),5)
cv.line(img,(0,0),(511,511),(255,0,0),5)
@endcode
### Drawing Rectangle
To draw a rectangle, you need top-left corner and bottom-right corner of rectangle. This time we
will draw a green rectangle at the top-right corner of image.
@code{.py}
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv.rectangle(img,(384,0),(510,128),(0,255,0),3)
@endcode
### Drawing Circle
To draw a circle, you need its center coordinates and radius. We will draw a circle inside the
rectangle drawn above.
@code{.py}
cv2.circle(img,(447,63), 63, (0,0,255), -1)
cv.circle(img,(447,63), 63, (0,0,255), -1)
@endcode
### Drawing Ellipse
@@ -55,10 +55,10 @@ To draw the ellipse, we need to pass several arguments. One argument is the cent
Next argument is axes lengths (major axis length, minor axis length). angle is the angle of rotation
of ellipse in anti-clockwise direction. startAngle and endAngle denotes the starting and ending of
ellipse arc measured in clockwise direction from major axis. i.e. giving values 0 and 360 gives the
full ellipse. For more details, check the documentation of **cv2.ellipse()**. Below example draws a
full ellipse. For more details, check the documentation of **cv.ellipse()**. Below example draws a
half ellipse at the center of the image.
@code{.py}
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
cv.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
@endcode
### Drawing Polygon
@@ -68,30 +68,30 @@ polygon of with four vertices in yellow color.
@code{.py}
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(0,255,255))
cv.polylines(img,[pts],True,(0,255,255))
@endcode
@note If third argument is False, you will get a polylines joining all the points, not a closed
shape.
@note cv2.polylines() can be used to draw multiple lines. Just create a list of all the lines you
@note cv.polylines() can be used to draw multiple lines. Just create a list of all the lines you
want to draw and pass it to the function. All lines will be drawn individually. It is a much better
and faster way to draw a group of lines than calling cv2.line() for each line.
and faster way to draw a group of lines than calling cv.line() for each line.
### Adding Text to Images:
To put texts in images, you need specify following things.
- Text data that you want to write
- Position coordinates of where you want put it (i.e. bottom-left corner where data starts).
- Font type (Check **cv2.putText()** docs for supported fonts)
- Font type (Check **cv.putText()** docs for supported fonts)
- Font Scale (specifies the size of font)
- regular things like color, thickness, lineType etc. For better look, lineType = cv2.LINE_AA
- regular things like color, thickness, lineType etc. For better look, lineType = cv.LINE_AA
is recommended.
We will write **OpenCV** on our image in white color.
@code{.py}
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv.LINE_AA)
@endcode
### Result
@@ -5,7 +5,7 @@ Goals
-----
- Here, you will learn how to read an image, how to display it and how to save it back
- You will learn these functions : **cv2.imread()**, **cv2.imshow()** , **cv2.imwrite()**
- You will learn these functions : **cv.imread()**, **cv.imshow()** , **cv.imwrite()**
- Optionally, you will learn how to display images with Matplotlib
Using OpenCV
@@ -13,25 +13,25 @@ Using OpenCV
### Read an image
Use the function **cv2.imread()** to read an image. The image should be in the working directory or
Use the function **cv.imread()** to read an image. The image should be in the working directory or
a full path of image should be given.
Second argument is a flag which specifies the way image should be read.
- cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the
- cv.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the
default flag.
- cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
- cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel
- cv.IMREAD_GRAYSCALE : Loads image in grayscale mode
- cv.IMREAD_UNCHANGED : Loads image as such including alpha channel
@note Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.
See the code below:
@code{.py}
import numpy as np
import cv2
import cv2 as cv
# Load an color image in grayscale
img = cv2.imread('messi5.jpg',0)
img = cv.imread('messi5.jpg',0)
@endcode
**warning**
@@ -40,21 +40,21 @@ Even if the image path is wrong, it won't throw any error, but `print img` will
### Display an image
Use the function **cv2.imshow()** to display an image in a window. The window automatically fits to
Use the function **cv.imshow()** to display an image in a window. The window automatically fits to
the image size.
First argument is a window name which is a string. second argument is our image. You can create as
many windows as you wish, but with different window names.
@code{.py}
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
@endcode
A screenshot of the window will look like this (in Fedora-Gnome machine):
![image](images/opencv_screenshot.jpg)
**cv2.waitKey()** is a keyboard binding function. Its argument is the time in milliseconds. The
**cv.waitKey()** is a keyboard binding function. Its argument is the time in milliseconds. The
function waits for specified milliseconds for any keyboard event. If you press any key in that time,
the program continues. If **0** is passed, it waits indefinitely for a key stroke. It can also be
set to detect specific key strokes like, if key a is pressed etc which we will discuss below.
@@ -62,30 +62,30 @@ set to detect specific key strokes like, if key a is pressed etc which we will d
@note Besides binding keyboard events this function also processes many other GUI events, so you
MUST use it to actually display the image.
**cv2.destroyAllWindows()** simply destroys all the windows we created. If you want to destroy any
specific window, use the function **cv2.destroyWindow()** where you pass the exact window name as
**cv.destroyAllWindows()** simply destroys all the windows we created. If you want to destroy any
specific window, use the function **cv.destroyWindow()** where you pass the exact window name as
the argument.
@note There is a special case where you can already create a window and load image to it later. In
that case, you can specify whether window is resizable or not. It is done with the function
**cv2.namedWindow()**. By default, the flag is cv2.WINDOW_AUTOSIZE. But if you specify flag to be
cv2.WINDOW_NORMAL, you can resize window. It will be helpful when image is too large in dimension
**cv.namedWindow()**. By default, the flag is cv.WINDOW_AUTOSIZE. But if you specify flag to be
cv.WINDOW_NORMAL, you can resize window. It will be helpful when image is too large in dimension
and adding track bar to windows.
See the code below:
@code{.py}
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
@endcode
### Write an image
Use the function **cv2.imwrite()** to save an image.
Use the function **cv.imwrite()** to save an image.
First argument is the file name, second argument is the image you want to save.
@code{.py}
cv2.imwrite('messigray.png',img)
cv.imwrite('messigray.png',img)
@endcode
This will save the image in PNG format in the working directory.
@@ -95,22 +95,22 @@ Below program loads an image in grayscale, displays it, save the image if you pr
simply exit without saving if you press ESC key.
@code{.py}
import numpy as np
import cv2
import cv2 as cv
img = cv2.imread('messi5.jpg',0)
cv2.imshow('image',img)
k = cv2.waitKey(0)
img = cv.imread('messi5.jpg',0)
cv.imshow('image',img)
k = cv.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
cv.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
cv.imwrite('messigray.png',img)
cv.destroyAllWindows()
@endcode
**warning**
If you are using a 64-bit machine, you will have to modify `k = cv2.waitKey(0)` line as follows :
`k = cv2.waitKey(0) & 0xFF`
If you are using a 64-bit machine, you will have to modify `k = cv.waitKey(0)` line as follows :
`k = cv.waitKey(0) & 0xFF`
Using Matplotlib
----------------
@@ -120,10 +120,10 @@ will see them in coming articles. Here, you will learn how to display image with
zoom images, save it etc using Matplotlib.
@code{.py}
import numpy as np
import cv2
import cv2 as cv
from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)
img = cv.imread('messi5.jpg',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
@@ -5,7 +5,7 @@ Goal
----
- Learn to handle mouse events in OpenCV
- You will learn these functions : **cv2.setMouseCallback()**
- You will learn these functions : **cv.setMouseCallback()**
Simple Demo
-----------
@@ -19,32 +19,32 @@ double-click etc. It gives us the coordinates (x,y) for every mouse event. With
location, we can do whatever we like. To list all available events available, run the following code
in Python terminal:
@code{.py}
import cv2
events = [i for i in dir(cv2) if 'EVENT' in i]
import cv2 as cv
events = [i for i in dir(cv) if 'EVENT' in i]
print( events )
@endcode
Creating mouse callback function has a specific format which is same everywhere. It differs only in
what the function does. So our mouse callback function does one thing, it draws a circle where we
double-click. So see the code below. Code is self-explanatory from comments :
@code{.py}
import cv2
import numpy as np
import cv2 as cv
# mouse callback function
def draw_circle(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img,(x,y),100,(255,0,0),-1)
if event == cv.EVENT_LBUTTONDBLCLK:
cv.circle(img,(x,y),100,(255,0,0),-1)
# Create a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
if cv2.waitKey(20) & 0xFF == 27:
cv.imshow('image',img)
if cv.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()
cv.destroyAllWindows()
@endcode
More Advanced Demo
------------------
@@ -55,8 +55,8 @@ function has two parts, one to draw rectangle and other to draw the circles. Thi
will be really helpful in creating and understanding some interactive applications like object
tracking, image segmentation etc.
@code{.py}
import cv2
import numpy as np
import cv2 as cv
drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
@@ -66,40 +66,40 @@ ix,iy = -1,-1
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN:
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
cv.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
elif event == cv.EVENT_LBUTTONUP:
drawing = False
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
cv.circle(img,(x,y),5,(0,0,255),-1)
@endcode
Next we have to bind this mouse callback function to OpenCV window. In the main loop, we should set
a keyboard binding for key 'm' to toggle between rectangle and circle.
@code{.py}
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv2.destroyAllWindows()
cv.destroyAllWindows()
@endcode
Additional Resources
--------------------
@@ -5,7 +5,7 @@ Goal
----
- Learn to bind trackbar to OpenCV windows
- You will learn these functions : **cv2.getTrackbarPos()**, **cv2.createTrackbar()** etc.
- You will learn these functions : **cv.getTrackbarPos()**, **cv.createTrackbar()** etc.
Code Demo
---------
@@ -14,7 +14,7 @@ Here we will create a simple application which shows the color you specify. You
shows the color and three trackbars to specify each of B,G,R colors. You slide the trackbar and
correspondingly window color changes. By default, initial color will be set to Black.
For cv2.getTrackbarPos() function, first argument is the trackbar name, second one is the window
For cv.getTrackbarPos() function, first argument is the trackbar name, second one is the window
name to which it is attached, third argument is the default value, fourth one is the maximum value
and fifth one is the callback function which is executed everytime trackbar value changes. The
callback function always has a default argument which is the trackbar position. In our case,
@@ -25,43 +25,43 @@ doesn't have button functionality. So you can use trackbar to get such functiona
application, we have created one switch in which application works only if switch is ON, otherwise
screen is always black.
@code{.py}
import cv2
import numpy as np
import cv2 as cv
def nothing(x):
pass
# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')
cv.namedWindow('image')
# create trackbars for color change
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)
# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image',0,1,nothing)
cv.createTrackbar(switch, 'image',0,1,nothing)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
# get current positions of four trackbars
r = cv2.getTrackbarPos('R','image')
g = cv2.getTrackbarPos('G','image')
b = cv2.getTrackbarPos('B','image')
s = cv2.getTrackbarPos(switch,'image')
r = cv.getTrackbarPos('R','image')
g = cv.getTrackbarPos('G','image')
b = cv.getTrackbarPos('B','image')
s = cv.getTrackbarPos(switch,'image')
if s == 0:
img[:] = 0
else:
img[:] = [b,g,r]
cv2.destroyAllWindows()
cv.destroyAllWindows()
@endcode
The screenshot of the application looks like below :
@@ -6,7 +6,7 @@ Goal
- Learn to read video, display video and save video.
- Learn to capture from Camera and display it.
- You will learn these functions : **cv2.VideoCapture()**, **cv2.VideoWriter()**
- You will learn these functions : **cv.VideoCapture()**, **cv.VideoWriter()**
Capture Video from Camera
-------------------------
@@ -22,25 +22,25 @@ the second camera by passing 1 and so on. After that, you can capture frame-by-f
end, don't forget to release the capture.
@code{.py}
import numpy as np
import cv2
import cv2 as cv
cap = cv2.VideoCapture(0)
cap = cv.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv.imshow('frame',gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
cv.destroyAllWindows()
@endcode
`cap.read()` returns a bool (`True`/`False`). If frame is read correctly, it will be `True`. So you can
check end of the video by checking this return value.
@@ -55,9 +55,9 @@ video) and full details can be seen here: cv::VideoCapture::get().
Some of these values can be modified using **cap.set(propId, value)**. Value is the new value you
want.
For example, I can check the frame width and height by `cap.get(cv2.CAP_PROP_FRAME_WIDTH)` and `cap.get(cv2.CAP_PROP_FRAME_HEIGHT)`. It gives me
640x480 by default. But I want to modify it to 320x240. Just use `ret = cap.set(cv2.CAP_PROP_FRAME_WIDTH,320)` and
`ret = cap.set(cv2.CAP_PROP_FRAME_HEIGHT,240)`.
For example, I can check the frame width and height by `cap.get(cv.CAP_PROP_FRAME_WIDTH)` and `cap.get(cv.CAP_PROP_FRAME_HEIGHT)`. It gives me
640x480 by default. But I want to modify it to 320x240. Just use `ret = cap.set(cv.CAP_PROP_FRAME_WIDTH,320)` and
`ret = cap.set(cv.CAP_PROP_FRAME_HEIGHT,240)`.
@note If you are getting error, make sure camera is working fine using any other camera application
(like Cheese in Linux).
@@ -66,26 +66,26 @@ Playing Video from file
-----------------------
It is same as capturing from Camera, just change camera index with video file name. Also while
displaying the frame, use appropriate time for `cv2.waitKey()`. If it is too less, video will be very
displaying the frame, use appropriate time for `cv.waitKey()`. If it is too less, video will be very
fast and if it is too high, video will be slow (Well, that is how you can display videos in slow
motion). 25 milliseconds will be OK in normal cases.
@code{.py}
import numpy as np
import cv2
import cv2 as cv
cap = cv2.VideoCapture('vtest.avi')
cap = cv.VideoCapture('vtest.avi')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv.imshow('frame',gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
cv.destroyAllWindows()
@endcode
@note Make sure proper versions of ffmpeg or gstreamer is installed. Sometimes, it is a headache to
@@ -95,7 +95,7 @@ Saving a Video
--------------
So we capture a video, process it frame-by-frame and we want to save that video. For images, it is
very simple, just use `cv2.imwrite()`. Here a little more work is required.
very simple, just use `cv.imwrite()`. Here a little more work is required.
This time we create a **VideoWriter** object. We should specify the output file name (eg:
output.avi). Then we should specify the **FourCC** code (details in next paragraph). Then number of
@@ -111,30 +111,30 @@ platform dependent. Following codecs works fine for me.
- In Windows: DIVX (More to be tested and added)
- In OSX: MJPG (.mp4), DIVX (.avi), X264 (.mkv).
FourCC code is passed as `cv2.VideoWriter_fourcc('M','J','P','G')` or
`cv2.VideoWriter_fourcc(*'MJPG')` for MJPG.
FourCC code is passed as `cv.VideoWriter_fourcc('M','J','P','G')` or
`cv.VideoWriter_fourcc(*'MJPG')` for MJPG.
Below code capture from a Camera, flip every frame in vertical direction and saves it.
@code{.py}
import numpy as np
import cv2
import cv2 as cv
cap = cv2.VideoCapture(0)
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
frame = cv.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
else:
break
@@ -142,7 +142,7 @@ while(cap.isOpened()):
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
cv.destroyAllWindows()
@endcode
Additional Resources