W
WXQJuly 25, 2018, 2:10 p.m.

How to install OpenCV on Qt on Windows

Introduction
I would like to express my gratitude to Evgeny for this wonderful site and for the fact that he helps novice programmers and not only develop. I would like to ask other users to contribute to the development of this project) Thank you all)
The following steps were taken by me when I installed OpenCV for myself. I would like to emphasize that there is no FULL article on this topic on the Internet. Since when I installed it, errors came out and I had to look for answers in Runet, then from the Americans, then the devil knows who.


Lan. Go)

To install OpenCV on Qt under OS Windows, we need.

  1. Download OpenCV from the official site. We get files from the archive.

https://opencv.org/

  1. Download CMake from the official site. We get files from the archive.

https://cmake.org/

  1. Qt itself (at the moment I have 5.10.1 v)
  2. On Drive C:\ or drive D:\ creates a folder OpenCV
    3.0 In this folder (OpenCV) we drop the folder that we got from the OpenCV.zip archive.
    3.1 In the same folder (OpenCV) create a folder OpneCV_bin
  3. Run CMake

ATTENTION!!!
Pay attention to the link
C: / OpenCV / opencv / sources (This is in the folder that we unzipped after we downloaded it has this SOURCES folder!)
C:/OpenCV/opencv_bin (And this is an empty! folder that we created)

  1. IMPORTANT !!!
    In this list, uncheck ENABLE_PRECOMPILED_HEADERS, WHIT_IPP, WHIT_CUDA, WHIT_TBB.
    In this list, put the WHIT_QT flag, change WHIT_OPENGL to Release
  2. Click on Configuer, the installation process will go through there and it will stop. Some fields will be red and need to be changed manually.
Установите QT_MAKE_EXECUTABLE в D: \ Qt \ 5.9 \ mingw53_32 \ bin \ qmake.exe
 Установите Qt5Concurrent_DIR в D: \ Qt \ 5.9 \ mingw53_32 \ lib \ cmake \ Qt5Concurrent
 Установите Qt5Core_DIR в D: \ Qt \ 5.9 \ mingw53_32 \ lib \ cmake \ Qt5Core
 Установите Qt5Gui_DIR в D: \ Qt \ 5.9 \ mingw53_32 \ lib \ cmake \ Qt5Gui
 Установите Qt5Test_DIR в D: \ Qt \ 5.9 \ mingw53_32 \ lib \ cmake \ Qt5Test
 Установите Qt5Widgets_DIR в D: \ Qt \ 5.9 \ mingw53_32 \ lib \ cmake \ Qt5Widgets
 Установите Qt5OpenGL_DIR в D: \ Qt \ 5.9 \ mingw53_32 \ lib \ cmake \ Qt5OpenGL
 Установите CMAKE_BUILD_TYPE для Release или RelWithDebInfo

then clicks on Config again and after the end on Generate. And that's it, close CMake.
7. Open the command line and go to the folder C:\OpenCV\opencv_bin (This is in my case) and on the command line we type

 cd с: \OpenCV\opencv_bin  
 mingw32-make -j 8
 mingw32-make install

Dear friends, you can also install OpenCV on Qt under MacOS .... but you need to use the sudo make command there
8. Then add PATH

Go to the properties of MY COMPUTER

All. We have installed everything)) Now you need to open the project in Qt and add the following links to the project

Sample code below

# ------------------------------------------------- 
# 
# Проект, созданный QtCreator 2017-03-05T12: 30: 06 
# 
# --------------------------------- ----------------

QT        + =  core  gui

moreThan ( QT_MAJOR_VERSION ,  4 ) :  QT  + =  виджеты

TARGET  =  opencvtest 
TEMPLATE  =  приложение

# Следующий параметр определяет, что ваш компилятор генерирует предупреждения, если вы используете 
# любую функцию Qt, которая помечается как устаревшая (точные предупреждения 
# зависят от вашего компилятора). Пожалуйста, ознакомьтесь с документацией 
# устаревшего API, чтобы узнать, как отменить его код. 
ОПРЕДЕЛЕНИЯ  + =  QT_DEPRECATED_WARNINGS

# Вы также можете сделать код не скомпилированным, если вы используете устаревшие API. 
# Чтобы сделать это, раскомментируйте следующую строку. 
# Вы также можете отключить устаревшие API только до определенной версии Qt. 
#DEFINES + = QT_DISABLE_DEPRECATED_BEFORE = 0x060000 # отключает все API, устаревшие до Qt 6.0.0


ИСТОЧНИКИ  + =  основной . cpp \
         mainwindow . CPP

HEADERS   + =  mainwindow . час

FORMS     + =  mainwindow . щ

INCLUDEPATH  + =  D : \ opencv \ build \ include

LIBS  + =  D : \ opencv - build \ bin \ libopencv_core320 . dll 
LIBS  + =  D : \ opencv - build \ bin \ libopencv_highgui320 . dll 
LIBS  \ libopencv_imgproc320 . dll LIBS + = D : \ opencv - + =  D : \ opencv - build \ bin \ libopencv_imgcodecs320 . dll 
LIBS  + =  D : \ opencv - build \ bin
   build \ bin \ libopencv_features2d320 . dll 
LIBS  + =  D : \ opencv - build \ bin \ libopencv_calib3d320 . длл

# более правильный вариант, как set includepath и libs для mingw 
# добавить системную переменную: OPENCV_SDK_DIR = D: / opencv / build 
# читать http: //doc.qt.io/qt-5/qmake-variable-reference.html#libs

#INCLUDEPATH + = $$ (OPENCV_SDK_DIR) / включить

#LIBS + = -L $$ (OPENCV_SDK_DIR) / x86 / mingw / lib \
# -lopencv_core320 \ 
# -lopencv_highgui320 \ 
# -lopencv_imgcodecs320 \ 
# -lopencv_imgproc320 \ 
# -lopencv_features2d320 \ 
# -lopencv_calib3d320
и измените mainwindow.cpp следующим образом:

#include  "mainwindow.h"
#include  "ui_mainwindow.h"

#include  <opencv2 / core / core.hpp>
#include  <opencv2 / highgui / highgui.hpp>

MainWindow :: MainWindow ( родитель QWidget  * ) : QMainWindow ( родительский ), ui 

     ( новый  Ui :: MainWindow ) 
{ 
    ui -> setupUi ( this );

    // читаем изображение 
    cv :: Mat  image  =  cv :: imread ( "f: //1.jpg" ,  1 ); 
    // создаем окно изображения с именем «My Image» 
    cv :: namedWindow ( «My Image» ); 
    // показать изображение в окне 
    cv :: imshow ( «Мое изображение» ,  изображение ); 
}

MainWindow :: ~ MainWindow () 
{ 
    delete  ui ; 
}

Source Qt wiki

But not everything is there ... I passed these paths

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

W
  • July 25, 2018, 2:40 p.m.

Код снизу чет слетел....не знаю как подправить ....простите ребята(

Evgenii Legotckoi
  • July 26, 2018, 6:32 a.m.

Спасибо за статью. Я поправил все моменты с вёрсткой.

T
  • Feb. 20, 2019, 2:39 p.m.

Спасибо за статью!
У меня возникли проблемы с CMake'ом он постоянно выдавал ошибки, нашел ролик на ютубе где пошагово показано как устанавливать эту либу. Ссылку прилагаю, надеюсь это разрешено..
(https://www.youtube.com/watch?v=7zYJFjqPklI)

Evgenii Legotckoi
  • Feb. 20, 2019, 3:20 p.m.

Не приветствуется спам, подозрительные ссылки, сомнительные предложения и некультурное поведение ))))

В остальном всё модерируется, конечно, но без тирании.

Если есть действительно полезные материалы или статьи на других ресурсах, то для этого даже имеется раздел социальных закладок , можете добавлять там ссылки, просто пишите небольшую аннотацию о том, что находится по той ссылке. Но, конечно, все материалы проходят пост-модерацию во избежание злоупотреблений.

v
  • Nov. 19, 2019, 10:19 a.m.
  • (edited)

Ребята а что если папки "Source" в архиве opencv нет? Скачал три варианта библиотеки ни в одном нет этой папки.

v
  • Nov. 19, 2019, 11:26 a.m.
  • (edited)

Разобрался!!! Надо было не архив качать а exe файл и его уже распаковывать в нужную папку)))

IscanderChe
  • May 31, 2020, 9:15 a.m.

Добавлю от себя: на Windows 10 x64 с MinGW 7.3.0 в CMake надо установить флаг OPENCV_ENABLE_ALLOCATOR_STATS=OFF, тогда всё скомпилится нормально.

РР
  • Feb. 16, 2021, 10:03 a.m.

А если на этапе консоли выдаёт ошибки?

Эту если с припиской -j 8

Эту - если простая установка

Можете подсказать, пожалуйста, что делать?

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 23, 2024, 3:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks