I was working on a project using OpenCV, Python that uses Probabilistic Hough Line Transform function "HoughLinesP" in some part of the project. My code worked just fine and there was no problem. Then I thought of converting the same code to C++.
After converting the code to C++, the output is not the same as that of the Python code. After long hours of debugging, I found out that everything else works fine but the "HoughLinesP" function is giving different output in the case of C++. The input to this function in both the languages is the same and the values of parameters are also the same but the output from it is different.
Can someone explain me why is this happening and any possible fixes for it?
Also, I have checked the version of OpenCV for both the languages, and it is the same:
4.5.0 dev
Also, I have tried playing with the values passed to the C++ code, but I am not able to obtain similar results.
Input Edge Image:
Python HoughLinesP() output:
C++ HoughLinesP() output:
Following are the codes in each language: Python:
Lines = cv2.HoughLinesP(EdgeImage, 1, np.pi / 180, 50, 10, 15)
C++:
std::vector<cv::Vec4i> Lines;
cv::HoughLinesP(EdgeImage, Lines, 1, CV_PI / 180, 50, 10, 15);
It would be a great help if anyone could suggest something.
Explanation & Fix
The problem arises because in the Python version you are not setting the arguments that you think you are setting. In contrast to some other functions for which the argument lists are adapted in the Python interface,
HoughLinesP
does not only return the lines but also still takes a parameterlines
for the line output. You can see that in the help forHoughLinesP
:which gives you (ellipsis mine):
So basically, in your python example you pass
10
aslines
instead of asminLineLength
. To fix this, you can either pass an empty array aslines
or you can pass the parameters as keyword arguments:Doing that should make your Python version's output match the C++ version's.
Alternatively, if you are happy with the results of the Python version, you have to leave out parameter
lines
(i.e. only settingminLineLength
to 15 and using the default of 0 formaxLineGap
[see docs]):This should then reproduce your Python version.
Example
Using the example listed in the openCV documentation of
HoughLinesP
, you can see that this fixes the issue.C++ version
(Taken from openCV documentation listed above and adapted to save image instead.)
If you compile this and run it over the example picture provided in the docs, you get the following result:
Incorrect Python version
(Basically, just the translated C++ version without the lines parameter.)
Running this gives the following (different) result:
Corrected python version
(Fixed by passing keyword args instead)
This gives the correct result (i.e. the same result as the C++ version):