Split string to numbers in Lua - lua

I've a problem with splitting this:
x = "-301 1021"
to this
x = -301
y = 1021
In C++ this is easier but I really don't know how to do it in Lua. I tried do it like
string1 .. string[i]
#Edit
I've made it like this but now it doesn't get values which are negative
for coordinate in ActualCoords:gmatch("%w+") do
table.insert(coordinates, coordinate)
end
x = coordinates[1];
x = tonumber(x);
z = coordinates[2];
z = tonumber(z);

Assuming your input is regular:
restults = {};
for m in str:gmatch("[^%s]+") do
results[#results+1] = m+0;
end
If input is irregular, meaning you need to verify that its not random things separated by spaces, you need to make a more complex pattern, eg.
"[%deE.-]+"

Try this:
s = "-301 1021"
x,y = s:match("(%S+)%s+(%S+)")
x,y = tonumber(x), tonumber(y)

You can use LPEG for such parsing tasks.
local lpeg = assert(require"lpeg")
local R, S = lpeg.R, lpeg.S
local integer = (S'+-'^-1 * R("09")^1) / tonumber
local space = S(" \t")^0
local x, y = lpeg.match((integer * space)^1, "-301 1021")
print(x,y)

or try this
local s = "-301 1021 -300 1022 -20 -1000"
local coord = {}
for x,y in s:gmatch("(-?%d+).-(-?%d+)") do
coord[#coord+1] = { x=tonumber(x), y=tonumber(y) }
end
print( coord[1].x, coord[1].y)
print( coord[2].x, coord[2].y)
print( coord[3].x, coord[3].y)

Related

Linefitting how to deal with continuous values?

I'm trying to fit a line using quadratic poly, but because the fit results in continuous values, the integer conversion (for CartesianIndex) rounds it off, and I loose data at that pixel.
I tried the method
here. So I get new y values as
using Images, Polynomials, Plots,ImageView
img = load("jTjYb.png")
img = Gray.(img)
img = img[end:-1:1, :]
nodes = findall(img.>0)
xdata = map(p->p[2], nodes)
ydata = map(p->p[1], nodes)
f = fit(xdata, ydata, 2)
ydata_new .= round.(Int, f.(xdata)
new_line_fitted_img=zeros(size(img))
new_line_fitted_img[xdata,ydata_new].=1
imshow(new_line_fitted_img)
which results in chopped line as below
whereas I was expecting it to be continuous line as it was in pre-processing
Do you expect the following:
Raw Image
Fitted Polynomial
Superposition
enter image description here
enter image description here
enter image description here
Code:
using Images, Polynomials
img = load("img.png");
img = Gray.(img)
fx(data, dCoef, cCoef, bCoef, aCoef) = #. data^3 *aCoef + data^2 *bCoef + data*cCoef + dCoef;
function fit_poly(img::Array{<:Gray, 2})
img = img[end:-1:1, :]
nodes = findall(img.>0)
xdata = map(p->p[2], nodes)
ydata = map(p->p[1], nodes)
f = fit(xdata, ydata, 3)
xdt = unique(xdata)
xdt, fx(xdt, f.coeffs...)
end;
function draw_poly!(X, y)
the_min = minimum(y)
if the_min<0
y .-= the_min - 1
end
initialized_img = Gray.(zeros(maximum(X), maximum(y)))
initialized_img[CartesianIndex.(X, y)] .= 1
dif = diff(y)
for i in eachindex(dif)
the_dif = dif[i]
if abs(the_dif) >= 2
segment = the_dif ÷ 2
initialized_img[i, y[i]:y[i]+segment] .= 1
initialized_img[i+1, y[i]+segment+1:y[i+1]-1] .= 1
end
end
rotl90(initialized_img)
end;
X, y = fit_poly(img);
y = convert(Vector{Int64}, round.(y));
draw_poly!(X, y)

Lua Acessing table values within nested table

I'm trying to test certain variables on a grid made out of nested tables. However no matter what I try it wont give me the values stored within the variables only the data type or a nil value
y = {}
for _y = 0,16 do
for _x = 0,16 do
x = {}
x.x = _x
x.y = _y
x.v = flr(rnd(2))
if x.x < 1 or x.x > 14 then
x.v = 3
end
if x.v == 0 then
x.v = "."
elseif x.v ==1 then
x.v = ","
else
x.v = "0"
end
add(y,x)
end
end
I've tried accessing the value using
print(t[1][3])
But this only prints back a nil value, how would I code this to show whats stored within the value within these two tables?
You have the nesting as follows:
y = {x_1, x_2, x_3, ...}
where, each of x_i is of the form:
x = {
x = p,
y = q,
v = r
}
so, you will have the indexing for each x element as y[i], and each y[i] contains 3 attributes:
print(y[1].x)
will give you x_1.x
You want to create a 2-dimensional table, but only create a 1-dimensional one.
Fix your code to look somewhat like this
y = {}
for _y=1,16 do
y[_y] = {}
for _x=1,16 do
y[_y][_x]= "your data"
end
end

Lua <eof> expected near 'print'

I'm having trouble with in lua.
Problem one:
Every time I run the following program the console tells me:
'end' expected (to close 'function' at line 1) near 'local'
Please notice where I've marked in all caps comments details about the error
function m11()
local inst = mc.mcGetInstance() -- controller instance
local gcodeLineNbr = mc.mcCntlGetGcodeLineNbr(inst) -- get current Gcode line number
local gcodeLineStr = mc.mcCntlGetGcodeLine(inst, gcodeLineNbr) -- get current Gcode line
function valFromLine(string, axis)
local startPoint = string.find(string, axis) + 1
local outputVal = ""
local isNum = true
while isNum do
local num = string.sub(string, startPoint, startPoint)
startPoint = startPoint + 1
if num ~= " " then
outputVal = outputVal .. num
else
isNum = false
end
end
outputVal = tonumber(outputVal)
end
return outputVal
--COMPILER HIGHLIGHTS FOLLOWING LINE AS LOCATION OF ERROR
local gcodeLocX = valFromLine(gcodeLineStr, "X")
local curLocX = mc.mcAxisGetPos(inst, 0) -- get current X axis value
local curLocY = mc.mcAxisGetPos(inst, 1) -- get current Y axis value
local curLocZ = mc.mcAxisGetPos(inst, 2) -- get current Z axis value
local curAngB = mc.mcAxisGetPos(inst, 4) -- get current C axis value
local curAngC = mc.mcAxisGetPos(inst, 5) -- get current C axis value
local toolOffset = mc.mcCntlGetToolOffset(inst, 2) -- get tool offset for axis Z
function rotateToolB()
local comHypot = toolOffset * math.sin(angle) -- get XY planar dist from C pivot to tool centre point
local compDestinX = comHypot * math.sin(math.rad(90) - curAxisC + curLocX
end
end
--END OF M11() FUNCTION SHOULD BE HERE
if (mc.mcInEditor() == 1) then
m11()
end
I can't see why it's expecting m11() to close so early.
Problem two:
I rewrote valFromLine() in a completely separate file and I get:
'eof' expected near 'print'
function valFromLine(string, axis)
local startPoint = string.find(string, axis) + 1
local outputVal = ""
local isNum = true
while isNum do
local num = string.sub(string, startPoint, startPoint)
startPoint = startPoint + 1
if num ~= " " then
outputVal = outputVal .. num
else
isNum = false
end
end
outputVal = tonumber(outputVal)
end
return outputVal
print(valFromLine("GO1 X254.348 Y1039.456 Z150.13 B90.23 C13 M11", "X"))
I've counted my 'end' statements, I can't find what's wrong with them in either examples of code. I'm at a complete loss for ideas at this point, please help. Thanks.
The line return outputVal is at the wrong position. Move it into the function valFromLine.
You cannot return outside the function.
correct:
function someFunction()
-- do something
local something = "something"
return something
end
wrong:
function someFunction()
-- do something
local something = "something"
end
return something
Defining global functions withn a function is also not very clean, use locals.

Love2D Lua framework - Converting an unorganised rendering table into a map structure

I'm turning a 2D rendered map which is unorganised into a string table, EG from:
"Render = {{Image,50,60,2}}"
Where Image is the image (I'm using Love2D Lua framework)
50 is the X axis
60 is the Y axis
2 is the Image ID (This is what will be in the actual table.)
But there's like 100 of these, all unorganised and stuff, and I need to oragnise them into a structured map.
Here's the odd bit: When I morph it into an organised string.. It.. Kinda rotates the table on a 90* angle anticlockwise.
Saying I want the result of
{
{7,6,5},
{6,5,4},
}
I would get:
{
{5,4},
{6,5},
{7,6},
}
Obviously no error since it technically works, just rotates wrongly. Here's the relevant code:
function OrganiseRenderIntoMap()
MapString = ""
Map2 = {}
MaxSoFarX = 0
MaxSoFarY = 0
for _,v in pairs(Render) do
if v[2] > MaxSoFarX then
MaxSoFarX = v[2]
elseif v[3] > MaxSoFarY then
MaxSoFarY = v[3]
end
end
for currx = 0, MaxSoFarX, 32 do
Map2[currx] = {}
MapString = MapString.."{"
for curry = 0, MaxSoFarY, 32 do
MapString = MapString..GetRenderPos(currx,curry)..","
Map2[currx][curry] = GetRenderPos(currx,curry)
end
MapString = MapString.."},\n"
end
return MapString
end
function GetRenderPos(locx,locy)
for _,v in pairs(Render) do
if v[2] == locx and v[3] == locy then
return v[4]
end
end
end
Give a look at my LÖVE tile tutorial. Section 1d-Strings speaks about how to handle the "switched x and y" problem.

DCT equation in openCV

I write JPEG compression in Scilab (equivalent of MATLAB) using function imdct. In this function is used function DCT from openCV and I don't know which equation is used in dct function.
lenna by imdct
lenna by my_function
You can see lenna by imdct which is internal function and lenna by my_function is my function in scilab.
I add my code in scilab
function vystup = dct_rovnice(vstup)
[M,N] = size(vstup)
for u=1:M
for v=1:N
cos_celkem = 0;
for m=1:M
for n=1:N
pom = double(vstup(m,n));
cos_citatel1 = cos(((2*m) * u * %pi)/(2*M));
cos_citatel2 = cos(((2*n) * v * %pi)/(2*N));
cos_celkem = cos_celkem + (pom * cos_citatel1 * cos_citatel2);
end
end
c_u = 0;
c_v = 0;
if u == 1 then
c_u = 1 / sqrt(2);
else
c_u = 1;
end
if v == 1 then
c_v = 1 / sqrt(2);
else
c_v = 1;
end
vystup(u,v) = (2/sqrt(n*m)) * c_u * c_v * cos_celkem;
end
end
endfunction
function vystup = dct_prevod(vstup)
Y = vstup(:,:,1);
Cb = vstup(:,:,2);
Cr = vstup(:,:,3);
[rows,columns]=size(vstup)
vystup = zeros(rows,columns,3)
for y=1:8:rows-7
for x=1:8:columns-7
blok_Y = Y(y:y+7,x:x+7)
blok_Cb = Cb(y:y+7,x:x+7)
blok_Cr = Cr(y:y+7,x:x+7)
blok_dct_Y = dct_rovnice(blok_Y)
blok_dct_Cb = dct_rovnice(blok_Cb)
blok_dct_Cr = dct_rovnice(blok_Cr)
vystup(y:y+7,x:x+7,1)= blok_dct_Y
vystup(y:y+7,x:x+7,2)= blok_dct_Cb
vystup(y:y+7,x:x+7,3)= blok_dct_Cr
end
end
vystup = uint8(vystup)
endfunction
You can see equation I used
EQUATION
The issue seems to be in the use of different normalization of the resulting coefficients.
The OpenCV library uses this equation for a forward transform (N=8, in your case):
The basis g is defined as
where
(Sorry for the ugly images, but SO does not provide any support for typesetting equations.)
Take care there are several definitions of the dct function (DCT-I, DCT-II, DCT-III and DCT-IV normalized and un-normmalized)
Moreover have you tried the Scilab builtin function dct (from FFTW) which can be applied straightforward to images.

Resources