Code error for contour anlaysis in VB.net - vb.net

I'm trying to use emgu.cv lib for contour function in vb.net. The problem is my var is not defined. This should come under lib emgu.cv which I have already imported.
Dim borderPen As New Pen(Color.FromArgb(150, 0, 255, 0))
Dim processor As ImageProcessor
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs)
Dim borderPen As New Pen(Color.FromArgb(150, 0, 255, 0))
If RadioButton1.Checked = True Then
For Each contour As var In processor.contours
If contour.Total > 1 Then
e.Graphics.DrawLines(Pens.Red, contour.ToArray())
End If
Next
End If
SyncLock processor.foundTemplates
For Each found As FoundTemplateDesc In processor.foundTemplates
If found.template.name.EndsWith(".png") OrElse found.template.name.EndsWith(".jpg") Then
DrawAugmentedReality(found, e.Graphics)
Continue For
End If
Next
End SyncLock
End Sub
Private Sub DrawAugmentedReality(found As FoundTemplateDesc, gr As Graphics)
Dim fileName As String = "C:\Users\pnasguna\Desktop\A56.jpg"
Dim AugmentedRealityImages As New Dictionary(Of String, Image)()
Dim img As Image = AugmentedRealityImages(fileName)
Dim p As Point = found.sample.contour.SourceBoundingRect.Center()
Dim state = gr.Save()
gr.TranslateTransform(p.X, p.Y)
gr.RotateTransform(CSng(180.0F * found.angle / Math.PI))
gr.ScaleTransform(CSng(found.scale), CSng(found.scale))
gr.DrawImage(img, New Point(-img.Width / 2, -img.Height / 2))
gr.Restore(state)
End Sub
I could not compile as var is not defined. How to fix this problem?

You get the Type <typename> is not defined error because the type var is not defined. You fix this by doing one of the following steps:
Remove As var.
For Each contour In processor.contours
Replace var with the correct data type.
For Each contour As <THE_CORRECT_TYPE> In processor.contours
Emgu
Looking at the source code for emgu (written in C#), the ImageProcessor.cs file will reveal the data type of contours:
public List<Contour<Point>> contours;
Translated into vb.net:
Public contours As List(Of Contour(Of Point))
Solution
So with this information it's pretty easy to pick the correct data type.
For Each contour As Contour(Of Point) In Me.processor.contours
Note: You should always have Option Strict set to On.

Related

making a function that does stuff to pictureboxes?

Function myFunction(ByVal degree1 As PictureBox) As PictureBox
degree1.Visible = True
degree1.Image = Image.FromFile("C:\Standard Pics\waiting3.gif")
degree1.Location = New Point(locationx, locationy)
degree1.Size = New Size(51, 51)
End Function
I'm very new to making functions in visual basic- anyway, I'm trying to make a function that makes several changes to a picturebox, but it gives me this "Argument not specified for parameter 'degree1' of 'Public Function myFunction(ByVal degree1 As PictureBox) As PictureBox'" error- any possible fixes?
Please try following:
Sub mySub(ByRef degree1 As PictureBox)
degree1.Visible = True
degree1.Image = Image.FromFile("C:\Standard Pics\waiting3.gif")
degree1.Location = New Point(locationx, locationy)
degree1.Size = New Size(51, 51)
End Sub
Note the ByRef part in Sub() signature - it means that you're directly operating over given PictureBox object. This is called "passing argument by reference". You can read more about it here. Oh, and I presume you have your locationx and locationy variables set somewhere in your code?

How to center text on Y axis when force wrapping a string

I force wrap some of my text. The following method is used in a loop when I do this; it returns the Y cord for the next line (based on the string height). This works like a charm, however I lose the ability to center the text vertically.
I'm looking for suggestions on how to enhance this method to allow for vertical centering.
<Extension()> _
Public Function DrawText(ByVal p_graphics As Graphics, ByVal p_text As String, ByVal p_Font As Font, ByVal p_fontColor As Brush, ByVal p_X As Decimal, ByVal p_Y As Decimal, _
ByVal p_boundingWidth As Decimal, ByVal p_StringFormat As StringFormat) As Decimal
If String.IsNullOrEmpty(p_text) Then
Return p_Y
End If
Dim _sizef As SizeF = p_graphics.MeasureString(p_text, p_Font, Integer.MaxValue, p_StringFormat)
Dim _LineCnt As Integer = Math.Ceiling(_sizef.Width / p_boundingWidth)
Dim _height As Integer = Math.Ceiling(_LineCnt * Math.Ceiling(_sizef.Height))
p_graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
Dim _rec As New RectangleF(p_X, p_Y, p_boundingWidth, _height)
p_graphics.DrawString(p_text, p_Font, p_fontColor, _rec, p_StringFormat)
Return (p_Y + _rec.Height)
End Function
Example of how I use this extension method (writing this free hand so syntax may not be correct):
.
.
.
Using g as graphics.FromImage(_MyImage)
Dim _LineStart as integer = 0
Foreach _line as string in _Lines 'List of String
_LineStart = g.DrawText(line, _font, Obj.FontColorBrush, 0, _LineStart, Obj.DPIWidth, Obj.StringFormat)
End For
End Using
.
.
.
OK, now I think I understand. You need to calculate where to start drawing vertically.
I put a PictureBox and a Button on a form, added your extension method, and used this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines As New List(Of String)
lines.Add("The quick brown")
lines.Add("fox jumps over")
lines.Add("the lazy dog.")
lines.Add("This line is too wide to fit the available space.")
Dim fmt = StringFormat.GenericTypographic
fmt.Alignment = StringAlignment.Center
Using fnt = New Font("Arial", 8)
Using brsh = New SolidBrush(Color.Black)
Using g = PictureBox1.CreateGraphics
Dim lineY As Integer = (PictureBox1.Height - lines.Count * fnt.Height) \ 2
For Each line As String In lines
lineY = CInt(g.DrawText(line, fnt, brsh, 0, lineY, PictureBox1.Width, fmt))
Next
End Using
End Using
End Using
End Sub
As I use Option Strict On, I had to make some minor modifications to your DrawText method.
Note how the line which is too long is truncated. Centred, but truncated. That is where you might want to use the Graphics.MeasureString Method (String, Font, SizeF, StringFormat) overload so that you have the possibility of it wrapping automatically. Which will of course mess up the calculation for the vertical centring.

Dropping shadow on WinForm distorts interface

I'm using the following code to create a Windows7 style drop shadow effect on my WinForms:
<DllImport("dwmapi.dll", PreserveSig:=True)> _
Private Shared Function DwmSetWindowAttribute(hwnd As IntPtr, attr As Integer, ByRef attrValue As Integer, attrSize As Integer) As Integer
End Function
<DllImport("dwmapi.dll")> _
Private Shared Function DwmExtendFrameIntoClientArea(hWnd As IntPtr, ByRef pMarInset As Margins) As Integer
End Function
Private Function CreateDropShadow() As Boolean
Try
Dim val As Integer = 2
Dim ret1 As Integer = DwmSetWindowAttribute(Me.Handle, 2, val, 4)
If ret1 = 0 Then
Dim m As New Margins(0, 0, 0, 0)
Dim ret2 As Integer = DwmExtendFrameIntoClientArea(Me.Handle, m)
Return ret2 = 0
Else
Return False
End If
Catch ex As Exception
' Probably dwmapi.dll not found (incompatible OS)
Return False
End Try
End Function
Protected Overrides Sub OnHandleCreated(e As EventArgs)
CreateDropShadow()
MyBase.OnHandleCreated(e)
End Sub
The result of above code creates a nice drop shadow effect on my borderless winform, but it causes the UI to distort. All the controls and labels on my form aren't appearing properly, with text not readable.
Am I missing something here? I don't want to use the traditional drop shadow effect using CreateParams, its too 'boxy' look and doesn't give a nice shadow effect.
Here are screenshots of without shadow and with shadow:
Thanks.
Dim m As New Margins(0, 0, 0, 0)
There's a subtle mistake visible here, looks a lot like you are using System.Drawing.Printing.Margins. But that's not a type that's compatible with the Windows' MARGINS type. Which is a structure, not a class.
So this just goes complete wrong, Windows reads nonsense instead of (0, 0, 0, 0). And extends the frame into the entire client area. Which then plays havoc on any control that draws with GDI, it is a 24bpp drawing api that leaves the alpha at 0 so anything that should be black becomes transparent instead.
Fix this by declaring a proper MARGINS structure:
Structure MARGINS
Public Left, Right, Top, Bottom As Integer
End Structure

store and play microphone data in real time vb.net

as the title says, i'm trying to store and play microphone data in real time with vb.net 2010 and NAudio library. I got this code in C# from the NAudio Codeplex website and i translated it in vb.net.
There's no error in the code and the program works (i put a counter that keeps increasing and updating a label each time mic data is available to see if it's actually working), but i can't hear anything.
here is the code
Imports NAudio
Imports System.IO
'Libraries I'm using
Private Sub wi_dataAvailable(ByVal obj As Object, ByVal e As Wave.WaveInEventArgs) Handles wi.DataAvailable
count += 1 'here is where the counter increases
Label1.Text = count 'and here the label is updated and it seems to work fine
play_packet(e.Buffer)
End Sub
Private Sub play_packet(ByVal DR() As Byte)
Dim MS As New MemoryStream(DR)
Dim frmt As New Wave.WaveFormat
frmt = Wave.WaveFormat.CreateALawFormat(8000, 1)
Dim rsws As New Wave.RawSourceWaveStream(MS, frmt)
Dim pcms As Wave.WaveStream = Wave.WaveFormatConversionStream.CreatePcmStream(rsws)
Dim m_bwp As New Wave.BufferedWaveProvider(New Wave.WaveFormat(8000, 16, 1))
Dim dec() As Byte = cnssb(pcms)
m_bwp.AddSamples(dec, 0, dec.Length)
Dim latency As Integer
Dim cbi As Wave.WaveCallbackInfo = Wave.WaveCallbackInfo.NewWindow
Dim out_dev As New Wave.WaveOut(cbi)
out_dev.DesiredLatency = latency
out_dev.Init(m_bwp)
out_dev.Play()
End Sub
Private Function cnssb(ByVal nss As Wave.WaveStream) As Byte()
Dim memstr As New MemoryStream
Dim buff(1024) As Byte
Dim bytes As Integer
bytes = nss.Read(buff, 0, buff.Length)
While bytes > 0
memstr.Write(buff, 0, bytes)
bytes = nss.Read(buff, 0, buff.Length)
End While
Dim by() As Byte = memstr.ToArray
Return by
End Function
hope you can help me!
You shouldn't be creating a new WaveOut and BufferedWaveProvider every time a recorded buffer is received. Instead create one of each, and just add the audio into the BufferedWaveProvider as you receive it.
Solved!
I declared a boolean variable and then i edited the play_packet function like this:
dim initialized as boolean
'in the form load i set the variable to false
'and then here is the function
Private Sub play_packet(ByVal DR() As Byte)
Dim MS As New MemoryStream(DR)
Dim dec() As Byte = MS.ToArray
m_bwp.AddSamples(dec, 0, dec.Length)
MS.Close()
MS.Dispose()
Dim latency As Integer = 50
Dim cbi As Wave.WaveCallbackInfo = Wave.WaveCallbackInfo.NewWindow
Dim out_dev As New Wave.DirectSoundOut
out_dev.Volume = 1
If initialized = False Then
out_dev.Init(m_bwp)
out_dev.Play()
initialized = True
End If
End Sub

How can I specify a printer other than the default printer?

I'd like to be able to specify two different printers for two different jobs. I'm using the following class to handle printing these, but regardless of what I do, the default printer is always the one that's printed to.
Public Class Receipt : Inherits Printing.PrintDocument
Private _font As Font = New Font("Courier", 8)
Private _text As String = ""
Public Property Text() As String
Get
Return _text
End Get
Set(ByVal Value As String)
_text = Value.Trim
End Set
End Property
Public Sub New(ByVal str As String, ByVal settings As Printing.PrinterSettings)
MyBase.New()
_text = str
Me.PrinterSettings = settings
End Sub
Protected Overrides Sub OnPrintPage(ByVal e As Printing.PrintPageEventArgs)
Dim printHeight As Integer
Dim printWidth As Integer
Dim leftMargin As Integer
Dim rightMargin As Integer
With Me.DefaultPageSettings
.PaperSize = New System.Drawing.Printing.PaperSize("Custom", 300, 1200)
.Margins.Left = 25
.Margins.Right = 25
printHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
printWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
leftMargin = .Margins.Left
rightMargin = .Margins.Top
End With
Dim printArea As New RectangleF(leftMargin, rightMargin, printWidth, printHeight)
Dim format As New StringFormat(StringFormatFlags.LineLimit)
Try
e.Graphics.DrawString(_text, _font, Brushes.Black, printArea, format)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If I inspect my PrinterSettings attribute immediately before the call to DrawString, the PrinterName attribute is still correctly set to the printer I specify, but it's still the default printer that kicks out the job. I'm sure I'm missing something obvious, but would certainly appreciate if someone could point out what it is. :)
Thanks
I just created a test app with the class code you posted and it works fine. It uses whatever printer I select. So I must conclude that wherever you are using this class you're accidentally altering the PrintSettings object after you initialize the object but before you call Print.
Or perhaps the printer name you specify isn't valid and the default is used as a backup. You can check this using PrinterSettings.IsValid after setting the PrinterName property.
The PrinterSettings.PrinterName property is actually what you should be using.
You can get a list of installed printers using PrinterSettings.InstalledPrinters (System.Drawing.Printing namespace). Perhaps your provider printer name is slightly different from what it should be, because I can confirm this actually works.