Install OpenCV 3 (core + contrib) in Windows & Python 3 environment & Difference between OpenCV 2 and OpenCV 3 & Easy operation check

Introduction

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.

Trends in how to install OpenCV

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.

Installation of OpenCV 3.1.0 (core + opencv_contrib) using pip

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.

Differences between OpenCV 2.4 and OpenCV 3.x

I've noticed some parts of the OpenCV 2.4 sample program running on OpenCV 3.5.

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
```

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

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'
```

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])
```

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)

\ # 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

Easy operation check of OpenCV 3

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.

sample.png ** 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.

Gray.png ** 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.

Take a look at the contents of the image

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_l.png ** 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.

color_gry.png ** 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.

Reference information

I referred to the tutorial below. OpenCV Headquarters Qiita Japanese translation

★ If you want to install matplotlib, Anaconda is still recommended.

to be continued

Next, let's detect the edges of the image. http://qiita.com/olympic2020/items/2c3a2bfefe73ab5c86a4

Recommended Posts

Install OpenCV 3 (core + contrib) in Windows & Python 3 environment & Difference between OpenCV 2 and OpenCV 3 & Easy operation check
Difference between list () and [] in Python
Difference between == and is in python
difference between statements (statements) and expressions (expressions) in Python
Difference between @classmethod and @staticmethod in Python
[python] Difference between variables and self. Variables in class
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
About the difference between "==" and "is" in python
Difference between Ruby and Python in terms of variables
Difference between return, return None, and no return description in Python
Install Python and Flask (Windows 10)
Python install in 2 lines @Windows
Check the operation of Python for .NET in each environment
Python module num2words Difference in behavior between English and Russian
List concatenation method in python, difference between list.extend () and “+” operator
Install CaboCha in Ubuntu environment and call it with Python.
Environment construction of python and opencv
Difference between Ruby and Python split
Difference between java and python (memo)
How to install OpenCV on Cloud9 and run it in Python
(Windows10) Install Linux environment and gnuplot.
Install python2.7 on windows 32bit environment
Install scrapy in python anaconda environment
Build and install OpenCV on Windows
Windows10: Install MeCab library in python
Difference in how to write if statement between ruby ​​and python
Check and move directories in Python
Difference between python2 series and python3 series dict.keys ()
install tensorflow in anaconda + python3.5 environment
Build and try an OpenCV & Python environment in minutes using Docker
Install pip in Serverless Framework and AWS Lambda with Python environment
Install Python development environment on Windows 10
Transcendental simple and clear! !! Difference between single quotes and double quotes in Python
[Python] Difference between function and method
File open function in Python3 (difference between open and codecs.open and speed comparison)
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Mouse operation using Windows API in Python
Differences in authenticity between Python and JavaScript
Differences between Ruby and Python in scope
Using venv in Windows + Docker environment [Python]
Build Python3 and OpenCV environment on Ubuntu 18.04
Differences in syntax between Python and Java
Check and receive Serial port in Python (Port check)
Difference between PHP and Python finally and exit
How to check opencv version in python
[Python] Difference between class method and static method
Find and check inverse matrix in Python
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
Differences in multithreading between Python and Jython
Python garbled in Windows + Git Bash environment
Difference in writing method to read external source code between Ruby and Python
Install and run Python3.5 + NumPy + SciPy on Windows 10
Install python package in personal environment on Ubuntu
Install the python package in an offline environment
Install gensim in conda environment (and also install mecab)
Super easy! Python + Flask environment in Docker quickly
[Python] How to install OpenCV on Anaconda [Windows]
Install ZIP version Python and pip on Windows 10