Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot use the openvino's pre built opencv #94

Closed
ghost opened this issue Apr 21, 2019 · 14 comments
Closed

Cannot use the openvino's pre built opencv #94

ghost opened this issue Apr 21, 2019 · 14 comments

Comments

@ghost
Copy link

ghost commented Apr 21, 2019

Hello. I am trying to use open vino's version of opencv which is already build with IE backend but i am unable to do so. Whenever i try to load .xml and .bin files of the model in the cv.dnn.readNet , i get the following error:

Traceback (most recent call last):
File "facedetection.py", line 16, in
'pruned_mobilenet_reduced_ssd_shared_weights/dldt/face-detection-adas-0001.xml')
cv2.error: OpenCV(4.0.0) /io/opencv/modules/dnn/src/dnn.cpp:2538: error: (-2:Unspecified error) Build OpenCV with Inference Engine to enable loading models from Model Optimizer. in function 'readFromModelOptimizer

The installation guide says to source the /opt/intel/openvino_2019.1.094/bin/setupvars.sh script in order to update the $OpenCV_DIR variable which I did but it didnt work. When i echo the variable, it points to the following path:

/opt/intel/openvino_2019.1.094/opencv/cmake

I even tried to sym link the cv2.so file from /opt/intel/openvino_2019.1.094/python/python3.5/ directory to the /usr/local/lib/python3.5/dist-packages/ directory but still it doesnt work.
Can you'll please enlist the exact steps to be taken or where i am going wrong? Thanks in advance.

@snosov1
Copy link
Contributor

snosov1 commented Apr 22, 2019

@dkurt, any ideas?

@dkurt
Copy link
Contributor

dkurt commented Apr 22, 2019

@sovereignscout, Please show the output of the following python commands from your script:

import cv2 as cv
print(cv.__file__)

@farshadopencv
Copy link

Hi. I get same error when I use bin and xml files in readFromModelOptimizer function in openvino's version of opencv built in openvino.

I also build opencv 4.0.0-openvino and opencv 4.1.0 with
-DWITH_INF_ENGINE=ON -DENABLE_CXX11=ON
to use IE backend and it build successfully, but again I got error
Build OpenCV with Inference Engine to enable loading models from Model Optimizer. in function 'readFromModelOptimizer, when I use bin and xml files in readFromModelOptimizer function

@alalek
Copy link

alalek commented Apr 22, 2019

CMake output should contain these lines:

-- Detected InferenceEngine: cmake package
...
--     Inference Engine:            YES (2019010000 / 1.6.0)
--                 libs:            /opt/intel/openvino_2019.1.094/deployment_tools/inference_engine/lib/intel64/libinference_engine.so
--             includes:            /opt/intel/openvino_2019.1.094/deployment_tools/inference_engine/include

4.0.0
4.0.0-openvino

These OpenCV versions are not able to work properly with IE from OpenVINO 2019R1.
You should use OpenCV 4.1.0 / 4.1.0-openvino / master.

@dkurt
Copy link
Contributor

dkurt commented Apr 22, 2019

@farshadopencv, Please analyze the CMake summary. It contains all the information about your build: getBuildInformation

@farshadopencv
Copy link

farshadopencv commented Apr 24, 2019

@alalek @dkurt Thanks for your help. Now I can build opencv 4.1.0 with IE backend. But now I encounter another problem. when I pass my bin, xml files of model into object_detection.cpp script, I have following error:

OpenCV(4.1.0) Error: Assertion failed (> Failed to initialize Inference Engine backend: Unsupported primitive of type: PriorBoxClustered name: PriorBoxClustered_5
..\src\mkldnn_plugin\mkldnn_node.cpp:167
c:\program files (x86)\intelswtools\openvino_2019.1.087\deployment_tools\inference_engine\include\details/ie_exception_conversion.hpp:71
) in cv::dnn::InfEngineBackendNet::initPlugin, file C:\o\opencv\modules\dnn\src\op_inf_engine.cpp, line 813

I changed object_detection.cpp to avoid parser as follows:

**#define _CRT_SECURE_NO_WARNINGS

#include
#include

#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

#include "common.hpp"

std::string keys =
"{ help h | | Print help message. }"
"{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }"
"{ zoo | models.yml | An optional path to file with preprocessing parameters }"
"{ device | 0 | camera device number. }"
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera. }"
"{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
"{ classes | | Optional path to a text file with names of classes to label detected objects. }"
"{ thr | .5 | Confidence threshold. }"
"{ nms | .4 | Non-maximum suppression threshold. }"
"{ backend | 0 | Choose one of computation backends: "
"0: automatically (by default), "
"1: Halide language (http://halide-lang.org/), "
"2: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"3: OpenCV implementation }"
"{ target | 0 | Choose one of target computation devices: "
"0: CPU target (by default), "
"1: OpenCL, "
"2: OpenCL fp16 (half-float precision), "
"3: VPU }";

using namespace cv;
using namespace dnn;

float confThreshold, nmsThreshold;
std::vectorstd::string classes;

void postprocess(Mat& frame, const std::vector& out, Net& net);

void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);

void callback(int pos, void* userdata);

std::vector getOutputsNames(const Net& net);

int main(int argc, char** argv)
{

confThreshold = 0.6f;
nmsThreshold = .4f;
float scale = 0.00784f;
Scalar mean = Scalar(127.5, 127.5, 127.5);
bool swapRB = true;
int inpWidth = 300;
int inpHeight = 300;

int backend = 2;
int target = 0;



std::string modelPath = "E:\carPlateSsdlite.bin";
std::string configPath = "E:\carPlateSsdlite.xml";




Net net = readNet(modelPath, configPath);
net.setPreferableBackend(backend);
net.setPreferableTarget(target);
std::vector<String> outNames = net.getUnconnectedOutLayersNames();


static const std::string kWinName = "Deep learning object detection in OpenCV";
namedWindow(kWinName, WINDOW_NORMAL);
int initialConf = (int)(confThreshold * 100);
createTrackbar("Confidence threshold, %", kWinName, &initialConf, 99, callback);



Mat  blob;
Mat frame = imread("E:\img25.jpg", 1);
while (waitKey(1) < 0)
{
	
	if (frame.empty())
	{
		waitKey();
		break;
	}

	
	Size inpSize(inpWidth > 0 ? inpWidth : frame.cols,
		inpHeight > 0 ? inpHeight : frame.rows);
	blobFromImage(frame, blob, scale, inpSize, mean, swapRB, false);

	
	net.setInput(blob);
	if (net.getLayer(0)->outputNameToIndex("im_info") != -1)  // Faster-RCNN or R-FCN
	{
		resize(frame, frame, inpSize);
		Mat imInfo = (Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
		net.setInput(imInfo, "im_info");
	}
	std::vector<Mat> outs;
	net.forward(outs, outNames);

	postprocess(frame, outs, net);

	
	std::vector<double> layersTimes;
	double freq = getTickFrequency() / 1000;
	double t = net.getPerfProfile(layersTimes) / freq;
	std::string label = format("Inference time: %.2f ms", t);
	putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));

	imshow(kWinName, frame);
}
return 0;

}

void postprocess(Mat& frame, const std::vector& outs, Net& net)
{
static std::vector outLayers = net.getUnconnectedOutLayers();
static std::string outLayerType = net.getLayer(outLayers[0])->type;

std::vector<int> classIds;
std::vector<float> confidences;
std::vector<Rect> boxes;
if (outLayerType == "DetectionOutput")
{
	
	CV_Assert(outs.size() > 0);
	for (size_t k = 0; k < outs.size(); k++)
	{
		float* data = (float*)outs[k].data;
		for (size_t i = 0; i < outs[k].total(); i += 7)
		{
			float confidence = data[i + 2];
			if (confidence > confThreshold)
			{
				int left = (int)data[i + 3];
				int top = (int)data[i + 4];
				int right = (int)data[i + 5];
				int bottom = (int)data[i + 6];
				int width = right - left + 1;
				int height = bottom - top + 1;
				if (width * height <= 1)
				{
					left = (int)(data[i + 3] * frame.cols);
					top = (int)(data[i + 4] * frame.rows);
					right = (int)(data[i + 5] * frame.cols);
					bottom = (int)(data[i + 6] * frame.rows);
					width = right - left + 1;
					height = bottom - top + 1;
				}
				classIds.push_back((int)(data[i + 1]) - 1);  // Skip 0th background class id.
				boxes.push_back(Rect(left, top, width, height));
				confidences.push_back(confidence);
			}
		}
	}
}
else if (outLayerType == "Region")
{
	for (size_t i = 0; i < outs.size(); ++i)
	{
		
		float* data = (float*)outs[i].data;
		for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
		{
			Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
			Point classIdPoint;
			double confidence;
			minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
			if (confidence > confThreshold)
			{
				int centerX = (int)(data[0] * frame.cols);
				int centerY = (int)(data[1] * frame.rows);
				int width = (int)(data[2] * frame.cols);
				int height = (int)(data[3] * frame.rows);
				int left = centerX - width / 2;
				int top = centerY - height / 2;

				classIds.push_back(classIdPoint.x);
				confidences.push_back((float)confidence);
				boxes.push_back(Rect(left, top, width, height));
			}
		}
	}
}
else
	CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType);

std::vector<int> indices;
NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
for (size_t i = 0; i < indices.size(); ++i)
{
	int idx = indices[i];
	Rect box = boxes[idx];
	drawPred(classIds[idx], confidences[idx], box.x, box.y,
		box.x + box.width, box.y + box.height, frame);
}

}

void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0));

std::string label = format("%.2f", conf);
if (!classes.empty())
{
	CV_Assert(classId < (int)classes.size());
	label = classes[classId] + ": " + label;
}

int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);

top = max(top, labelSize.height);
rectangle(frame, Point(left, top - labelSize.height),
	Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar());

}

void callback(int pos, void*)
{
confThreshold = pos * 0.01f;
}**

@dkurt
Copy link
Contributor

dkurt commented Apr 25, 2019

OpenCV(4.1.0) Error: Assertion failed (> Failed to initialize Inference Engine backend: Unsupported primitive of type: PriorBoxClustered name: PriorBoxClustered_5
..\src\mkldnn_plugin\mkldnn_node.cpp:167
c:\program files (x86)\intelswtools\openvino_2019.1.087\deployment_tools\inference_engine\include\details/ie_exception_conversion.hpp:71
) in cv::dnn::InfEngineBackendNet::initPlugin, file C:\o\opencv\modules\dnn\src\op_inf_engine.cpp, line 813

Similar issue: opencv/opencv#14409. It looks like there is something wrong with Windows package.

@farshadopencv please check the solution from opencv/opencv#14409 (comment). It looks like your CPU might also don't support AVX2.

@cuixing158
Copy link

cuixing158 commented May 27, 2019

@farshadopencv thank you give a example!!! I ran successfully on "Release" mode

@snosov1 snosov1 closed this as completed May 27, 2019
@dongyangli-del
Copy link

Hello, When I input the command " sudo python3 face_detection.py", it tells me that : Traceback (most recent call last):
File "face_detection.py", line 3, in
net = cv.dnn.readNet('face-detection-adas-0001.xml', 'face-detection-adas-0001.bin')
cv2.error: OpenCV(3.4.3) /home/pi/opencv-python/opencv/modules/dnn/src/dnn.cpp:2365: error: (-2:Unspecified error) Build OpenCV with Inference Engine to enable loading models from Model Optimizer. in function 'readFromModelOptimizer'

Have you ever come across a problem like this? Any good Suggestions? thank you!

@alalek
Copy link

alalek commented Oct 14, 2020

3.4.3

This means that used OpenCV binaries are not from OpenVINO package (-openvino suffix is expected in version identifier).
Check cv.__file__ and cv.getBuildInformation() to confirm that.

sudo

Don't use sudo. At least it drops environment variables (due to security reasons).

@Welyweloo
Copy link

Hello @alalek,
I've been trying to understand your previous message.
Where should I add that -openvino suffix please? I am having the same issue.

(cv) aurelie@aurelie-VirtualBox:~/LO_Computervision_YOLO$ python object_detection_caffe.py --input IMG_4587.MOV --output ./
/home/aurelie/.virtualenvs/cv/lib/python3.8/site-packages/cv2/cv2.cpython-38-x86_64-linux-gnu.so

General configuration for OpenCV 4.5.1 =====================================
  Version control:               4.5.1-dirty

  Platform:
    Timestamp:                   2021-01-02T13:00:02Z
    Host:                        Linux 4.15.0-1077-gcp x86_64
    CMake:                       3.18.4
    CMake generator:             Unix Makefiles
    CMake build tool:            /bin/gmake
    Configuration:               Release

  CPU/HW features:
    Baseline:                    SSE SSE2 SSE3
      requested:                 SSE3
    Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
      requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
      SSE4_1 (15 files):         + SSSE3 SSE4_1
      SSE4_2 (1 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
      FP16 (0 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
      AVX (4 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
      AVX2 (29 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
      AVX512_SKX (4 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX

  C/C++:
    Built as dynamic libs?:      NO
    C++ standard:                11
    C++ Compiler:                /usr/lib/ccache/compilers/c++  (ver 9.3.1)
    C++ flags (Release):         -Wl,-strip-all   -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
    C++ flags (Debug):           -Wl,-strip-all   -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
    C Compiler:                  /usr/lib/ccache/compilers/cc
    C flags (Release):           -Wl,-strip-all   -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
    C flags (Debug):             -Wl,-strip-all   -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
    Linker flags (Release):      -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -L/root/ffmpeg_build/lib  -Wl,--gc-sections -Wl,--as-needed  
    Linker flags (Debug):        -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -L/root/ffmpeg_build/lib  -Wl,--gc-sections -Wl,--as-needed  
    ccache:                      YES
    Precompiled headers:         NO
    Extra dependencies:          ade Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Test Qt5::Concurrent /lib64/libpng.so /lib64/libz.so dl m pthread rt
    3rdparty dependencies:       ittnotify libprotobuf libjpeg-turbo libwebp libtiff libopenjp2 IlmImf quirc ippiw ippicv

  OpenCV modules:
    To be built:                 calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching video videoio
    Disabled:                    world
    Disabled by dependency:      -
    Unavailable:                 java python2 ts
    Applications:                -
    Documentation:               NO
    Non-free algorithms:         NO

  GUI: 
    QT:                          YES (ver 5.15.0)
      QT OpenGL support:         NO
    GTK+:                        NO
    VTK support:                 NO

  Media I/O: 
    ZLib:                        /lib64/libz.so (ver 1.2.7)
    JPEG:                        libjpeg-turbo (ver 2.0.6-62)
    WEBP:                        build (ver encoder: 0x020f)
    PNG:                         /lib64/libpng.so (ver 1.5.13)
    TIFF:                        build (ver 42 - 4.0.10)
    JPEG 2000:                   build (ver 2.3.1)
    OpenEXR:                     build (ver 2.3.0)
    HDR:                         YES
    SUNRASTER:                   YES
    PXM:                         YES
    PFM:                         YES

  Video I/O:
    DC1394:                      NO
    FFMPEG:                      YES
      avcodec:                   YES (58.109.100)
      avformat:                  YES (58.61.100)
      avutil:                    YES (56.60.100)
      swscale:                   YES (5.8.100)
      avresample:                NO
    GStreamer:                   NO
    v4l/v4l2:                    YES (linux/videodev2.h)

  Parallel framework:            pthreads

  Trace:                         YES (with Intel ITT)

  Other third-party libraries:
    Intel IPP:                   2020.0.0 Gold [2020.0.0]
           at:                   /tmp/pip-req-build-ms668fyv/_skbuild/linux-x86_64-3.8/cmake-build/3rdparty/ippicv/ippicv_lnx/icv
    Intel IPP IW:                sources (2020.0.0)
              at:                /tmp/pip-req-build-ms668fyv/_skbuild/linux-x86_64-3.8/cmake-build/3rdparty/ippicv/ippicv_lnx/iw
    Lapack:                      NO
    Eigen:                       NO
    Custom HAL:                  NO
    Protobuf:                    build (3.5.1)

  OpenCL:                        YES (no extra features)
    Include path:                /tmp/pip-req-build-ms668fyv/opencv/3rdparty/include/opencl/1.2
    Link libraries:              Dynamic load

  Python 3:
    Interpreter:                 /opt/python/cp38-cp38/bin/python (ver 3.8.6)
    Libraries:                   libpython3.8.a (ver 3.8.6)
    numpy:                       /tmp/pip-build-env-qm375ina/overlay/lib/python3.8/site-packages/numpy/core/include (ver 1.17.3)
    install path:                python

  Python (for build):            /bin/python2.7

  Java:                          
    ant:                         NO
    JNI:                         NO
    Java wrappers:               NO
    Java tests:                  NO

  Install to:                    /tmp/pip-req-build-ms668fyv/_skbuild/linux-x86_64-3.8/cmake-install
-----------------------------------------------------------------


Initializing...
Traceback (most recent call last):
  File "object_detection_caffe.py", line 199, in <module>
    net = cv2.dnn.readNet('/open_model_zoo-master/tools/downloader/intel/vehicle-attributes-recognition-barrier-0039/FP32/vehicle-attributes-recognition-barrier-0039.bin', 
cv2.error: OpenCV(4.5.1) /tmp/pip-req-build-ms668fyv/opencv/modules/dnn/src/dnn.cpp:3901: error: (-2:Unspecified error) Build OpenCV with Inference Engine to enable loading models from Model Optimizer. in function 'readFromModelOptimizer'

@shahla-ai
Copy link

hi @farshadopencv , I wish you can help me
can you tell me how you compiled OpenCV with openvino IE backend from source ?
all documentations show how to use openvino's OpenCV , but that is not what I want
best regards

@ZhongQiyu
Copy link

3.4.3

This means that used OpenCV binaries are not from OpenVINO package (-openvino suffix is expected in version identifier). Check cv.__file__ and cv.getBuildInformation() to confirm that.

sudo

Don't use sudo. At least it drops environment variables (due to security reasons).
@alalek I was trying to figure out the information generated from cv.getBuildInformation(), and for the point I am getting myself around with the version information:
General configuration for OpenCV 4.5.5 =====================================
Version control: 4.5.5
Is this expected to be adding a suffix of -openvino?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants