OpenCV 2 Computer Vision Application Programming Cookbook / Изучаем OpenCV

→When the cv::Mat object goes out of scope, the memory allocated is automatically released.
This is very convenient because you avoid having problems with memory leaks. Moreover, the
cv::Mat class implements reference counting and shallow copy such that when an image
is assigned to another one, the image data (that is the pixels) is not copied, and both images
will point to the same memory block. This also applies to images passed by value or returned
by value. A reference count is kept such that the memory will be released only when all of the
references to the image will be destructed. If you wish to create an image that will contain a new
copy of the original image, you will use the method copyTo(). You can test this behavior by
declaring a few extra images in the example of this project, as follows:
0 Когда объект cv:Mat выходит из области видения он автоматически удаляется из памяти. Это очень удобно, так как помогает избежать утечек памяти. Так же, класс cv:Mat поддерживает подсчет ссылок, и скрытое копирование когда изображение присваивается другому, тогда две переменных указывают на один и тот же участок памяти с изображением. Подсчет ссылок работает так, что очищает память с изображением, когда больше ничто не указывает на это изображение. Когда вы заходите создать копию оригинального изображения, то используйте метод copyTo().
→In this case, you also need to specify the type of each matrix element, here CV_8U which
corresponds to 1-byte pixel images. Letter U means unsigned. You can also declare
signed numbers by using the letter S. For a color image, you would specify three channels
(CV_8UC3). You can also declare integers (signed or unsigned) of size 16 and 32 (for example,
CV_16SC3). You also have access to 32-bit and 64-bit floating point numbers (for example,
CV_32F).
0 В этом случае так же необходимо задать тип каждого элемента матрицы, наше CV_8U в данном случае означает, что каждому пикселю изображения отвечает один байт. Буква U означает беззнаковый. Так же можно объявить числа со знаком используя букву S. Для цветного изображения необходимо использовать три канала (CV_8UC3). Так же можно задать целое число (со знаком или нет) размера 16 и 32 (например, CV_16SC3). Так же есть возможность доступа к 32-х и 64-х битным числам с плавающей точкой (например, CV_32F).
→The class cv::Mat is the data structure used to hold your images (and obviously other matrix
data). By default, they have a zero size but you can also specify an initial size:
0 Класс cv::Mat - это структура данных, которая используется для хранения ваших изображений (и других данных матриц). По умолчанию, он имеет нулевой размер, но можно указать размер при вызове конструктура:
→Alternatively, prefix all OpenCV class and function names by the namespace specification that
is cv::, as we did in this recipe.
0 Или, использовать ко всем классам и функциям OpenCV префикс cv::, как в этой книге.
→All classes and functions defined in the C++ API of OpenCV are defined within the name space
cv. You have two options to access them. First, precede the main function definition by the
following declaration:
0 Все классы и функции определенные в API OpenCV на языке С++ находятся в пространстве имен cv. Есть две возможности доступа к ним. Первый - это определить перед главной функций следующее определение:
→The file extension determines which codec will be used to save the image.
0 Расширение файла определяется кодеком, который использовался для сохранения вашего изображения:
→You can then see both the input and output images displayed on two distinct windows. Finally,
you will probably want to save the processed image on your disk. This is done using the
following highgui function:
0 Теперь можно увидеть входящее и выходящее изображение, которые отображены в двух разных окнах. Так же можно сохранить результат обработки (изображение) на жесткий диск в виде файла. Используем функцию модуля highgui для этого:
→Since it is a console window that will terminate at the end of the main function, we add an
extra highgui method to wait for a user key before ending the program:
0 Так как это консольное окно завершится вместе с функцией main, то добавим специальный метод модуля highgui для ожидания нажатия пользователем какой нибудь клавиши:
→And the result is displayed on another window:
0 И отобразим результат в отдельном окне:
→Now, you would normally apply some processing to the image. OpenCV offers a wide selection
of processing functions, and several of them are explored in this book. Let's start with a
very simple one that will simply flip the image horizontally. Several image transformations in
OpenCV can be performed in-place, meaning that the transformation is applied directly on the
input image (no new image being created). This is the case of the flipping method. However,
we can always create another matrix to hold the output result and that is what we will do:
0 Теперь можно применить обработчики к этому изображению. OpenCV предлагает много функций обработчиков, и о некоторых из них рассказывается в этой книге. Давайте начнем с простого отображения изображения в горизонтальном отображении. Некоторые трансформации изображений OpenCV могут быть применены на месте, т.е. не прибегая к созданию новой переменной-изображения. Тем не менее, у нас всегда есть возможность создать новую переменную, что бы отобразить изображение, и мы это сделаем:
→The member variable data is in fact a pointer to the allocated memory block that will contain
the image data. It is simply set to 0 when no image has been read. The first thing you might
want to do with this image is to display it. You do it using the highgui module provided by
OpenCV. You start by declaring the window on which you want to display images, and then you
specify the image to be shown on this special window:
0 Поле data в переменной на самом деле являются указателем на блок памяти, в котором находится изображение. В случае ошибки чтения туда устанавливается 0. Самое простое действие, которое можно сделать с этим изображением - это отобразить его. Для этого необходимо использовать модуль highgui. Прежде всего, необходимо объявить окно, в котором мы хотим отобразить изображение, а потом указать какое изображение мы хотим отобразить в этом окне:
→You are now ready to use this image. However, you should first check if the image has been
correctly read (an error will occur if the file is not found or if the file is corrupted, or is not a
recognizable format). The validity of the image is tested by:
0 Теперь можно использовать это изображения. Но, тем не менее, необходимо проверить считалось ли изображение правильно, не возникло ли никаких ошибок при считывании (например, файл не найден, поврежден, или неизвестный формат). Проверка происходит следующим образом:
→Next a simple call to the reading function will read an image from file, decode it, and allocate
the memory:
0 Следующий шаг - это простой вызов функции, которая считает изображения из файла, декодирует его в понятный компьютеру формат, и разместит в памяти:
→This definition creates an image of size 0 by 0. This can be confirmed by calling the cv::Mat
method size() that allows you to read the current size of this image. It returns a structure
containing the height and width of the image:
0 По умолчанию созданное изображение имеет размер 0 на 0 пикселей. Можно вызвать метод size() класса cv::Mat, что-бы получить текущие размеры изображения. Метод вернет структуру, которая будет хранить высоту (height) и ширину (width) изображения:
→The first thing to do is to declare a variable that will hold the image. Under OpenCV 2, you
define an object of class cv::Mat.
0 Первое, что необходимо сделать это объявить переменную, которая будет хранить изображение. В OpenCV 2 за это отвечает класс cv::Mat.
→Using either MS Visual Studio or Qt, create a new console application with a main function
ready to be filled. See the first two recipes on how to proceed.
0 Используя MS Visual Studio или Qt, создайте новое консольное приложение с функцией main, которую далее мы заполним. Смотрите первые два пункта, что бы сделать это.
→The new property sheet is then added once we click on Add. We now need to edit it. Simply
double-click on the property sheet's name and select VC++ Directories, as seen here:
0 Новый шаблон бует добавлен после нажатия на Add. Теперь необходимо редактировать его. Простой двойной клик по имени шаблона и выберите VS++ Directories, как показано ниже:
→In Visual C++ 2010, a property sheet is an XML file that describes your project settings. We
will now create a new one by right-clicking on the Debug | Win32 node of the project, and by
selecting the Add New Project Property Sheet option (as seen in the following screenshot):
0 В Visual C++ 2010 шаблон - это XML файл, который описывает ваши настройки проекта. Теперь необходимо создать новый правым кликом по Debug | Win32 ветке вашего проекта и выбрать Add New Project Property Sheet (как показано на скриншоте ниже):
→But first, to be able to compile and run your future OpenCV application, you need to tell Visual
C++ where to find the OpenCV libraries and include files. Since you will probably create several
OpenCV projects in the future, the best option is to create a Property Sheet that you will be
able to reuse from project to project. This is done through the Property Manager. If it is not
already visible in your current IDE, you can access it from the View menu.
0 Но сначала, для компилирования и создания ваших OpenCV приложений необходимо "показать" Visual Studio где находится библиотека OpenCV и подключаемые файлы. Лучшим вариантом будет создание Property Sheet (шаблон), что бы было удобнее в будущем создавать проекты.
→You need to specify where your want to create your project, and what name you want to give to
your project. There is also an option for creating or not creating a directory for the solution (the
bottom-right checkbox). If you check this option, an additional directory will be created (with
the name you specify) that will contain your solution directory. If you simply leave this option
unchecked, a solution file (extension .sln) will still be created, but this one will be contained
within the same (single) project directory. Click on OK and then Next to go to the Application
Settings window of the Win32 Application Wizard. As seen in the following screenshot, a
number of options are offered there. We will simply create an empty project.
0 Вам необходимо указать где необходимо создать проект, и под каким названием. Так же есть настройка, что позволяет выбирать - создавать папку для решения или нет. Если выбрать эту настройку, то будет создана папка с названием, которое вы задали, в папке с решением. Если это не будет сделано, то файл решения (разрешение .sln) все равно будет создано, но все файлы будут находиться в одной папке в неупорядоченном виде. Нажмите на ОК и Next, что бы перейти в следующему окну Application Settings. Как видно на следующем скриншоте, предлагается несколько вариантов создания. Мы же создадим пустой проект.
Резюме
Пол:
мужчина
Родной язык:
русский
С нами:
с 2 июля 2013 г. (4857 дней)
Не является членом клуба.
Деятельность:
124 версии перевода с общим рейтингом 0
1 комментарий
Написать oneassasin личное сообщение