OpenCV (Open Source Computer Vision Library) is a collection of BSD-licensed video / image processing libraries. There are many algorithms for image filtering, template matching, object recognition, video analysis, machine learning, and more.
Example of motion tracking using OpenCV (OpenCV Google Summer of Code 2015) https://www.youtube.com/watch?v=OUbUFn71S4s
pip is a Python package management tool that has been one of the Python standard libraries since Python 3.3. This page describes how to build an environment to try OpenCV by adding only OpenCV package and PyNum package to Python 3.5.
It seems that the recent trend is to install in the order of Anaconda → OpenCV. Easy introduction of python3 and OpenCV3
However, I didn't really understand the impact on my environment without Anaconda, such as "Anaconda is huge, isn't it?" Or "What happens to the pip environment so far when Anaconda is installed?" I tried to install OpenCV with.
Survey target environment
Result By adding a simple module using pip, the above environment worked without problems.
** Download ** From the link (http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv) opencv_python-3.1. Download 0 + contrib_opencl-cp35-cp35m-win32.whl.
** Install **
Install with the pip install command.
--For 32-bit Python
bash $ pip install opencv_python-3.1.0+contrib_opencl-cp35-cp35m-win32.whl
--For 64-bit Python
bash $ pip install opencv_python-3.1.0+contrib_opencl-cp35-cp35m-win_amd64.whl
** Check version **
$ python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'3.1.0'
>>> exit()
** Various samples of OpenCV 3.1.0 **
--Download
Download from GitHub of OpenCV.
https://github.com/opencv
--Deployment
opencv → releases → OpenCV 3.1 → Downloads → opencv-3.1.0.exe → Execute → Specify the extraction folder → Extract
Samples (photos, videos) are stored below.
opencv\sources\samples\data
** Install NumPy ** When using OpenCV with Python, the matrix calculation / numerical calculation library NumPy is often required, so install it as well.
$ conda install numpy
** Anaconda + OpenCV with opencv_ontrib ** For reference, I will also explain how to install OpenCV with opencv_contrib on Anaconda. After installing Anaconda, you can install OpenCV with opencv_contrib below.
conda install -c https://conda.anaconda.org/menpo opencv3
The installed OpenCV library is expanded in the following directory.
> ~/Anaconda3/pkgs/opencv3-3.1.0-py35_0/Library/bin
It turns out that the optical flow library (opencv_optflow310.lib) that can also be used for deep learning library (opencv_dnn310.lib) and Deepflow is installed. I will.
I've noticed some parts of the OpenCV 2.4 sample program running on OpenCV 3.5.
** cv2.cv is gone ** In OpenCV 2.4
import cv2.cv as cv
Code often appeared at the beginning of the script, but it seems that it is no longer OpenCV 3.x. When I write this in OpenCV 3.x, I get this error.
```
Traceback (most recent call last):
File "~\sample.py", line 4, in <module>
import cv2.cv as cv
ImportError: No module named 'cv2.cv'; 'cv2' is not a package
```
** Method name changed **
For example, OpenCV2.4's cv2.cv.CV_FOURCC
has been changed to cv2.VideoWriter_fourcc
in OpenCV3.1.
import cv2.cv as cv
cv.CV_FOURCC('X', 'V', 'I', 'D')
import cv2
cv2.VideoWriter_fourcc(*'XVID')
If you need to make a program that works in common with OpenCV2.x and OpenCV3.x, you have to define the equivalent method by yourself as follows. Example)
```opencv2.4_3.1.py
# cv2.cv.CV_FOURCC, cv2.VideoWriter_fourcc
def cv_fourcc(c1, c2, c3, c4):
return (ord(c1) & 255) + ((ord(c2) & 255) << 8) + \
((ord(c3) & 255) << 16) + ((ord(c4) & 255) << 24)
cv_fourcc('X', 'V', 'I', 'D')
```
Or, if the video codec is fixed in the program, this is OK.
```opencv3.1.py
XVID = 0x44495658
````
Other codecs are summarized in this article (the chapter "How to specify a codec" in the middle), so please refer to those who need it. Codec and FOURCC correspondence table
** There is a method moved to the non-standard library opencv_contrib **
Typical ones are ʻupdateMotionHistory (...)and
calcGlobalOrientation (...)`.
This was the case with OpenCV 2.4,
cv2.updateMotionHistory(...)
cv2.calcGlobalOrientation(...)
In OpenCV 3.x, I moved to motempl of opencv_contrib, so I need to install opencv_contrib and write as follows.
```
cv2.motempl.updateMotionHistory(...)
cv2.motempl.calcGlobalOrientation(...)
```
As with OpenCV 2.x, if you write cv2.updateMotionHistory (...)
for OpenCV 3.x, you will get the following error:
```
Traceback (most recent call last):
File "~\sample.py", line 10, in <module>
cv2.updateMotionHistory(...)
AttributeError: module 'cv2' has no attribute 'updateMotionHistory'
```
** Some constants have disappeared **
The constant cv2.CV_AA
, which specifies antialiasing when drawing lines and circles, is no longer defined in OpenCV 3.x. If you specify cv2.CV_AA
, the following error will be displayed.
AttributeError: module 'cv2' has no attribute 'CV_AA'
If you specify antialiasing, you can work around this issue by defining constant values directly in your program.
```
CV_AA = 16
```
Also, the constant cv2.CV_PI
, which stores the value of π, is no longer defined in OpenCV 3.x. If you specify cv2.CV_PI
, the following error will be displayed.
```
AttributeError: module 'cv2' has no attribute 'CV_PI'
```
Speaking of the constant π in OpenCV, I think that it is often used for angle conversion such as "degree → radian" and "radian → degree". In fact, Python provides these constants and conversion methods in the standard library. If you use the constant π provided by Python as standard instead of the OpenCV constant π, you can avoid the problem that the constant π is no longer defined in OpenCV 3.x.
```
import math
#Constant π: 3.141592653589793
math.pi
#Degree → radian conversion
math.radians([deg])
#Radian → degree conversion
math.degrees([rad])
```
TypeError: 'int' object is not iterable
The fix was committed to GitHub on April 21, 2016, so it seems that I have to download the latest source code from GitHub and compile it myself. --Question site pointing out bugs (Link) --Site that wrote the solution (Link) --Fixed on GitHub on April 21, 2016 (Link) - Repository for OpenCV's extra modules (Link)
** Tutorial does not work ** --OpenCV 3 for Python tutorial (link) The OpenCV 3 for Python tutorial remains OpenCV 2. Everyone is in trouble because it doesn't work, but it's left unattended. For example, a feature matching tutorial. http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_feature2d/py_matcher/py_matcher.html When I try to run the FLANN based Matcher sample, I get an error on the line below.
> matches = flann.knnMatch(des1,des2,k=2)
>
\ # The following error occurs # error: C:\dev\opencv-3.1.0\modules\python\src2\cv2.cpp:163: error: (-215) The data should normally be NULL! in function NumpyAllocator::allocate
Let's create a program to convert a color image to grayscale with OpenCV 3.
readImage.py
import cv2
filename = "sample.png "
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
cv2.imshow('window title', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Specify the file name in the first argument of imread (filename, flags). The supported file formats are as follows.
format | extension |
---|---|
Windows bitmap | BMP, DIB |
JPEG | JPEG, JPG, JPE |
JPEG 2000 | JP2 |
Portable Network Graphics | PNG |
TIFF | TIFF, TIF |
Portable Anymap Format | PBM, PGM, PPM |
Sun raster format | SR, RAS |
Select the second argument of imread (filename, flags) from the following.
constant | value | meaning |
---|---|---|
cv2.IMREAD_UNCHANGED | -1 | No conversion (also holds alpha channel) |
cv2.IMREAD_GRAYSCALE | 0 | Gray (8bit 1 channel) |
cv2.IMREAD_COLOR | 1 | Color (8bit 3 channels) |
cv2.IMREAD_ANYDEPTH | 2 | Arbitrary depth |
cv2.IMREAD_ANYCOLOR | 3 | Any color |
This time, we will convert from color to gray, so select cv2.IMREAD_GRAYSCALE
.
The first argument of imshow () specifies the title of the window.
** Original image (color): sample.png **
When you execute the script, the image converted from color to black and white will be displayed in a separate window. If you press any key while the window is active (in focus), the window will close and the script will end.
** Grayscale image **
I didn't install Anaconda, but if pip is already installed, OpenCV seems to work with a simple module addition using pip. Also, there seems to be no problem with python3.
OpenCV handles images in units called numpy.ndarray (N-dimensional array) in the Numpy library. The Python standard list connects elements internally with a list, but since ndarray has a fixed length like an array in C language, there are the following differences.
Now, let's see what a 5x2 pixel image like the one below looks like in ndarray.
** Color image **
ndarray.py
import cv2
filename_c = "color.png "
array_c = cv2.imread(filename_c, cv2.IMREAD_COLOR)
print("===== color image array =====")
print(array_c)
print("")
filename_g = "gray.png "
array_g = cv2.imread(filename_g, cv2.IMREAD_GRAYSCALE)
print("===== gray image array =====")
print(array_g)
===== color image array =====
[[[ 36 28 237]
[ 0 0 0]
[ 36 28 237]
[255 255 255]
[ 76 177 34]]
[[ 76 177 34]
[204 72 63]
[127 127 127]
[204 72 63]
[ 36 28 237]]]
In OpenCV, pixel data is stored in the order of BGR. Please note that the order of RGB is standard in the world of the Web. See the link here (http://www.learnopencv.com/why-does-opencv-use-bgr-color-format/) to find out why it's BGR instead of RGB.
** Gray image **
===== gray image array =====
[[138 0 138 255 142]
[142 98 127 98 138]]
You can see that the color image is a three-dimensional array and the gray image is a two-dimensional array.
I referred to the tutorial below. OpenCV Headquarters Qiita Japanese translation
★ If you want to install matplotlib, Anaconda is still recommended.
Next, let's detect the edges of the image. http://qiita.com/olympic2020/items/2c3a2bfefe73ab5c86a4
Recommended Posts