# Implementation Run Length Smoothing Algorithm in C++

This is my old question related to RLSA in C++, but I havent got any help yet.

I tried to implement the code from Matlab to C++

The description of this algorithm :

There is RLSA implementation in Matlab by this thread :

MatLabCode

 hor_thresh=20;
zeros_count=0;
one_flag=0;
hor_image=image;
for i=1:m
for j=1:n
if(image(i,j)==1)
if(one_flag==1)
if(zeros_count<=hor_thresh)
hor_image(i,j-zeros_count:j-1)=1;
else
one_flag=0;
end
zeros_count=0;
end
one_flag=1;
else
if(one_flag==1)
zeros_count=zeros_count+1;
end
end
end
end


I tried to implement in C++ Code

    int hor_thres = 22;
int one_count = 0;
int zero_flag = 0;
Mat tmpImg = Mat(Img.size(), CV_8UC1, Scalar(0, 0, 0));
for (int j = 0; j<Img.rows; j++){
for (int i = 0; i<Img.cols; j++){
if (Img.at<uchar>(j, i) == 0)
{
if (zero_flag == 1)
{
if (one_count <= hor_thres)
{
tmpText(cv::Range(j - zero_count, j), cv::Range(i, i+1)).setTo(cv::Scalar::all(255));
// I want to do the same thing in Matlab as this  image(i,j-one_count:j-1)=0;
}
else
{
zero_flag = 1;
}
one_count = 0;
}
zero_flag = 1;
}
else
{
if (zero_flag == 1)
{
one_count = one_count + 1;
}
}
}
}


This time no error but the result is not expected ..

The issue is the way i want to write c++ code the same thing as

Matlab

tmpImg(i,j-one_count:j-1)=0;


C++

tmpText(cv::Range(j - zero_count, j), cv::Range(i, i+1)).setTo(cv::Scalar::all(255));


Anyidea???

Another thing is in Matlab the index start from 1 while C++ start from 0.

Thank

edit retag close merge delete

Sort by » oldest newest most voted

Well, regarding the index start problem, you just have to shift everything in order to make it work I think. As for the setting to 0 the matrix, I think you could use the Rect class:

tmpText(Rect(i,j-zero_count,zero_count-1,1)).setTo(0);


or something like this, where you specify starting position, width and height.

In any case, in what way the result is not as expected?

more

@Luca Thank you, i already fix the issue, Just like you said I have some problems with indexs. However, I still not satify with the implementation since I only use nested loop rather than access in matrice way. what you think?

Sorry for the huge delay :P I'm not sure that you can avoid these loops! In any case, you could use pointers to access the Mat elements instead of the at<>() function!

uchar* p = Mat.data; int pos = j*Img.Cols + i; if(p[pos]==0) [...]

Official site

GitHub

Wiki

Documentation