Edit: Motion Detection I believe this may answer my question...
I want to not only detect motion, but read where the motion occurred in the frame. Nothing in MotionDetector seems to have anything about its location. I thought maybe I could run it through MotionDetector then extract the biggest blob, but that doesn't seem to work either. It only picks up one blob.
Video clip is a vehicle coming down a ramp. mainPBX is the original frame, main2PBX is the altered frame (with the biggest blob overlayed). My thought is to read when the blob goes from smaller to bigger (and vice versa), to determine entering or leaving.
Private Sub Processor()
Dim bc As New BlobCounter With {
.MinWidth = 5,
.MinHeight = 5,
.ObjectsOrder = ObjectsOrder.Size
}
Dim detector As New MotionDetector(New SimpleBackgroundModelingDetector, New MotionAreaHighlighting)
Using reader As New AForge.Video.FFMPEG.VideoFileReader()
reader.Open("C:\Videos\MyVideo.mp4")
For i As Integer = 0 To reader.FrameCount - 1
Dim frame = reader.ReadVideoFrame()
Dim frame2 As Bitmap = frame.Clone()
Dim frame3 As Bitmap = frame.Clone()
detector.ProcessFrame(frame2)
bc.ProcessImage(frame2)
Dim blobs = bc.GetObjectsInformation()
If blobs.Length > 0 Then
bc.ExtractBlobsImage(frame3, blobs(0), True)
PBX_Image(main2PBX, frame3.Clone())
End If
PBX_Image(mainPBX, frame.Clone())
Threading.Thread.Sleep(25)
frame.Dispose()
frame2.Dispose()
frame3.Dispose()
Next
End Using
End Sub
This is in no way finished, but I can actually interact with the blobs.
Private Sub Processor()
Dim Rectangles As New List(Of Rectangle)
Dim detector As New SimpleBackgroundModelingDetector With {
.SuppressNoise = True,
.DifferenceThreshold = 10,
.FramesPerBackgroundUpdate = 10,
.KeepObjectsEdges = True
}
Dim processor As New AForge.Vision.Motion.BlobCountingObjectsProcessing With {
.MinObjectsWidth = 40,
.MinObjectsHeight = 40,
.HighlightColor = Color.Red
}
Dim motionDetector As New MotionDetector(detector, processor)
Using reader As New AForge.Video.FFMPEG.VideoFileReader()
reader.Open("C:\Videos\MyVideo.mp4")
For i As Integer = 0 To reader.FrameCount - 1
Dim frame = reader.ReadVideoFrame()
motionDetector.ProcessFrame(frame)
Dim t As BlobCountingObjectsProcessing = motionDetector.MotionProcessingAlgorithm
Dim r As Rectangle = Rectangle.Empty
If t.ObjectRectangles.Length > 0 Then
If t.ObjectRectangles.Length > 2 Then
r = t.ObjectRectangles.Aggregate(Function(r1, r2) If((r1.Width * r1.Height) > (r2.Width * r2.Height), r1, r2))
Else
r = t.ObjectRectangles.First()
End If
End If
If r.IsEmpty = False Then Rectangles.Add(r)
PBX_Image(mainPBX, frame.Clone())
Threading.Thread.Sleep(25)
frame.Dispose()
Next
End Using
End Sub
Related
How do I get the full path to the required value in the table? I want to track changes in another table through a proxy table.
I understand that I need to use metatables and __index in it. But I haven't been able to come up with a tracker yet.
Sample table structure:
Objects = {
Panel = { layer = 1, x = 600, y = 328, w = 331, h = 491;
objects = {
label = { layer = 1, x = 0, y = 0, text = 'header' };
Window = { layer = 2, x = 400, y = 100, w = 100, h = 100;
objects = {
label = { layer = 1, x = 0, y = 0, text = 'lorem ipsum dorem' };
};
};
};
};
};
Path: Objects.Panel.objects.Window.objects.label.text
I tried to create a metatable for each of the tables and collect the result of each call to __index into a table in order to roughly understand which key and value were retrieved or changed in order to synchronize these values with other tables.
This will prove itself to be horrendously slow and memory inefficient. Anyway, you were right on the track: proxy and handle __index and __newindex metamethods to your liking. This being said you also need to track the state of the proxy somehow.
You can try to hide it with some closures and upvalues but the easy way is to store the information directly in the proxy tables:
function make_tracker (o, name)
local mt = {}
mt.__index = function (proxy, key)
local path = {unpack(rawget(proxy, "__path"))} -- Stupid shallow copy
local object = rawget(proxy, "__to")
table.insert(path, key)
if type(object[key]) == "table" then
return setmetatable({__to = object[key], __path = path}, mt)
else
return table.concat(path, ".") .. " = " .. tostring(object[key])
end
end
return setmetatable({__to = o, __path = {name}}, mt)
end
__to fields indicates what proxy should point to and __path is there to cover fields we have trespassed so far. It does a shallow copy, so that one can use subproxies with local variables. name parameter is there to initialize the name of the first table, as you just simply can't know that. You use it like this:
local tObjects = make_tracker(Objects, "Objects")
local subproxy = tObjects.Panel.objects.Window
print(subproxy.objects.label.text)
print(tObjects.Panel.objects.label.text)
print(subproxy.x)
-- prints:
-- Objects.Panel.objects.Window.objects.label.text = lorem ipsum dorem
-- Objects.Panel.objects.label.text = header
-- Objects.Panel.objects.Window.x = 400
Of course, I doubt that appending the path to the original value is what you want. Modify insides of else block:
return table.concat(path, ".") .. " = " .. tostring(object[key])
according to your needs, e.g:
register_tracked_path(table.concat(path, "."))
return object[key]
If you want to handle modification of values you need to extend the metatable with similar __newindex.
I am trying to create a dataset for ML using Scilab, and I need to save during data generation because it's too big for scilab's max stack.
Here is a toy example I made to find out what goes wrong but I'm not able to figure it out
datas=[];
labels=[];
for i =1:10
for j=1:100
if j==1
disp(i)
end
data = sin(-%pi:0.01:%pi);
label = rand();
datas = [datas, data];
labels = [labels, label];
end
save(chemin+'\test.h5','-append','datas','labels')
datas = [];
labels = [];
end
I am looking for the shape of data to be [1000,629] at the end, but I get [62900,0]
Have you any ideas why it is?
Here is an example of how to incrementally save a big matrix without any memory pressure:
// create a new HDF5 file
a = h5open(TMPDIR + "/test.h5", "w")
// create the dataset
N = 3; // number of chuncks
nrows = 5; // rows of a single chunk
ncols = 10; // cols of a single chunk
chsize = [nrows, ncols];
maxrows = N*nrows; // final number of rows of concatenated matrix
maxcols = ncols; // final number of cols of concatenated matrix
for k=1:N
// warning, x is viewed as a C-matrix (row-major), transpose if applicable
x = rand(nrows,ncols);
h5dataset(a, "My_Dataset", ...
[chsize ;1 1 ;1 1 ;chsize ;chsize],...
x, ...
[k*nrows ncols; maxrows maxcols; 1+(k-1)*nrows 1 ;1 1 ;chsize; chsize])
h5dump(a, "My_Dataset");
end
disp(a.root.My_Dataset.data)
h5close(a)
You have to vertically concatenate (semicolon) instead of horizontally (coma)
datas = [datas; data];
labels = [labels; label];
BTW this won't solve your memory problem as the matrices grow in Scilab's workspace and using "-append" just owerwrites the objects in the hdf5 file (you are using the same names).
I have code in c# windows app creating a line in a 2D sketch. And then I created a 3D sketch. Eventually I want to add a helical curve around this line from the 3D sketch. Can anyone help me please to solve this issue? Thanks in advance.
public void MyMethod(Inventor.Application ThisApplication)
{
PartDocument oSheetMetalDoc = (PartDocument)m_oInventorApp.Documents.Add(DocumentTypeEnum.kPartDocumentObject, m_oInventorApp.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject, SystemOfMeasureEnum.kMetricSystemOfMeasure, DraftingStandardEnum.kDefault_DraftingStandard, "{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}"), true);
// Set a reference to the component definition.
SheetMetalComponentDefinition oCompDef = (SheetMetalComponentDefinition)oSheetMetalDoc.ComponentDefinition;
// Set a reference to the sheet
// metal features collection.
SheetMetalFeatures oSheetMetalFeatures = (SheetMetalFeatures)oCompDef.Features;
// Create a new sketch on the X-Y work plane.
PlanarSketch oSketch = default(PlanarSketch);
oSketch = oCompDef.Sketches.Add(oCompDef.WorkPlanes[3]);
TransientGeometry oTransGeom = (TransientGeometry)ThisApplication.TransientGeometry;
// Draw a 4cm x 3cm rectangle with the
// corner at (0,0)
SketchLine line = (SketchLine)oSketch.SketchLines.AddByTwoPoints(oTransGeom.CreatePoint2d(0, 0), oTransGeom.CreatePoint2d(0, 500)); // 2. ihtimal
// skecth line turn to centerline
line.Centerline = true;
ThisApplication.ActiveView.GoHome();
// Create a 3D sketch.
Sketch3D sketch3 = (Sketch3D)oCompDef.Sketches3D.Add();
SketchEntity3D selectObj = m_oInventorApp.CommandManager.Pick(SelectionFilterEnum.kSketch3DCurveFilter, "Select 3d sketch entity");
if (selectObj == null)
{
}
// HelicalConstraint3D . want to add helical curve around the line above
}
This is iLogic/VB.net code for creating helix curve based on selected SketchLine.
Part document must be active, and at least one SketchLine must be visible for selection.
Sub Main()
Dim oSketchLine As SketchLine = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kSketchCurveLinearFilter,
"Select line")
CreateHelicalCurve(oSketchLine)
End Sub
Private Sub CreateHelicalCurve(oSketchLine As SketchLine)
Dim partDef As PartComponentDefinition = oSketchLine.Parent.Parent
Dim sketch3D As Sketch3D = partDef.Sketches3D.Add()
Dim axisStartPoint As Point = oSketchLine.StartSketchPoint.Geometry3d
Dim axisEndPoint As Point = oSketchLine.EndSketchPoint.Geometry3d
Dim curveStartPoint As Point = axisStartPoint.Copy()
curveStartPoint.TranslateBy(ThisApplication.TransientGeometry.CreateVector(0, 0, 1))
Dim diameter As Double = 5 ' [cm]
Dim pitch As Double = 1 ' [cm]
Dim revolution As Object = Nothing ' Optional argument
Dim height As Double = 5 ' [cm]
Dim helicalCurveDefinition As HelicalCurveConstantShapeDefinition = sketch3D.HelicalCurves.
CreateConstantShapeDefinition(
HelicalShapeDefinitionTypeEnum.kPitchAndHeightShapeType,
axisStartPoint,
axisEndPoint,
curveStartPoint,
diameter,
pitch,
revolution,
height
)
sketch3D.HelicalCurves.Add(helicalCurveDefinition)
End Sub
I'm trying to make a kind of "cloth simulation" by using ROBLOX's new rope constraints and a grid of parts.
Currently, I've made a 10x10 grid of .4x.4x.4 blocks and now I want to connect each one up with rope constraints.
I've named each part in the grid after their row and column (eg: first part in the grid being 1 1, last one being 10 10)
and then I get the parts around each individual grid part using their name and string manipulation.
I then insert 4 attachments into each part and 4 rope constraints.
Here's the code (ab stands for above, be stands for below, etc) :
for i2 = 1, #gParts do
local ab = tostring(tonumber(gParts[i2].Name:match("^(%S+)"))-5).." "..tostring(tonumber(string.sub(gParts[i2].Name,-1))-1)
local be = tostring(tonumber(gParts[i2].Name:match("^(%S+)"))+5).." "..tostring(tonumber(string.sub(gParts[i2].Name,-1))+1)
local le = tostring(tonumber(gParts[i2].Name:match("^(%S+)"))-1).." "..tostring(tonumber(string.sub(gParts[i2].Name,-1)))
local ri = tostring(tonumber(gParts[i2].Name:match("^(%S+)"))+1).." "..tostring(tonumber(string.sub(gParts[i2].Name,-1)))
for i3 = 1, 4 do
local atchm = Instance.new("Attachment",gParts[i2])
local ropeconst = Instance.new("RopeConstraint",gParts[i2])
end
end
Rope constraint has 2 main properties I need to use; attachment 1 and attachment 2.
I've never really messed with the new constraints, but I believe this should work.
Do keep in mind that the constraints are a new Instance in Roblox, and that they are likely still experimental.
X = 10;
Y = 10;
spread = 4;
--Spread is the Length of the Constraint. You may have to increase this, especially if it's stiff.
function createAttachments()
--This is under the assumption that gParts is a table filled with the Part Instances
for i,v in pairs(gParts) do
local atch = Instance.new("Attachment",v);
end;
end;
function connectConstraints(part,x,y)
if x ~= X then
connectRight = x+1.." "..y;
end;
if y ~= Y then
connectDown = x.." "..y+1;
end;
if connectRight ~= nil then
local ropeconst = Instance.new("RopeConstraint",part);
ropeconst.Length = spread;
ropeconst.Attachment0 = part.Attachment;
ropeconst.Attachment1 = connectRight.Attachment;
end;
if connectLeft ~= nil then
local ropeconst = Instance.new("RopeConstraint",part);
ropeconst.Length = spread;
ropeconst.Attachment0 = part.Attachment;
ropeconst.Attachment1 = connectLeft.Attachment;
end
end
createAttachments();
connectConstraints();
If this does not work for you, please let me know. I can contact you from the site itself if needed.
I'm looking to find replace text within multiple PDF documents using Draw. Thus far I've managed to open the PDF however
mydoc.createReplaceDescription
appears not to be a valid property / method on a Draw doc. Although oddly this is used in many examples for writer and calc.
Are there any alternatives?
Okay after some playing around with the recorder in the Writer I managed to record a macro that seems to be more general purpose than the createReplaceDiscription I was trying earlier.
It's got a lot of bumf that I guess could be cleaned up but it works...
REM ***** BASIC *****
Sub Main
End Sub
sub WriterFindReplace
rem ----------------------------------------------------------------------
rem define variables
dim document as object
dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem ----------------------------------------------------------------------
dim args1(18) as new com.sun.star.beans.PropertyValue
args1(0).Name = "SearchItem.StyleFamily"
args1(0).Value = 2
args1(1).Name = "SearchItem.CellType"
args1(1).Value = 0
args1(2).Name = "SearchItem.RowDirection"
args1(2).Value = true
args1(3).Name = "SearchItem.AllTables"
args1(3).Value = false
args1(4).Name = "SearchItem.Backward"
args1(4).Value = false
args1(5).Name = "SearchItem.Pattern"
args1(5).Value = false
args1(6).Name = "SearchItem.Content"
args1(6).Value = false
args1(7).Name = "SearchItem.AsianOptions"
args1(7).Value = false
args1(8).Name = "SearchItem.AlgorithmType"
args1(8).Value = 0
args1(9).Name = "SearchItem.SearchFlags"
args1(9).Value = 65536
args1(10).Name = "SearchItem.SearchString"
args1(10).Value = "<<THE WORD YOUR FINDING>>"
args1(11).Name = "SearchItem.ReplaceString"
args1(11).Value = "<< THE WORD YOUR USING TO REPLACE>>"
args1(12).Name = "SearchItem.Locale"
args1(12).Value = 255
args1(13).Name = "SearchItem.ChangedChars"
args1(13).Value = 2
args1(14).Name = "SearchItem.DeletedChars"
args1(14).Value = 2
args1(15).Name = "SearchItem.InsertedChars"
args1(15).Value = 2
args1(16).Name = "SearchItem.TransliterateFlags"
args1(16).Value = 1280
args1(17).Name = "SearchItem.Command"
args1(17).Value = 3
args1(18).Name = "Quiet"
args1(18).Value = true
dispatcher.executeDispatch(document, ".uno:ExecuteSearch", "", 0, args1())
end sub