wuffur: переводы
OpenCV 2 Computer Vision Application Programming Cookbook / Изучаем OpenCV
→The input and output images are being displayed on the two highgui windows that we
defined.
defined.
0 Входные и выходные изображения отображаются на двух окнах, выводящихся поверх экрана(highgui), которые мы определили.
→You can now compile and run this program and your 2-button GUI will allow you to select an
image and process it.
image and process it.
0 Теперь вы можете скомпилировать и запустить эту программу и ваш двухкнопочный графический интерфейс GUI позволит вам выбрать изображение и произвести над ним преобразования.
→You then create a new slot by right-clicking on the second button. This second slot will perform
some processing on the selected input image. The following code will simply flip the image:
some processing on the selected input image. The following code will simply flip the image:
0 Вы можете создать новый слот, если нажмёте правой кнопкой мыши по второй кнопке. Этот второй слот произведет некоторые преобразования над выбранным входным изображением. Следующий код просто перевернёт изображение:
→OpenCV code can then be added. The first button opens the source image. This is done by
adding the following code to the corresponding slot method:
adding the following code to the corresponding slot method:
0 OpenCV код может потом быть добавлен. Эта первая кнопка открывает исходное изображение. Это производится при добавлении следующего кода к связанному с ним методу слота:
→Note that we have also included the core.hpp and the highgui.hpp header files. As we
learned in a preceding recipe, we must not forget to edit the project file in order to append the
OpenCV library information.
learned in a preceding recipe, we must not forget to edit the project file in order to append the
OpenCV library information.
0 Отметим, что мы также включили заголовочные файлы core.hpp и highgui.hpp. Как мы уже выучили в предыдущем рецепте(практике), мы теперь должны забыть о том, чтобы редактировать файл проекта, чтобы добавить информацию библиотеки OpenCV.
→In order to be able to display and then process the image, we need to define a cv::Mat class
member variable. This is done in the header file of the MainWindow class. This header now
reads as follows:
member variable. This is done in the header file of the MainWindow class. This header now
reads as follows:
0 Чтобы иметь возможность вывести изображение на экран и затем провести какое-то преобразование над ним, нам нужно опредилить переменную-член класса cv::Mat. Это производится в заголовочном файле класса MainWindow. Так выглядит теперь заголовочный файл:
→Simply select the clicked() signal. This is the one that handles the button pushed events.
By doing this, you will be brought to the mainwindow.cpp file. You will see that a new
method has been added. This is the slot method that is called when the click() signal is
received:
By doing this, you will be brought to the mainwindow.cpp file. You will see that a new
method has been added. This is the slot method that is called when the click() signal is
received:
0 Просто выберете сигнал clicked(). Он управляет событием нажатия кнопки. Когда вы это сделаете, тогда вас перенесёт в файл mainwindow.cpp. Это метод слота, который вызывается при получении сигнала click():
→Note that we also have unchecked the Precompiled header option which is an MS Visual
Studio-specific feature to make the compilation process faster. Since we want to stay within
the ANSI C++ standard, we will not use this option. If you click on Finish, your project will be
created. It is empty for now, but we will add a main file to it soon.
Studio-specific feature to make the compilation process faster. Since we want to stay within
the ANSI C++ standard, we will not use this option. If you click on Finish, your project will be
created. It is empty for now, but we will add a main file to it soon.
0 Заметим, что мы также не отметили опцию заголовков до компиляции, которая является особ MS Visual
Studio--специфической особенностью, делающей процесс компиляции более быстрым. Так как мы хотим оставаться внутри стандарта ANSI C++, то мы не будем использовать эту опцию. Если мы нажмём на кнопку "завершить", тогда наш проект создастся. Пока он ещё пустой, но мы скоро добавим к нему главный файл main.
Studio--специфической особенностью, делающей процесс компиляции более быстрым. Так как мы хотим оставаться внутри стандарта ANSI C++, то мы не будем использовать эту опцию. Если мы нажмём на кнопку "завершить", тогда наш проект создастся. Пока он ещё пустой, но мы скоро добавим к нему главный файл main.
→Let's now add a signal method in order to handle the click button event. Right-click on the
first button and select Go to slot... in the contextual menu. The list of possible signals is then
displayed as seen in the following screenshot:
first button and select Go to slot... in the contextual menu. The list of possible signals is then
displayed as seen in the following screenshot:
0 Добавим теперь сигнальный метод, чтобы управлять событием нажатия на кнопку. Нажмите на правую кнопку мыши по первой кнопке и выберете пункт Go to slot... в контекстном меню. Список возможных сигналов выводится на экран так как показано на следующем скриншоте:
→You can drag-and-drop different widgets on it. Drop two Push Buttons as we did in the
preceding example. You can resize them and resize the window to make it nice. You should
also rename the button labels. Just click on the text and insert the name of your choice.
preceding example. You can resize them and resize the window to make it nice. You should
also rename the button labels. Just click on the text and insert the name of your choice.
0 Также вы можете сюда drag-and-drop'нуть (перетащить) различные виджеты. Положите две кнопки Push, как мы делали в предыдущем премере. Вы можете изменить их размер, и изменить размер окна, чтобы он выглядел хорошо. Вам также следует переименовать кнопки label. Просто нажмите на мышку и вставьте любое имя по вашему выбору.
→Give a name and a location to your project. If you then click on Next, you will see that the
QtGUI Module is checked. Since we do not need other modules, you can click on Finish at
this point. This will create your new project. In addition to the usual project file ( .pro) and
the main.cpp file, you see two mainwindow files defining the class that contains your GUI
window. You will also find a file having the extension .ui, which is the one that describes the
UI layout. In fact, if you double-click on it, you will see the current user interface as seen here:
QtGUI Module is checked. Since we do not need other modules, you can click on Finish at
this point. This will create your new project. In addition to the usual project file ( .pro) and
the main.cpp file, you see two mainwindow files defining the class that contains your GUI
window. You will also find a file having the extension .ui, which is the one that describes the
UI layout. In fact, if you double-click on it, you will see the current user interface as seen here:
0 Задайте имя и место расположения вашего проекта. Если вы затем нажмёте кнопку Next, то увидите что модуль QtGUI проверяется. Так как на не нужно больше других модулей, то поэтому вы можете нажать Finish . Таким образом вы создадите новый проект. Кроме того, чтобы использовать файл проекта ( .pro) и файл main.cpp , вы увидите два файла главных окон (mainwindow), определяющих класс, который содержит ваше GUI окно. Вы также найдёте файл у которого расширение .ui, то самое которое описывает UI вывод(layout). На самом деле, если два раза по нему нажмёте правой кнопкой мыши, то увидите текущий интерфейс как представлено здесь:
→Select Create New Project… and choose Qt GUI Application as seen in the following
screenshot:
screenshot:
0 Выберети в меню Создать новый проект(Create New Project),
и там выберете Qt GUI Application как на следующем скриншоте:
и там выберете Qt GUI Application как на следующем скриншоте:
→Start Qt Creator which we will use to create our GUI application. It is also possible to create a
GUI without this tool, but the use of a visual IDE in which the widgets can simply be dragged
and dropped is the easiest way to build a nice looking GUI.
GUI without this tool, but the use of a visual IDE in which the widgets can simply be dragged
and dropped is the easiest way to build a nice looking GUI.
0 Запускаем Qt Creator, который будем используем для создания GUI приложения. Также можно создать GUI приложение без этого инструмента, но использование графической IDE, в которые виджеты можно просто drag'n'drop'ать самый простой способ создать хорошо выглядящий GUI.
→Qt offers a rich library to build a sophisticated GUI with a professional look. Using Qt Creator,
the process of GUI creation is made easy. This recipe will show you how to build an OpenCV
application with Qt that a user can control using a GUI.
the process of GUI creation is made easy. This recipe will show you how to build an OpenCV
application with Qt that a user can control using a GUI.
0 Qt предоставляет богатую библиотеку, чтобы построить изощрённый графический интерфейс с профессиональным видом. С помощью Qt Creator процесс создания GUI стал простым. Этот рецет покажет вам как построить и создать приложение OpenCV с помощью Qt так, чтобы пользователь мог управлять используя GUI.
→Creating a GUI application using Qt
0 Создание графического интерфейса пользователя GUI с помощью библиотеки Qt
→Remember, you should avoid using this deprecate data structure. Instead, always use
cv::Mat.
cv::Mat.
0 Помните, что вам следует избегать использовать устаревшую структуру данных. Всегда используйте cv::Mat напротив.
→Otherwise, if you need to deallocate the memory pointed by your IplImage structure, you
need to do it explicitly:
need to do it explicitly:
0 Другими словами, если вам нужно разыменовать указатель на структуру IplImage, тогда вам нужно делать это явно:
→The function cvLoadImage is the C-interface function to load images. The second parameter
in the constructor of the cv::Mat object indicates that the data will not be copied (set it to
true if you want a new copy, while false is the default value so it could have been omitted),
that is both IplImage and image4 will share the same image data. You need to be careful
here to not create dangling pointers. For this reason, it is safer to encapsulate the IplImage
pointer into the reference-counting pointer class provided by OpenCV 2:
in the constructor of the cv::Mat object indicates that the data will not be copied (set it to
true if you want a new copy, while false is the default value so it could have been omitted),
that is both IplImage and image4 will share the same image data. You need to be careful
here to not create dangling pointers. For this reason, it is safer to encapsulate the IplImage
pointer into the reference-counting pointer class provided by OpenCV 2:
0 Функция cvLoadImage - это функция си-интерфейса для загрузки изображений. Второй параметр конструктор объекта cv::Mat показывает, что данные не будут скопированы (установите его значение true, если вам нужна новая копия, а значение false можно пропустить потому, что но стоит по-умолчанию), тогда и IplImage, и image4 будут разделять между собой одни и те же данные изображения. Вам нужно быть осторожным, если вы не хотите наделать висячих ссылок. По этой причине, безопаснее инкапсулировать указатель IplImage в ссылочный класс считающий указатели, предоставляемый в OpenCV 2:
→With version 2 of the OpenCV, a new C++ interface has been introduced. Previously, C-like
functions and structures were used (and can still be used). In particular, images were
manipulated using the IplImage structure. This structure was inherited from the IPL library
(that is the Intel Image Processing Library) now integrated with the IPP library (the Intel
Integrated Performance Primitive library). If you use code and libraries that were created with
the old C interface, you might need to manipulate those IplImage structures. Fortunately,
there is a convenient way to convert an IplImage into a cv::Mat object.
functions and structures were used (and can still be used). In particular, images were
manipulated using the IplImage structure. This structure was inherited from the IPL library
(that is the Intel Image Processing Library) now integrated with the IPP library (the Intel
Integrated Performance Primitive library). If you use code and libraries that were created with
the old C interface, you might need to manipulate those IplImage structures. Fortunately,
there is a convenient way to convert an IplImage into a cv::Mat object.
0 С появлением версии 2 OpenCV был представлен новый интерфейс. До этого использовались си-подобные функции и структуры(и все ещё могут использоваться. В частности изображениями можно управлять с помощью структуры. Эта структуры наследуется от библиотеки IPL(это Intel Image Processing Library), теперь интегрированная с библиотекой IPP( Intel Integrated Performance Primitive library). Если вы используете код или библиотеки, созданные с помощью старого интерфейса Си, то вам должно быть было необходимо управлять этими структурами IplImage. К счастью существует удобный способ преобразовать структуру IplImage в объект cv::Mat.
→Here, if a function calls the method of this class, it obtains a shallow copy of the image
attributes. If later, this copy is modified, the class attribute will also be modified which can
affect the subsequent behavior of the class (and vice versa). To avoid these kinds of errors,
you should instead return a copy of the attribute.
attributes. If later, this copy is modified, the class attribute will also be modified which can
affect the subsequent behavior of the class (and vice versa). To avoid these kinds of errors,
you should instead return a copy of the attribute.
0 Здесь, если функция вызывает метод этого класса, он получи поверхностную копию атрибутов изображения. Если потом, это копия будет изменена, то атрибут класса также изменится, что может повлиять на последующее поведение этого класса(и наоборот). Чтобы избежать этих ошибок, вам вместо этого нужно вернуть копию этого атрибута.
Резюме
- Пол:
- мужчина
- Родной язык:
- русский
- С нами:
- с 17 марта 2009 г. (6424 дня)
- Деятельность:
-
3282 версии перевода
с общим рейтингом 172
325 комментариев
Карма: 13 (оценок: 13)
