Port of: https://mahotas.readthedocs.io/en/latest/wally.html
In this case it would have been simpler to create a sub with the python code:
Usage:
B4X:
Dim pylab As PyWrapper = Py.ImportModule("pylab")
Dim mahotas As PyWrapper = Py.ImportModule("mahotas")
Dim demos As PyWrapper = Py.ImportModule("mahotas.demos")
Dim np As PyWrapper = Py.ImportModule("numpy")
Dim wally As PyWrapper = demos.Run("load").Arg("Wally")
Dim wfloat As PyWrapper = wally.Run("astype").Arg("float")
Dim rgb As PyWrapper = wfloat.Run("transpose").Arg(Array(2, 0, 1))
Dim w As PyWrapper = wfloat.Run("mean").Arg(2)
Dim pattern As PyWrapper = np.Run("ones").Arg(Array(24, 16)).Arg("float")
For i = 0 To 1
pattern.Set(Py.Slice(i, Null).Arg(4), -1)
Next
Dim v As PyWrapper = mahotas.Run("convolve").Arg(rgb.Get(0).OprSub(w)).Arg(pattern)
Dim mask As PyWrapper = v.OprEqual(v.Run("max"))
mask = mahotas.Run("dilate").Arg(mask).Arg(np.Run("ones").Arg(Array(48, 24)))
Dim maskWithAdditionalDim As PyWrapper = mask.Get3D(Py.SliceAll, Py.SliceAll, Null)
Dim notmask As PyWrapper = wally.OprMul(0.9).OprMul(maskWithAdditionalDim.OprNot)
Dim maskedWally As PyWrapper = wally.Run("copy")
np.Run("subtract").Arg(wally).Arg(notmask).ArgNamed("casting", "unsafe") _
.ArgNamed("out", maskedWally)
Dim imgs As List = Array(wally, maskedWally)
For i = 0 To imgs.Size - 1
pylab.Run("subplot").Arg(1).Arg(2).Arg(i + 1)
pylab.Run("imshow").Arg(imgs.Get(i))
pylab.Run("axis").Arg("off")
Next
pylab.Run("show")
In this case it would have been simpler to create a sub with the python code:
B4X:
Private Sub FindWally (img As Object) As PyWrapper
Dim Code As String = $"
import mahotas
import numpy as np
def FindWally (img):
wally = img.copy()
wfloat = wally.astype(float)
r,g,b = wfloat.transpose((2,0,1))
w = wfloat.mean(2)
pattern = np.ones((24,16), float)
for i in range(2):
pattern[i::4] = -1
v = mahotas.convolve(r-w, pattern)
mask = (v == v.max())
mask = mahotas.dilate(mask, np.ones((48,24)))
np.subtract(wally, .8*wally * ~mask[:,:,None], out=wally, casting='unsafe')
return wally
"$
Return Py.RunCode("FindWally", Array(img), Code)
End Sub
Usage:
B4X:
Dim pylab As PyWrapper = Py.ImportModule("pylab")
Dim demos As PyWrapper = Py.ImportModule("mahotas.demos")
Dim wally As PyWrapper = demos.Run("load").Arg("Wally")
Dim MaskedWally As PyWrapper = FindWally(wally)
Dim imgs As List = Array(wally, MaskedWally)
For i = 0 To imgs.Size - 1
pylab.Run("subplot").Arg(1).Arg(2).Arg(i + 1)
pylab.Run("imshow").Arg(imgs.Get(i))
pylab.Run("axis").Arg("off")
Next
pylab.Run("show")