In Elixir, variables are actually constants. You can’t reassign values to an existing variable. You can only create a new variable with the same name and shadow the old one.
This line square = square + 1 reads the value of square outside the for-loop, adds 1 to it, and creates a new variable also named square, which is not used at all, because this new square variable is inside a sub-sub scope of the for-loop, and the old square is outside the for-loop. They are in different scopes.
How to fix this?
square = for contour <- contours, reduce: 0 do
acc ->
{:ok,peri} = OpenCV.arcLength(contour,true)
{:ok,approx} = OpenCV.approxPolyDP(contour, 0.01 * peri,true)
ap=OpenCV.Nx.to_nx(approx)
{len,_,_}=Nx.shape(ap)
if len==4 do #to bound squares from the countor
{:ok,{x1, y1, w, h}}= OpenCV.boundingRect(approx)
aspectRatio = (w/1)/h
if aspectRatio >= 0.95 and aspectRatio <= 1.05 and (y1+h)*(x1+w) < 985000 do
acc + 1
else
acc
end
else
acc
end
end
square = for contour <- contours, reduce: 0 do
acc ->
{:ok,peri} = OpenCV.arcLength(contour,true)
{:ok,approx} = OpenCV.approxPolyDP(contour, 0.01 * peri,true)
ap=OpenCV.Nx.to_nx(approx)
{len,_,_}=Nx.shape(ap)
if len==4 do #to bound squares from the countor
{:ok,{x1, y1, w, h}}= OpenCV.boundingRect(approx)
aspectRatio = (w/1)/h
if aspectRatio >= 0.95 and aspectRatio <= 1.05 and (y1+h)*(x1+w) < 985000 do
acc + 1
else
acc
end
end
end
so that in further code if i will face problem regarding this i can rectify it
Here’s a simple example of the for comprehension with the option :reduce:
for n <- 1..10, reduce: 0 do
acc -> acc + n
end
# returns 55
It’s equivalent to this code (I’m using the same variable names as in the snippet above):
Enum.reduce(1..10, 0, fn n, acc ->
acc + n
end)
The for comprehension first passes 0, the value of the option :reduce, to acc, the first element in 1..10 to n, and apply the anonymous function to acc and n. Then it passes the return value of the anonymous function to acc, the second element in 1..10 to n, and apply the anonymous function again. So on and so forth, until there’s no element to take from 1..10, then it returns the return value of the last call of that anonymous function.
And note that both for ... do ... end and if ... else ... end are expressions, and they have return values.
The if without else returns whatever inside the if block returns, if the condition is met, otherwise, it returns nil, which usually is not what you want, so be careful.
Then you have a very easy problem: find exactly in which directory the tesseract program binary resides and add that to $PATH. Because right now it’s not there.