Nils J.
Nils J.

Reputation: 101

Opencv Python Code to C++

I am trying to translate Python code to C++. Here is the code:

kernelx = cv2.getStructuringElement(cv2.MORPH_RECT,(2,10))

dx = cv2.Sobel(res,cv2.CV_16S,1,0)
dx = cv2.convertScaleAbs(dx)
cv2.normalize(dx,dx,0,255,cv2.NORM_MINMAX)
ret,close = cv2.threshold(dx,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
close = cv2.morphologyEx(close,cv2.MORPH_DILATE,kernelx,iterations = 1)

contour, hier = cv2.findContours(close,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contour:
    x,y,w,h = cv2.boundingRect(cnt)
    if h/w > 5:
        cv2.drawContours(close,[cnt],0,255,-1)
    else:
        cv2.drawContours(close,[cnt],0,0,-1)
close = cv2.morphologyEx(close,cv2.MORPH_CLOSE,None,iterations = 2)
closex = close.copy()

the only problem I have is this line:

if h/w > 5:

I'm have trouble to find a solution for that.

Upvotes: 1

Views: 467

Answers (1)

karlphillip
karlphillip

Reputation: 93410

In the C++ API x, y, h and w are properties of the cv::Rect object returned by cv::boundingRect():

for (size_t i = 0; i < contour.size(); i++)
{
    cv::Mat cnt = contour[i];
    cv::Rect rect = cv::boundingRect(cnt);
    if (rect.height / rect.width > 5)
        // ...
    else
        // ...
}

Upvotes: 1

Related Questions