Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Python & OpenCV: Tutoriais e Documentação, Traduções de Programação Linear

OpenCV apresenta um novo conjunto de tutoriais que o guiarão através de várias funções disponíveis no OpenCV-Python. Este guia é focado principalmente na versão OpenCV 3.x (embora a maioria dos tutoriais funcione também com o OpenCV 2.x). Um conhecimento prévio sobre Python e Numpy é necessário antes de começar porque não serão cobertos neste guia. Especialmente, um bom conhecimento sobre Numpy é necessário para escrever códigos otimizados no OpenCV-Python.

Tipologia: Traduções

2019

Compartilhado em 06/12/2019

yam-fontalba
yam-fontalba 🇧🇷

1 documento

1 / 269

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
Python &OpenCV
Tutoriais e Documentação
Tradução Alexandre H.
Agosto, 2017
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Python & OpenCV: Tutoriais e Documentação e outras Traduções em PDF para Programação Linear, somente na Docsity!

Python & OpenCV

Tutoriais e Documentação

Tradução Alexandre H.

Agosto, 2017

Sumario

  • 1 OpenCV-Python Tutorials
    • 1.1 Introduction to OpenCV
    • 1.2 Gui Features in OpenCV
    • 1.3 Core Operations
    • 1.4 Image Processing in OpenCV
    • 1.5 Feature Detection and Description
    • 1.6 Video Analysis
    • 1.7 Camera Calibration and 3D Reconstruction
    • 1.8 Machine Learning
    • 1.9 Computational Photography
    • 1.10 Object Detection
    • 1.11 OpenCV-Python Bindings
  • 2 Indices and tables

Nesta seção você aprenderá diferentes funções de processamen- to de imagem dentro do OpenCV.

  • Feature Detection and Description

Nesta seção, você aprenderá sobre detectores de recursos e descritores

  • Video Analysis

Nesta seção, você aprenderá diferentes técnicas para trabalhar com vídeos como rastreamento de objeto etc.

  • Camera Calibration and 3D Reconstruction

Nesta seção, aprenderemos sobre a calibração da câmera, imagem estéreo etc.

  • Machine Learning

Nesta seção você aprenderá diferentes funções de processamen- to de imagem dentro do OpenCV.

  • Computational Photography

Nesta seção, você aprenderá diferentes técnicas de fotografia computacional, como o desmembramento de imagem etc.

  • Object Detection

4 Chapter 1. OpenCV-Python Tutorials

Nesta seção, você irá analisar técnicas de detecção como detecção de rosto etc.

  • OpenCV-Python Bindings

Nesta seção, veremos como as ligações OpenCV-Python são geradas

Introdução aos Tutoriais OpenCV-Python

OpenCV

O OpenCV foi iniciado na Intel em 1999 por Gary Bradsky e o primeiro lançamento foi lançado em 2000. Vadim Pisarevsky juntou-se a Gary Bradsky para gerenciar a equipe de software OpenCV da Intel. Em 2005, o OpenCV foi usado em Stanley, o veículo que venceu o DARPA Grand Challenge 2005. Mais tarde, seu desenvolvimento ativo continuou sob o apoio da Willow Garage, com Gary Bradsky e Vadim Pisarevsky liderando o projeto. Agora, o OpenCV suporta muitos algoritmos relacionados à visão de computador e à aprendizagem de máquinas e está expandindo dia a dia.

Atualmente, o OpenCV suporta uma grande variedade de linguagens de programação como C ++, Python, Java etc e está disponível em diferentes plataformas, incluindo Windows, Linux, OS X, Android, iOS, etc. Além disso, interfaces baseadas em CUDA e OpenCL também estão em desenvolvimento ativo para alta - operações de velocidade de GPU.

OpenCV-Python é a Python API do OpenCV. Combina as melhores qualidades da OpenCV C ++ API e Python

OpenCV-Python

Python é uma linguagem de programação de uso geral, iniciada por Guido van Rossum, que se tornou muito popular em pouco tempo, principalmente por causa da simplicidade e legibilidade do código. Ele permite ao programador expressar suas idéias em menos linhas de código sem reduzir a legibilidade.

Comparado com outros idiomas como o C / C ++, o Python é mais lento. Mas outra característica impor- tante do Python é que ele pode ser facilmente estendido com C / C ++. Esse recurso nos ajuda a escrever códigos computacionalmente intensivos em C / C ++ e criar um wrapper Python para que possamos usar esses wrappers como módulos Python. Isso nos dá duas vantagens: em primeiro lugar, nosso código é tão rápido quanto o código C / C ++ original (uma vez que é o código C ++ atual que trabalha em segundo plano) e, em segundo lugar, é muito fácil codificar em Python. É assim que o OpenCV-Python funciona, é um wrapper do Python em torno da implementação original do C ++.

E o apoio de Numpy torna a tarefa mais fácil. Numpy é uma biblioteca altamente otimizada para oper- ações numéricas. Ele fornece uma sintaxe de estilo MATLAB. Todas as estruturas da matriz OpenCV são convertidas em matrizes Numpy. Então, qualquer operação que você possa fazer em Numpy, você pode combiná-la com OpenCV, o que aumenta o número de armas em seu arsenal. Além disso, várias outras bibliotecas como SciPy, Matplotlib que suporta Numpy podem ser usadas com isso.

Portanto, o OpenCV-Python é uma ferramenta apropriada para a prototipagem rápida de problemas de visão por computador.

OpenCV-Python Tutorials

O OpenCV apresenta um novo conjunto de tutoriais que o guiarão através de várias funções disponíveis no OpenCV-Python. Este guia é focado principalmente na versão OpenCV 3.x (embora a maioria dos tutoriais funcione também com o OpenCV 2.x).

Um conhecimento prévio sobre Python e Numpy é necessário antes de começar porque não serão cober- tos neste guia. Especialmente, um bom conhecimento sobre Numpy é necessário para escrever códigos otimizados no OpenCV-Python.

Este tutorial foi iniciado por Abid Rahman K. como parte do programa Google Summer of Code 2013, sob a orientação de Alexander Mordvintsev.

OpenCV Needs You !!!

1.1. Introduction to OpenCV 7

E essa será uma boa tarefa para os freshers que começam a contribuir com projetos open source. Apenas garfo o OpenCV no github, faça as correções necessárias e envie um pedido de tração para o OpenCV. Os desenvolvedores do OpenCV verificarão seu pedido de tração, darão feedback importante e, uma vez que aprovarão o avaliador, ele será incorporado ao OpenCV. Então você se torna um colaborador de código aberto. Similar é o caso com outros tutoriais, documentação etc. À medida que novos módulos são adicionados ao OpenCV-Python, este tutorial terá que ser expandido. Então, aqueles que conhecem algoritmos particulares podem escrever um tutorial que inclui uma teoria básica do algoritmo e um código que mostra o uso básico do algoritmo e submete-o ao OpenCV. Lembre-se, juntos podemos fazer deste projeto um grande sucesso!

Contribuicoes

Abaixo está a lista de contribuidores que enviaram tutoriais para o OpenCV-Python.

  1. Alexander Mordvintsev (GSoC-2013 mentor)
  2. Abid Rahman K. (GSoC-2013 intern)

Recursos Adicionais

  1. Um guia rápido para Python- A Byte of Python
  2. Basic Numpy Tutorials
  3. Numpy Examples List
  4. OpenCV Documentation
  5. OpenCV Forum

Install OpenCV-Python in Windows

Objetivos

In this tutorial

  • Aprenderemos a configurar o OpenCV-Python no seu sistema Windows.

As etapas abaixo são testadas em uma máquina Windows 7-64 bit com Visual Studio 2 010 e Visual Studio 201 2. As capturas de tela mostram VS2 01 2.

Instalando o OpenCV a partir de binários pré-compilados

  1. Abaixo dos pacotes Python devem ser baixados e instalados em suas localidades padrão. 1.1. Python-2.7.x. 1.2. Numpy. 1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials). 2.Instale todos os pacotes em suas localidades padrão. Python será instalado em C: / Python27 /.
  2. Após a instalação, abra Python IDLE. Digite importação numpy e certifique-se de que Numpy esteja trabalhando bem.
  3. Baixe a versão OpenCV mais recente do site sourceforge e clique duas vezes para extraí-la. 5 .Va para opencv / build / python / 2.7 pasta.

8 Chapter 1. OpenCV-Python Tutorials

7.4. It will open a new window to select the compiler. Choose appropriate compiler (here, Visual Studio 11) and click Finish.

7.5. Wait until analysis is finished.

  1. You will see all the fields are marked in red. Click on the WITH field to expand it. It decides what extra features you need. So mark appropriate fields. See the below image:

10 Chapter 1. OpenCV-Python Tutorials

  1. Now click on BUILD field to expand it. First few fields configure the build method. See the below image:

1.1. Introduction to OpenCV 11

  1. Now click on ENABLE field to expand it. Make sure ENABLE_SOLUTION_FOLDERS is unchecked (So- lution folders are not supported by Visual Studio Express edition). See the image below:

1.1. Introduction to OpenCV 13

  1. Also make sure that in the PYTHON field, everything is filled. (Ignore PYTHON_DEBUG_LIBRARY). See image below:
  2. Finally click the Generate button.
  3. Now go to our opencv/build folder. There you will find OpenCV.sln file. Open it with Visual Studio.
  4. Check build mode as Release instead of Debug.
  5. In the solution explorer, right-click on the Solution (or ALL_BUILD) and build it. It will take some time to finish.
  6. Again, right-click on INSTALL and build it. Now OpenCV-Python will be installed.

14 Chapter 1. OpenCV-Python Tutorials

Installing OpenCV from source

Compiling from source may seem a little complicated at first, but once you succeeded in it, there is nothing compli- cated.

First we will install some dependencies. Some are compulsory, some are optional. Optional dependencies, you can leave if you don’t want.

Compulsory Dependencies

We need CMake to configure the installation, GCC for compilation, Python-devel and Numpy for creating Python extensions etc.

yum install cmake yum install python-devel numpy yum install gcc gcc-c++

Next we need GTK support for GUI features, Camera support (libdc1394, libv4l), Media Support (ffmpeg, gstreamer) etc.

yum install gtk2-devel yum install libdc1394-devel yum install libv4l-devel yum install ffmpeg-devel yum install gstreamer-plugins-base-devel

Optional Dependencies

Above dependencies are sufficient to install OpenCV in your fedora machine. But depending upon your requirements, you may need some extra dependencies. A list of such optional dependencies are given below. You can either leave it or install it, your call :)

OpenCV comes with supporting files for image formats like PNG, JPEG, JPEG2000, TIFF, WebP etc. But it may be a little old. If you want to get latest libraries, you can install development files for these formats.

yum install libpng-devel yum install libjpeg-turbo-devel yum install jasper-devel yum install openexr-devel yum install libtiff-devel yum install libwebp-devel

Several OpenCV functions are parallelized with Intel’s Threading Building Blocks (TBB). But if you want to en- able it, you need to install TBB first. ( Also while configuring installation with CMake, don’t forget to pass -D WITH_TBB=ON. More details below.)

yum install tbb-devel

OpenCV uses another library Eigen for optimized mathematical operations. So if you have Eigen installed in your sys- tem, you can exploit it. ( Also while configuring installation with CMake, don’t forget to pass -D WITH_EIGEN=ON. More details below.)

yum install eigen3-devel

16 Chapter 1. OpenCV-Python Tutorials

If you want to build documentation ( Yes, you can create offline version of OpenCV’s complete official documentation in your system in HTML with full search facility so that you need not access internet always if any question, and it is quite FAST!!! ), you need to install Sphinx (a documentation generation tool) and pdflatex (if you want to create a PDF version of it). ( Also while configuring installation with CMake, don’t forget to pass -D BUILD_DOCS=ON. More details below.)

yum install python-sphinx yum install texlive

Downloading OpenCV

Next we have to download OpenCV. You can download the latest release of OpenCV from sourceforge site. Then extract the folder.

Or you can download latest source from OpenCV’s github repo. (If you want to contribute to OpenCV, choose this. It always keeps your OpenCV up-to-date). For that, you need to install Git first.

yum install git git clone https://github.com/Itseez/opencv.git

It will create a folder OpenCV in home directory (or the directory you specify). The cloning may take some time depending upon your internet connection.

Now open a terminal window and navigate to the downloaded OpenCV folder. Create a new build folder and navigate to it.

mkdir build cd build

Configuring and Installing

Now we have installed all the required dependencies, let’s install OpenCV. Installation has to be configured with CMake. It specifies which modules are to be installed, installation path, which additional libraries to be used, whether documentation and examples to be compiled etc. Below command is normally used for configuration (executed from build folder).

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..

It specifies that build type is “Release Mode” and installation path is /usr/local. Observe the -D before each option and .. at the end. In short, this is the format:

cmake [-D ] [-D ] ..

You can specify as many flags you want, but each flag should be preceded by -D.

So in this tutorial, we are installing OpenCV with TBB and Eigen support. We also build the documentation, but we exclude Performance tests and building samples. We also disable GPU related modules (since we use OpenCV-Python, we don’t need GPU related modules. It saves us some time).

(All the below commands can be done in a single cmake statement, but it is split here for better understanding.)

  • Enable TBB and Eigen support:

cmake -D WITH_TBB=ON -D WITH_EIGEN=ON ..

1.1. Introduction to OpenCV 17

-- PdfLaTeX compiler: /usr/bin/pdflatex

-- Tests and samples: -- Tests: NO -- Performance tests: NO -- C/C++ Examples: NO

Many other flags and settings are there. It is left for you for further exploration.

Now you build the files using make command and install it using make install command. make install should be executed as root.

make su make install

Installation is over. All files are installed in /usr/local/ folder. But to use it, your Python should be able to find OpenCV module. You have two options for that.

  1. Move the module to any folder in Python Path : Python path can be found out by entering import sys;print sys.path in Python terminal. It will print out many locations. Move /usr/local/lib/ python2.7/site-packages/cv2.so to any of this folder. For example,

su mv /usr/local/lib/python2.7/site-packages/cv2.so /usr/lib/python2.7/ ˓→site-packages

But you will have to do this every time you install OpenCV.

  1. Add ‘‘/usr/local/lib/python2.7/site-packages‘‘ to the PYTHON_PATH: It is to be done only once. Just open ~/.bashrc and add following line to it, then log out and come back.

export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages

Thus OpenCV installation is finished. Open a terminal and try import cv2.

To build the documentation, just enter following commands:

make docs make html_docs

Then open opencv/build/doc/_html/index.html and bookmark it in the browser.

Additional Resources

Exercises

  1. Compile OpenCV from source in your Fedora machine.

Gui Features in OpenCV

  • Getting Started with Images

1.2. Gui Features in OpenCV 19

Learn to load an image, display it and save it back

  • Getting Started with Videos

Learn to play videos, capture videos from Camera and write it as a video

  • Drawing Functions in OpenCV

Learn to draw lines, rectangles, ellipses, circles etc with OpenCV

  • Mouse as a Paint-Brush

Draw stuffs with your mouse

  • Trackbar as the Color Palette

Create trackbar to control certain parameters

20 Chapter 1. OpenCV-Python Tutorials