VP02 5 BuildingApp-Lab5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

VisionPro Advanced

Section 2: Lab 5: Implementing Custom Behavior

The following may be used as a reference on the basic steps for building a VisionPro application in Microsoft
Visual Basic .NET. This should be used in conjunction with the notes presented in Section 2 of the class.

Objectives:

 Add Custom functionality to enable a user to re‐train a pattern.

Add The Controls

 Start by adding a new CheckBox to your form:


o Change the “Appearance” property to be “Button”.
o Change the button text to “Show Training Image”.
o Change the button name to “chkShowTrain”.
 Also add a new Button to your form:
o Change the button text to “Retrain”.
o Change the button name to “btnRetrain”.
o Change the “Enabled” property to “False”.

Disable Controls When Running

 We’ve disabled our Retrain button by default.


 Now let’s add some code so that our CheckBox is disabled whenever our CJM is running:
o Inside btnRunOnce_Click() add:

chkShowTrain.Enabled = False

o Inside chkContinuous_CheckedChanged() add:

chkShowTrain.Enabled = False

o Inside myJobManager_Stopped() add:

chkShowTrain.Enabled = True

More Button Logic

 Double‐click on the “Show Training Image” CheckBox and add the following code:

If (chkShowTrain.Checked) Then
btnRunOnce.Enabled = False
chkContinuous.Enabled = False
btnRetrain.Enabled = True
Else
btnRunOnce.Enabled = True
chkContinuous.Enabled = True
btnRetrain.Enabled = False
End If

Use two new Assemblies

 So, add references to:


• Cognex.VisionPro.ToolGroup, and
• Cognex.VisionPro.PMAlign
 Add the appropriate Imports at the top of your code:

Imports Cognex.VisionPro.ToolGroup
Imports Cognex.VisionPro.PMAlign

Declare global variables

Private myTG As CogToolGroup


Private WithEvents myPMTool As CogPMAlignTool

Display the Training Image

 To bottom of Form_Load() add:

'Creating ToolGroup object


myTG = New CogToolGroup
myTG = myJob.VisionTool

'Creating PMTool object


myPMTool = New CogPMAlignTool
myPMTool = myTG.Tools("CogPMAlignTool1")

 In chkShowTrain_CheckedChanged(), below the first half of the IF statement add:

Dim tmpRecord As Cognex.VisionPro.ICogRecord

'Extract the "TrainIMage" record and replace it with the "InputImage"


If myPMTool.InputImage IsNot Nothing Then
'Make the last acquired image the image to be used for training
myPMTool.Pattern.TrainImage = myPMTool.InputImage
tmpRecord = myPMTool.CreateCurrentRecord()
tmpRecord = tmpRecord.SubRecords.Item("TrainImage")
CogRecordDisplay1.Record = tmpRecord
CogRecordDisplay1.Fit(True)
stlStatus.Text = "Set the region/origin and click Retrain to train a
new pattern."

Else
stlStatus.Text = "There is no input image to load as a train image."
End If

 This code drills into the CJM to extract the “TrainImage” inspection record from the PMAlignTool.
 This record is shown in the display.

Erase the Training Image

 When the user pushes the “Show Training Image” button for a second time, we should erase the
training image.
 In chkShowTrain_CheckedChanged(), below the ELSE add:

'Release use of the CogRecordDisplay


CogRecordDisplay1.Record = Nothing
stlStatus.Text = "Ready"

Allow the User to Retrain

 Double‐click the “Retrain” button and type:

'Traing the new pattern


Try
myPMTool.Pattern.Train()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

If myPMTool.Pattern IsNot Nothing Then


stlStatus.Text = "Pattern trained successfully."
Else
stlStatus.Text = "Pattern NOT trained successfully."
End If

 For extra credit: Add a label to your application that always displays the “Trained”, or “Not Trained”
status of the PMAlignPattern in the CJM.
Complete Solution

Imports Cognex.VisionPro
Imports Cognex.VisionPro.QuickBuild
Imports Cognex.VisionPro.ToolGroup
Imports Cognex.VisionPro.PMAlign

Public Class Form1

Private WithEvents myJobManager As CogJobManager


Private myJob As CogJob
Private myIndependentJob As CogJobIndependent
Private myTG As CogToolGroup
Private WithEvents myPMTool As CogPMAlignTool

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As


System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

'Explictly dispose of all VisionPro controls


CogDisplayStatusBarV21.Dispose()
CogRecordDisplay1.Dispose()

'Shut down the CogJobManager to clean up threads properly


myJobManager.Shutdown()

End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles


Me.Load
'Load your QuickBuild application
myJobManager = CType( _
CogSerializer.LoadObjectFromFile( _
"C:\Documents and Settings\mperez\My
Documents\Temp\Cognex\VisionPro\Demos\DemoPlate.vpp"), _
CogJobManager)

'Initialize variable
myJob = myJobManager.Job("CogJob1")
myIndependentJob = myJob.OwnedIndependent

'Flush queues
myJobManager.UserQueueFlush()
myJobManager.FailureQueueFlush()
myJob.ImageQueueFlush()
myIndependentJob.RealTimeQueueFlush()

'Connect the status bar to the CogRecordDisplay


CogDisplayStatusBarV21.Display = CogRecordDisplay1

'Creating ToolGroup object


myTG = New CogToolGroup
myTG = myJob.VisionTool

'Creating PMTool object


myPMTool = New CogPMAlignTool
myPMTool = myTG.Tools("CogPMAlignTool1")
'Run inspection once on startup
myJobManager.Run()

End Sub

Private Sub btnRunOnce_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnRunOnce.Click

'Disable buttons while running application


btnRunOnce.Enabled = False
chkContinuous.Enabled = False
ControlBox = False
chkShowTrain.Enabled = False

'Attempt to run the application


Try
myJobManager.Run()

Catch ex As Exception
'If there is a problem show the error message
MessageBox.Show(ex.Message)
End Try

End Sub

'Delegate whose signature matches CJM events.


Delegate Sub myJobManagerDelegate(ByVal sender As Object, ByVal e As
CogJobManagerActionEventArgs)

Private Sub myJobManager_Stopped(ByVal sender As Object, ByVal e As


Cognex.VisionPro.QuickBuild.CogJobManagerActionEventArgs) Handles myJobManager.Stopped

'Check to see if we are calling Windows forms from other threads


If InvokeRequired Then
' Create a pointer to this function
Dim myDel As New myJobManagerDelegate(AddressOf myJobManager_Stopped)

' Call this same function on the correct thread


Dim eventArgs() As Object = {sender, e}
Invoke(myDel, eventArgs)

Return
End If

'Enable the buttons after running application


btnRunOnce.Enabled = True
chkContinuous.Enabled = True
ControlBox = True
chkShowTrain.Enabled = True

End Sub

Private Sub chkContinuous_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles chkContinuous.CheckedChanged
If (chkContinuous.Checked) Then

'Disable buttons while running application


btnRunOnce.Enabled = False
ControlBox = False
chkShowTrain.Enabled = False

'Attempt to run the application continuously


Try
myJobManager.RunContinuous()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Else
'Enable buttons when stopping continuous execution
chkContinuous.Enabled = True
Try
myJobManager.Stop()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If

End Sub

Private Sub myJobManager_UserResultAvailable(ByVal sender As Object, ByVal e As


Cognex.VisionPro.QuickBuild.CogJobManagerActionEventArgs) Handles
myJobManager.UserResultAvailable
'Check to see if we are calling Windows forms from other threads
If InvokeRequired Then
'Create a pointer to this function
Dim myDel As New myJobManagerDelegate(AddressOf
myJobManager_UserResultAvailable)

'Call this same function on the correct thread


Dim eventArgs() As Object = {sender, e}
Invoke(myDel, eventArgs)

Return
End If

'Declare and assign local ICogRecord variable


Dim topRecord As Cognex.VisionPro.ICogRecord = myJobManager.UserResult

'Populate status label with application information


stlStatus.Text = _
topRecord.SubRecords("UserResultTag").Content & ": " _
& topRecord.SubRecords("JobName").Content & " --> " _
& topRecord.SubRecords("RunStatus").Content.ToString

Dim tmpRecord As Cognex.VisionPro.ICogRecord


' Assume the required record is present and get it
tmpRecord = topRecord.SubRecords("ShowLastRunRecordForUserQueue")
tmpRecord = tmpRecord.SubRecords("LastRun")
tmpRecord = tmpRecord.SubRecords("CogFixtureTool1.OutputImage")
CogRecordDisplay1.Record = tmpRecord
CogRecordDisplay1.Fit(True)

End Sub

Private Sub chkShowTrain_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles chkShowTrain.CheckedChanged

If (chkShowTrain.Checked) Then
'User toggles "Show Train Image" down
btnRunOnce.Enabled = False
chkContinuous.Enabled = False
btnRetrain.Enabled = True

Dim tmpRecord As Cognex.VisionPro.ICogRecord

'Extract the "TrainIMage" record and replace it with the "InputImage"


If myPMTool.InputImage IsNot Nothing Then
'Make the last acquired image the image to be used for training
myPMTool.Pattern.TrainImage = myPMTool.InputImage
tmpRecord = myPMTool.CreateCurrentRecord()
tmpRecord = tmpRecord.SubRecords.Item("TrainImage")
CogRecordDisplay1.Record = tmpRecord
CogRecordDisplay1.Fit(True)
stlStatus.Text = "Set the region/origin and click Retrain to train a new
pattern."

Else
stlStatus.Text = "There is no input image to load as a train image."
End If

Else
'User toggles "Show Train Image" down
btnRunOnce.Enabled = True
chkContinuous.Enabled = True
btnRetrain.Enabled = False

'Release use of the CogRecordDisplay


CogRecordDisplay1.Record = Nothing
stlStatus.Text = "Ready"

End If

End Sub

Private Sub btnRetrain_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnRetrain.Click

'Traing the new pattern


Try
myPMTool.Pattern.Train()
Catch ex As Exception
'If there is a problem show the error message
MessageBox.Show(ex.Message)
End Try

If myPMTool.Pattern IsNot Nothing Then


stlStatus.Text = "Pattern trained successfully."
Else
stlStatus.Text = "Pattern NOT trained successfully."
End If
End Sub
End Class

You might also like