Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reading an image from OpenCV python samples giving error where as it does not give error in c++?

I am trying to read an image in opencv python

import cv2
import numpy as np

# Read images
image=cv2.imread(cv2.samples.findFile("lena.jpg"))
cv2.imshow("image",image)
cv2.waitKey(0)

and it gives the following error

[ WARN:0] global C:\projects\opencv-python\opencv\modules\core\src\utils\samples.cpp (59) cv::samples::findFile cv::samples::findFile('lena.jpg') => ''
Traceback (most recent call last):
  File "D:/all_libraries/main.py", line 5, in <module>
    image=cv2.imread(cv2.samples.findFile("lena.jpg"))
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\utils\samples.cpp:62: error: (-2:Unspecified error) OpenCV samples: Can't find required data file: lena.jpg in function 'cv::samples::findFile'

where as the C++ version of this does not give any error


#include <iostream>

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

using namespace std;
using namespace cv;
using namespace cv::ml;
int main()
{

    Mat image;
    image=imread(samples::findFile("lena.jpg"));
    imshow("lena.jpg",image);
    waitKey(0);

    return 0;
}

I have installed OpenCV 4.1.1 in pycharm c++ version is also 4.1.1 operating system Windows

like image 637
Gourav Roy Avatar asked Dec 15 '19 05:12

Gourav Roy


2 Answers

I had the same problem running the first OpenCV tutorial, the following worked for me. I am using PyCharm Community and python. addSamplesDataSearchSubDirectory did not work.

cv.samples.addSamplesDataSearchPath("C:\\......\\opencv\\sources\\samples\\data")
img = cv.imread(cv.samples.findFile("starry_night.jpg"))
like image 129
Roo Avatar answered Oct 16 '22 08:10

Roo


In Python, the findFile function uses an environment variable to define the search path. When you installed OpenCV, you would have a created a folder with a name similar to C:\something\samples\data (I'm guessing a little bit here because I use Linux not Windows). So you need to set the environment variable OPENCV_SAMPLES_DATA_PATH to the value C:\something\samples\data and then try running your code.

There's a little bit of relevant documentation (but not really enough to be useful) at https://docs.opencv.org/3.4/d6/dba/group__core__utils__samples.html

like image 2
Alexander Hanysz Avatar answered Oct 16 '22 09:10

Alexander Hanysz