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
@@ -21,10 +21,10 @@ Accessing and Modifying pixel values
Let's load a color image first:
@code{.py}
>>> import cv2
>>> import numpy as np
>>> import cv2 as cv
>>> img = cv2.imread('messi5.jpg')
>>> img = cv.imread('messi5.jpg')
@endcode
You can access a pixel value by its row and column coordinates. For BGR image, it returns an array
of Blue, Green, Red values. For grayscale image, just corresponding intensity is returned.
@@ -122,8 +122,8 @@ Sometimes you will need to work separately on B,G,R channels of image. In this c
to split the BGR images to single channels. In other cases, you may need to join these individual
channels to a BGR image. You can do it simply by:
@code{.py}
>>> b,g,r = cv2.split(img)
>>> img = cv2.merge((b,g,r))
>>> b,g,r = cv.split(img)
>>> img = cv.merge((b,g,r))
@endcode
Or
@code
@@ -137,14 +137,14 @@ Numpy indexing is faster:
**Warning**
cv2.split() is a costly operation (in terms of time). So do it only if you need it. Otherwise go
cv.split() is a costly operation (in terms of time). So do it only if you need it. Otherwise go
for Numpy indexing.
Making Borders for Images (Padding)
-----------------------------------
If you want to create a border around the image, something like a photo frame, you can use
**cv2.copyMakeBorder()**. But it has more applications for convolution operation, zero
**cv.copyMakeBorder()**. But it has more applications for convolution operation, zero
padding etc. This function takes following arguments:
- **src** - input image
@@ -152,34 +152,34 @@ padding etc. This function takes following arguments:
directions
- **borderType** - Flag defining what kind of border to be added. It can be following types:
- **cv2.BORDER_CONSTANT** - Adds a constant colored border. The value should be given
- **cv.BORDER_CONSTANT** - Adds a constant colored border. The value should be given
as next argument.
- **cv2.BORDER_REFLECT** - Border will be mirror reflection of the border elements,
- **cv.BORDER_REFLECT** - Border will be mirror reflection of the border elements,
like this : *fedcba|abcdefgh|hgfedcb*
- **cv2.BORDER_REFLECT_101** or **cv2.BORDER_DEFAULT** - Same as above, but with a
- **cv.BORDER_REFLECT_101** or **cv.BORDER_DEFAULT** - Same as above, but with a
slight change, like this : *gfedcb|abcdefgh|gfedcba*
- **cv2.BORDER_REPLICATE** - Last element is replicated throughout, like this:
- **cv.BORDER_REPLICATE** - Last element is replicated throughout, like this:
*aaaaaa|abcdefgh|hhhhhhh*
- **cv2.BORDER_WRAP** - Can't explain, it will look like this :
- **cv.BORDER_WRAP** - Can't explain, it will look like this :
*cdefgh|abcdefgh|abcdefg*
- **value** - Color of border if border type is cv2.BORDER_CONSTANT
- **value** - Color of border if border type is cv.BORDER_CONSTANT
Below is a sample code demonstrating all these border types for better understanding:
@code{.py}
import cv2
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
BLUE = [255,0,0]
img1 = cv2.imread('opencv-logo.png')
img1 = cv.imread('opencv-logo.png')
replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
constant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)
replicate = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REPLICATE)
reflect = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT)
reflect101 = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT_101)
wrap = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_WRAP)
constant= cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
@@ -6,12 +6,12 @@ Goal
- Learn several arithmetic operations on images like addition, subtraction, bitwise operations
etc.
- You will learn these functions : **cv2.add()**, **cv2.addWeighted()** etc.
- You will learn these functions : **cv.add()**, **cv.addWeighted()** etc.
Image Addition
--------------
You can add two images by OpenCV function, cv2.add() or simply by numpy operation,
You can add two images by OpenCV function, cv.add() or simply by numpy operation,
res = img1 + img2. Both images should be of same depth and type, or second image can just be a
scalar value.
@@ -23,7 +23,7 @@ For example, consider below sample:
>>> x = np.uint8([250])
>>> y = np.uint8([10])
>>> print( cv2.add(x,y) ) # 250+10 = 260 => 255
>>> print( cv.add(x,y) ) # 250+10 = 260 => 255
[[255]]
>>> print( x+y ) # 250+10 = 260 % 256 = 4
@@ -44,20 +44,20 @@ By varying \f$\alpha\f$ from \f$0 \rightarrow 1\f$, you can perform a cool trans
another.
Here I took two images to blend them together. First image is given a weight of 0.7 and second image
is given 0.3. cv2.addWeighted() applies following equation on the image.
is given 0.3. cv.addWeighted() applies following equation on the image.
\f[dst = \alpha \cdot img1 + \beta \cdot img2 + \gamma\f]
Here \f$\gamma\f$ is taken as zero.
@code{.py}
img1 = cv2.imread('ml.png')
img2 = cv2.imread('opencv-logo.png')
img1 = cv.imread('ml.png')
img2 = cv.imread('opencv-logo.png')
dst = cv2.addWeighted(img1,0.7,img2,0.3,0)
dst = cv.addWeighted(img1,0.7,img2,0.3,0)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv.imshow('dst',dst)
cv.waitKey(0)
cv.destroyAllWindows()
@endcode
Check the result below:
@@ -76,31 +76,31 @@ ROI as we did in last chapter. But OpenCV logo is a not a rectangular shape. So
bitwise operations as below:
@code{.py}
# Load two images
img1 = cv2.imread('messi5.jpg')
img2 = cv2.imread('opencv-logo.png')
img1 = cv.imread('messi5.jpg')
img2 = cv.imread('opencv-logo.png')
# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols ]
# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)
# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
img1_bg = cv.bitwise_and(roi,roi,mask = mask_inv)
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)
img2_fg = cv.bitwise_and(img2,img2,mask = mask)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
dst = cv.add(img1_bg,img2_fg)
img1[0:rows, 0:cols ] = dst
cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv.imshow('res',img1)
cv.waitKey(0)
cv.destroyAllWindows()
@endcode
See the result below. Left image shows the mask we created. Right image shows the final result. For
more understanding, display all the intermediate images in the above code, especially img1_bg and
@@ -115,4 +115,4 @@ Exercises
---------
-# Create a slide show of images in a folder with smooth transition between images using
cv2.addWeighted function
cv.addWeighted function
@@ -10,7 +10,7 @@ So in this chapter, you will learn
- To measure the performance of your code.
- Some tips to improve the performance of your code.
- You will see these functions : **cv2.getTickCount**, **cv2.getTickFrequency** etc.
- You will see these functions : **cv.getTickCount**, **cv.getTickFrequency** etc.
Apart from OpenCV, Python also provides a module **time** which is helpful in measuring the time of
execution. Another module **profile** helps to get detailed report on the code, like how much time
@@ -21,34 +21,34 @@ ones, and for more details, check links in **Additional Resouces** section.
Measuring Performance with OpenCV
---------------------------------
**cv2.getTickCount** function returns the number of clock-cycles after a reference event (like the
**cv.getTickCount** function returns the number of clock-cycles after a reference event (like the
moment machine was switched ON) to the moment this function is called. So if you call it before and
after the function execution, you get number of clock-cycles used to execute a function.
**cv2.getTickFrequency** function returns the frequency of clock-cycles, or the number of
**cv.getTickFrequency** function returns the frequency of clock-cycles, or the number of
clock-cycles per second. So to find the time of execution in seconds, you can do following:
@code{.py}
e1 = cv2.getTickCount()
e1 = cv.getTickCount()
# your code execution
e2 = cv2.getTickCount()
time = (e2 - e1)/ cv2.getTickFrequency()
e2 = cv.getTickCount()
time = (e2 - e1)/ cv.getTickFrequency()
@endcode
We will demonstrate with following example. Following example apply median filtering with a kernel
of odd size ranging from 5 to 49. (Don't worry about what will the result look like, that is not our
goal):
@code{.py}
img1 = cv2.imread('messi5.jpg')
img1 = cv.imread('messi5.jpg')
e1 = cv2.getTickCount()
e1 = cv.getTickCount()
for i in xrange(5,49,2):
img1 = cv2.medianBlur(img1,i)
e2 = cv2.getTickCount()
t = (e2 - e1)/cv2.getTickFrequency()
img1 = cv.medianBlur(img1,i)
e2 = cv.getTickCount()
t = (e2 - e1)/cv.getTickFrequency()
print( t )
# Result I got is 0.521107655 seconds
@endcode
@note You can do the same with time module. Instead of cv2.getTickCount, use time.time() function.
@note You can do the same with time module. Instead of cv.getTickCount, use time.time() function.
Then take the difference of two times.
Default Optimization in OpenCV
@@ -57,23 +57,23 @@ Default Optimization in OpenCV
Many of the OpenCV functions are optimized using SSE2, AVX etc. It contains unoptimized code also.
So if our system support these features, we should exploit them (almost all modern day processors
support them). It is enabled by default while compiling. So OpenCV runs the optimized code if it is
enabled, else it runs the unoptimized code. You can use **cv2.useOptimized()** to check if it is
enabled/disabled and **cv2.setUseOptimized()** to enable/disable it. Let's see a simple example.
enabled, else it runs the unoptimized code. You can use **cv.useOptimized()** to check if it is
enabled/disabled and **cv.setUseOptimized()** to enable/disable it. Let's see a simple example.
@code{.py}
# check if optimization is enabled
In [5]: cv2.useOptimized()
In [5]: cv.useOptimized()
Out[5]: True
In [6]: %timeit res = cv2.medianBlur(img,49)
In [6]: %timeit res = cv.medianBlur(img,49)
10 loops, best of 3: 34.9 ms per loop
# Disable it
In [7]: cv2.setUseOptimized(False)
In [7]: cv.setUseOptimized(False)
In [8]: cv2.useOptimized()
In [8]: cv.useOptimized()
Out[8]: False
In [9]: %timeit res = cv2.medianBlur(img,49)
In [9]: %timeit res = cv.medianBlur(img,49)
10 loops, best of 3: 64.1 ms per loop
@endcode
See, optimized median filtering is \~2x faster than unoptimized version. If you check its source,
@@ -115,11 +115,11 @@ working on this issue)*
one or two elements, Python scalar is better than Numpy arrays. Numpy takes advantage when size of
array is a little bit bigger.
We will try one more example. This time, we will compare the performance of **cv2.countNonZero()**
We will try one more example. This time, we will compare the performance of **cv.countNonZero()**
and **np.count_nonzero()** for same image.
@code{.py}
In [35]: %timeit z = cv2.countNonZero(img)
In [35]: %timeit z = cv.countNonZero(img)
100000 loops, best of 3: 15.8 us per loop
In [36]: %timeit z = np.count_nonzero(img)