Gets the zero-based index of the zone under a certain point.
int HitTestZone(Leadtools.Forms.LogicalPoint point)
Function HitTestZone( _ByVal point As Leadtools.Forms.LogicalPoint _) As Integer
int HitTestZone(Leadtools.Forms.LogicalPoint point)
- (NSUInteger)hitTestZone:(LeadPoint)point public int hitTestZone(LeadPoint point) function Leadtools.Forms.Ocr.IOcrPage.HitTestZone(point)
int HitTestZone(Leadtools.Forms.LogicalPoint point)
point
The test point in logical coordinates.
The zero-based index of the zone under point, if no zone is under the test point, this method will return -1.
You can use this method to check whether a zone (either added manually or automatically) is under a given test point. For example, if you have a Windows Forms based application with the current IOcrPage in a ImageViewer control. You might want to draw the zones on the surface of the viewer. For this, you can use the GetZoneBoundsInPixels methods. If you want to allow the user to click with the mouse on the viewer to select and de-select zones, you can use HitTestZone.
This example will view the OCR Page and its zones in a ImageViewer control. It will then allow the user to select/deselect zones with the mouse.
using Leadtools;using Leadtools.Codecs;using Leadtools.Forms.Ocr;using Leadtools.Forms;using Leadtools.Forms.DocumentWriters;using Leadtools.WinForms;using Leadtools.Drawing;using Leadtools.ImageProcessing;using Leadtools.ImageProcessing.Color;// Assume Form1 is a Windows.Forms form in your application// The OCR engine we are usingprivate IOcrEngine _ocrEngine;// The OCR page we are usingprivate IOcrPage _ocrPage;// Our raster image viewer instanceprivate RasterImageViewer _viewer;public Form1(){InitializeComponent();// Initialize the raster image viewer// Turn on use DPI, center the image, add border padding and frame shadow to show that our calculations will be// independent on all of those extra options_viewer = new RasterImageViewer();_viewer.Dock = DockStyle.Fill;_viewer.BackColor = SystemColors.AppWorkspace;_viewer.UseDpi = true;_viewer.BorderPadding.All = 8;_viewer.FrameSize = new SizeF(1, 1);_viewer.FrameShadowSize = new SizeF(2, 2);_viewer.SizeMode = RasterPaintSizeMode.Normal;_viewer.HorizontalAlignMode = RasterPaintAlignMode.Center;_viewer.VerticalAlignMode = RasterPaintAlignMode.Center;_viewer.AutoDisposeImages = true;_viewer.InteractiveMode = RasterViewerInteractiveMode.None;// Turn on scale to gray painting in the viewerRasterPaintProperties props = _viewer.PaintProperties;props.PaintDisplayMode |= RasterPaintDisplayModeFlags.ScaleToGray;_viewer.PaintProperties = props;// Subscribe to the viewer events we need_viewer.KeyDown += new KeyEventHandler(_viewer_KeyDown);_viewer.MouseDown += new MouseEventHandler(_viewer_MouseDown);_viewer.PostImagePaint += new PaintEventHandler(_viewer_PostImagePaint);Controls.Add(_viewer);_viewer.BringToFront();// Create and startup the OCR engine_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Advantage, false);_ocrEngine.Startup(null, null, null, LEAD_VARS.OcrAdvantageRuntimeDir);// Load an image into the OCR documentstring tifFileName = Path.Combine(LEAD_VARS.ImagesDir, "Ocr1.tif");_ocrPage = _ocrEngine.CreatePage(_ocrEngine.RasterCodecsInstance.Load(tifFileName, 1), OcrImageSharingMode.AutoDispose);// Do auto zone_ocrPage.AutoZone(null);// AutoZone does not specify a name for the zones, so loop through all the zones and set their names// to a unique value. We will use the name in the paint code laterIOcrZoneCollection ocrZones = _ocrPage.Zones;for (int i = 0; i < ocrZones.Count; i++){OcrZone ocrZone = ocrZones[i];// Construct the name from the IDocrZone.Name = string.Format("Zone {0}", ocrZone.Id);ocrZones[i] = ocrZone;}// Show the same image in the viewer_viewer.Image = _ocrPage.GetRasterImage();// Note, the image we got from GetRasterImage is a copy of the image in the engine// Since we set teh AutoDisposeImages of the viewer to "true", the image will be disposed// when the viewer is disposed at application terminationText = "+ to zoom in, - to zoom out, enter to return to 100%. Select the zones with the mouse";}protected override void OnFormClosed(FormClosedEventArgs e){// Dispose the page_ocrPage.Dispose();// Shutdown the OCR engine_ocrEngine.Dispose();base.OnFormClosed(e);}private void _viewer_KeyDown(object sender, KeyEventArgs e){const double zoomRatio = 1.2;double scaleFactor = _viewer.ScaleFactor;switch (e.KeyCode){case Keys.Add:case Keys.Oemplus:// Zoon inscaleFactor *= zoomRatio;e.Handled = true;break;case Keys.Subtract:case Keys.OemMinus:// Zone outscaleFactor /= zoomRatio;e.Handled = true;break;case Keys.Enter:scaleFactor = 1;e.Handled = true;break;}const double minimumScaleFactor = 0.05;const double maximumScaleFactor = 11;scaleFactor = Math.Max(minimumScaleFactor, Math.Min(maximumScaleFactor, scaleFactor));// Check if scale factor has changedif (scaleFactor != _viewer.ScaleFactor){_viewer.BeginUpdate();// Yes, zoom keeping the center of the image// Get what you see in physical coordinatesRectangle rc = Rectangle.Intersect(_viewer.PhysicalViewRectangle, _viewer.ClientRectangle);// Get the center of what you see in physical coordinatesPointF center = new PointF(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2);Transformer t = new Transformer(_viewer.Transform);// Get the center of what you see in logical coordinatescenter = t.PointToLogical(center);_viewer.ScaleFactor = scaleFactor;// Bring the original center into the view centert = new Transformer(_viewer.Transform);// Get the center of what you saw before the zoom in physical coordinatescenter = t.PointToPhysical(center);// Bring the old center into the center of the view_viewer.CenterAtPoint(Point.Round(center));_viewer.EndUpdate();}}private void _viewer_MouseDown(object sender, MouseEventArgs e){// Perform hit-testing on the zonesif (_ocrEngine != null && _ocrEngine.IsStarted && _ocrPage != null && e.Button == MouseButtons.Left){// Get the transform of the viewer// Use the transform that takes the DPI into consideration since we turned that onusing (Matrix matrix = _viewer.GetTransformWithDpi()){Transformer t = new Transformer(matrix);// Convert the mouse click coordinates from physical (viewer) to logical (image)PointF point = new PointF(e.X, e.Y);point = t.PointToLogical(point);// Hit test the zones// An alternitave to calling HitTestZone is to loop through all the zones// and get the value of .Bounds in pixels, then check if the point is inside// the boundaries.LeadPoint lPoint = new LeadPoint((int)point.X, (int)point.Y);int zoneIndex = _ocrPage.HitTestZone(new LogicalPoint(lPoint));if (zoneIndex != -1){// We hit a zone, loop through all the zones, unselect all but the hit tested zonefor (int index = 0; index < _ocrPage.Zones.Count; index++){// Since OcrZone is a structure, we cannot simply do// ocrZone.Zones[index].Name = value// We have to get a copy of the structure, modify it and set it backOcrZone ocrZone = _ocrPage.Zones[index];if (index != zoneIndex)ocrZone.Name = null;elseocrZone.Name = "Selected";_ocrPage.Zones[index] = ocrZone;}// Re-paint the viewer to show the new zones_viewer.Invalidate();}}}}private void _viewer_PostImagePaint(object sender, PaintEventArgs e){// Draw the zones on the viewer in their correct locationif (_ocrEngine != null && _ocrEngine.IsStarted && _ocrPage != null){// Get the transform of the viewer// Use the transform that takes the DPI into consideration since we turned that onusing (Matrix matrix = _viewer.GetTransformWithDpi()){Transformer t = new Transformer(matrix);Pen normalPen = new Pen(Color.Blue, 1);Pen selectedPen = new Pen(Color.Red, 2);selectedPen.DashStyle = DashStyle.Dash;foreach (OcrZone ocrZone in _ocrPage.Zones){// Get the zone bounds in pixels// You can also use _ocrPage.GetZoneBoundsInPixels hereLeadRect ltzoneBounds = ocrZone.Bounds.ToRectangle(_ocrPage.DpiX, _ocrPage.DpiY);RectangleF zoneBounds = new RectangleF(ltzoneBounds.Left, ltzoneBounds.Top, ltzoneBounds.Width, ltzoneBounds.Height);// This rectangle is in image (logical) coordinates with top-left view perspective// Convert to the physical coordinates of the viewerzoneBounds = t.RectangleToPhysical(zoneBounds);// Now draw this zone on the viewer surfaceif (ocrZone.Name == "Selected")e.Graphics.DrawRectangle(selectedPen, zoneBounds.X, zoneBounds.Y, zoneBounds.Width - 1, zoneBounds.Height - 1);elsee.Graphics.DrawRectangle(normalPen, zoneBounds.X, zoneBounds.Y, zoneBounds.Width - 1, zoneBounds.Height - 1);// Draw the zone name on the left hand corner of the zone// Note, in a real application you might want to have an option to show/hide the zone names (labels)SizeF labelSize = e.Graphics.MeasureString(ocrZone.Name, Font);RectangleF labelRectangle = new RectangleF(zoneBounds.X, zoneBounds.Y - labelSize.Height, labelSize.Width, labelSize.Height);e.Graphics.FillRectangle(Brushes.Yellow, labelRectangle);e.Graphics.DrawString(ocrZone.Name, Font, Brushes.Black, labelRectangle.X, labelRectangle.Y);}}}}static class LEAD_VARS{public const string ImagesDir = @"C:\Users\Public\Documents\LEADTOOLS Images";public const string OcrAdvantageRuntimeDir = @"C:\LEADTOOLS 19\Bin\Common\OcrAdvantageRuntime";}
Imports LeadtoolsImports Leadtools.CodecsImports Leadtools.Forms.OcrImports Leadtools.FormsImports Leadtools.Forms.DocumentWritersImports Leadtools.WinFormsImports Leadtools.DrawingImports Leadtools.ImageProcessingImports Leadtools.ImageProcessing.Color' Assume Form1 is a Windows.Forms form in your application' The OCR engine we are usingPrivate _ocrEngine As IOcrEngine' The OCR page we are usingPrivate _ocrPage As IOcrPage' Our raster image viewer instancePrivate _viewer As RasterImageViewerPublic Sub New()InitializeComponent()' Initialize the raster image viewer' Turn on use DPI, center the image, add border padding and frame shadow to show that our calculations will be' independent on all of those extra options_viewer = New RasterImageViewer()_viewer.Dock = DockStyle.Fill_viewer.BackColor = SystemColors.AppWorkspace_viewer.UseDpi = True_viewer.BorderPadding.All = 8_viewer.FrameSize = New SizeF(1, 1)_viewer.FrameShadowSize = New SizeF(2, 2)_viewer.SizeMode = RasterPaintSizeMode.Normal_viewer.HorizontalAlignMode = RasterPaintAlignMode.Center_viewer.VerticalAlignMode = RasterPaintAlignMode.Center_viewer.AutoDisposeImages = True_viewer.InteractiveMode = RasterViewerInteractiveMode.None' Turn on scale to gray painting in the viewerDim props As RasterPaintProperties = _viewer.PaintPropertiesprops.PaintDisplayMode = props.PaintDisplayMode Or RasterPaintDisplayModeFlags.ScaleToGray_viewer.PaintProperties = props' Subscribe to the viewer events we needAddHandler _viewer.KeyDown, AddressOf _viewer_KeyDownAddHandler _viewer.MouseDown, AddressOf _viewer_MouseDownAddHandler _viewer.PostImagePaint, AddressOf _viewer_PostImagePaintControls.Add(_viewer)_viewer.BringToFront()' Create and startup the OCR engine_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Advantage, False)_ocrEngine.Startup(Nothing, Nothing, Nothing, LEAD_VARS.OcrAdvantageRuntimeDir)' Load an image into the OCR documentDim tifFileName As String = Path.Combine(LEAD_VARS.ImagesDir, "Ocr1.tif")_ocrPage = _ocrEngine.CreatePage(_ocrEngine.RasterCodecsInstance.Load(tifFileName, 1), OcrImageSharingMode.AutoDispose)' Do auto zone_ocrPage.AutoZone(Nothing)' AutoZone does not specify a name for the zones, so loop through all the zones and set their names' to a unique value. We will use the name in the paint code laterDim ocrZones As IOcrZoneCollection = _ocrPage.ZonesFor i As Integer = 0 To ocrZones.Count - 1Dim ocrZone As OcrZone = ocrZones(i)' Construct the name from the IDocrZone.Name = String.Format("Zone {0}", ocrZone.Id)ocrZones(i) = ocrZoneNext' Show the same image in the viewer_viewer.Image = _ocrPage.GetRasterImage()' Note, the image we got from GetRasterImage is a copy of the image in the engine' Since we set teh AutoDisposeImages of the viewer to "true", the image will be disposed' when the viewer is disposed at application terminationText = "+ to zoom in, - to zoom out, enter to return to 100%. Select the zones with the mouse"End SubProtected Overrides Sub OnFormClosed(e As FormClosedEventArgs)' Dispose the page_ocrPage.Dispose()' Shutdown the OCR engine_ocrEngine.Dispose()MyBase.OnFormClosed(e)End SubPrivate Sub _viewer_KeyDown(sender As Object, e As KeyEventArgs)Const zoomRatio As Double = 1.2Dim scaleFactor As Double = _viewer.ScaleFactorSelect Case e.KeyCodeCase Keys.Add, Keys.Oemplus' Zoon inscaleFactor *= zoomRatioe.Handled = TrueExit SelectCase Keys.Subtract, Keys.OemMinus' Zone outscaleFactor /= zoomRatioe.Handled = TrueExit SelectCase Keys.EnterscaleFactor = 1e.Handled = TrueExit SelectEnd SelectConst minimumScaleFactor As Double = 0.05Const maximumScaleFactor As Double = 11scaleFactor = Math.Max(minimumScaleFactor, Math.Min(maximumScaleFactor, scaleFactor))' Check if scale factor has changedIf scaleFactor <> _viewer.ScaleFactor Then_viewer.BeginUpdate()' Yes, zoom keeping the center of the image' Get what you see in physical coordinatesDim rc As Rectangle = Rectangle.Intersect(_viewer.PhysicalViewRectangle, _viewer.ClientRectangle)' Get the center of what you see in physical coordinatesDim center As New PointF(rc.Left + rc.Width \ 2, rc.Top + rc.Height \ 2)Dim t As New Transformer(_viewer.Transform)' Get the center of what you see in logical coordinatescenter = t.PointToLogical(center)_viewer.ScaleFactor = scaleFactor' Bring the original center into the view centert = New Transformer(_viewer.Transform)' Get the center of what you saw before the zoom in physical coordinatescenter = t.PointToPhysical(center)' Bring the old center into the center of the view_viewer.CenterAtPoint(Point.Round(center))_viewer.EndUpdate()End IfEnd SubPrivate Sub _viewer_MouseDown(sender As Object, e As MouseEventArgs)' Perform hit-testing on the zonesIf _ocrEngine IsNot Nothing AndAlso _ocrEngine.IsStarted AndAlso _ocrPage IsNot Nothing AndAlso e.Button = MouseButtons.Left Then' Get the transform of the viewer' Use the transform that takes the DPI into consideration since we turned that onUsing matrix As Matrix = _viewer.GetTransformWithDpi()Dim t As New Transformer(matrix)' Convert the mouse click coordinates from physical (viewer) to logical (image)Dim point As New PointF(e.X, e.Y)point = t.PointToLogical(point)' Hit test the zones' An alternitave to calling HitTestZone is to loop through all the zones' and get the value of .Bounds in pixels, then check if the point is inside' the boundaries.Dim lPoint As New LeadPoint(CInt(Math.Truncate(point.X)), CInt(Math.Truncate(point.Y)))Dim zoneIndex As Integer = _ocrPage.HitTestZone(New LogicalPoint(lPoint))If zoneIndex <> -1 Then' We hit a zone, loop through all the zones, unselect all but the hit tested zoneFor index As Integer = 0 To _ocrPage.Zones.Count - 1' Since OcrZone is a structure, we cannot simply do' ocrZone.Zones[index].Name = value' We have to get a copy of the structure, modify it and set it backDim ocrZone As OcrZone = _ocrPage.Zones(index)If index <> zoneIndex ThenocrZone.Name = NothingElseocrZone.Name = "Selected"End If_ocrPage.Zones(index) = ocrZoneNext' Re-paint the viewer to show the new zones_viewer.Invalidate()End IfEnd UsingEnd IfEnd SubPrivate Sub _viewer_PostImagePaint(sender As Object, e As PaintEventArgs)' Draw the zones on the viewer in their correct locationIf _ocrEngine IsNot Nothing AndAlso _ocrEngine.IsStarted AndAlso _ocrPage IsNot Nothing Then' Get the transform of the viewer' Use the transform that takes the DPI into consideration since we turned that onUsing matrix As Matrix = _viewer.GetTransformWithDpi()Dim t As New Transformer(matrix)Dim normalPen As New Pen(Color.Blue, 1)Dim selectedPen As New Pen(Color.Red, 2)selectedPen.DashStyle = DashStyle.DashFor Each ocrZone As OcrZone In _ocrPage.Zones' Get the zone bounds in pixels' You can also use _ocrPage.GetZoneBoundsInPixels hereDim ltzoneBounds As LeadRect = ocrZone.Bounds.ToRectangle(_ocrPage.DpiX, _ocrPage.DpiY)Dim zoneBounds As New RectangleF(ltzoneBounds.Left, ltzoneBounds.Top, ltzoneBounds.Width, ltzoneBounds.Height)' This rectangle is in image (logical) coordinates with top-left view perspective' Convert to the physical coordinates of the viewerzoneBounds = t.RectangleToPhysical(zoneBounds)' Now draw this zone on the viewer surfaceIf ocrZone.Name = "Selected" Thene.Graphics.DrawRectangle(selectedPen, zoneBounds.X, zoneBounds.Y, zoneBounds.Width - 1, zoneBounds.Height - 1)Elsee.Graphics.DrawRectangle(normalPen, zoneBounds.X, zoneBounds.Y, zoneBounds.Width - 1, zoneBounds.Height - 1)End If' Draw the zone name on the left hand corner of the zone' Note, in a real application you might want to have an option to show/hide the zone names (labels)Dim labelSize As SizeF = e.Graphics.MeasureString(ocrZone.Name, Font)Dim labelRectangle As New RectangleF(zoneBounds.X, zoneBounds.Y - labelSize.Height, labelSize.Width, labelSize.Height)e.Graphics.FillRectangle(Brushes.Yellow, labelRectangle)e.Graphics.DrawString(ocrZone.Name, Font, Brushes.Black, labelRectangle.X, labelRectangle.Y)NextEnd UsingEnd IfEnd SubPublic NotInheritable Class LEAD_VARSPublic Const ImagesDir As String = "C:\Users\Public\Documents\LEADTOOLS Images"Public Const OcrAdvantageRuntimeDir As String = "C:\LEADTOOLS 19\Bin\Common\OcrAdvantageRuntime"End Class
|
Products |
Support |
Feedback: HitTestZone Method - Leadtools.Forms.Ocr |
Introduction |
Help Version 19.0.2017.6.6
|

Raster .NET | C API | C++ Class Library | JavaScript HTML5
Document .NET | C API | C++ Class Library | JavaScript HTML5
Medical .NET | C API | C++ Class Library | JavaScript HTML5
Medical Web Viewer .NET
Your email has been sent to support! Someone should be in touch! If your matter is urgent please come back into chat.
Chat Hours:
Monday - Friday, 8:30am to 6pm ET
Thank you for your feedback!
Please fill out the form again to start a new chat.
All agents are currently offline.
Chat Hours:
Monday - Friday
8:30AM - 6PM EST
To contact us please fill out this form and we will contact you via email.