VintaSoft Barcode .NET SDK 16.0: Руководство для .NET разработчика
Vintasoft.Barcode Namespace / ReaderSettings Class / ThresholdMode Property
Синтаксис Ремарки Пример Требования Смотрите также
В этом разделе
ThresholdMode Свойство (ReaderSettings)
В этом разделе
Возвращает или задает режим обнаружения порога.
Синтаксис
'Declaration

<DescriptionAttribute("Mode of threshold detection.")>
<DefaultValueAttribute(Automatic)>
Public Property ThresholdMode As ThresholdMode

[Description("Mode of threshold detection.")]
[DefaultValue(Automatic)]
public ThresholdMode ThresholdMode { get; set; }

Property Value

Значение по умолчанию: ThresholdMode.Automatic.
Ремарки

Цветное, палитровое или серое изображение преобразуется в черно-белое изображение перед распознаванием штрих-кодов.

Вот список шагов алгоритма преобразования изображения:

  • Вычисляет сумму компонентов цвета (T) для каждого пикселя по следующей формуле: T = R + G + B
  • Цвет пикселя меняется на черный, если T меньше порогового значения
  • Цвет пикселя изменяется на белый цвет, если T больше или равно пороговому значению

Пороговое значение может быть:
  • Рассчитано автоматически (ThresholdMode = ThresholdMode.Automatic). Используется по умолчанию.
  • Устанавливлено вручную (ThresholdMode = ThresholdMode.Manual).
    Библиотека преобразует не черно-белое изображение в черно-белое изображение с помощью Threshold и распознает штрих-коды в изображении.
  • Диапазон пороговых значений (ThresholdMode = ThresholdMode.Iterations).
    Библиотека преобразует не черно-белое изображение в N-черно-белых изображений и распознает штрих-коды с изображений, где N = ThresholdIterations, ThresholdMin - левая граница диапазона, ThresholdMax - правая граница диапазона. Процесс распознавания штрих-кодов будет прерван, если будет достигнуто значение ExpectedBarcodes.

Режим ThresholdMode.Automatic следует использовать только в том случае, если необходимо распознавать штрих-коды с множества "разных" изображений. Данный режим работает медленне, чем режим НЕ автоматические режимы, потому что приходится выполнять много операций для поиска штрих-кодов.
Необходимо использовать режим ThresholdMode.Manual, если нужно распознавать штрих-коды с "похожих" изображений.

Пример

Вот простой пример, демонстрирующий, как обнаруживать штрих-коды на цветном изображении с трудным для обнаружения порогом.

   
   
Imports Vintasoft.Imaging   
   
Imports Vintasoft.Barcode   
   
''' <summary>
''' Test that shows how to read barcodes from image using several iterations
''' with different thresholds.
''' </summary>
Class ThresholdModeExample   
   
    ''' <summary>
    ''' Runs the test.
    ''' </summary>
    Public Shared Sub Test()   
        Using barcodeImage As VintasoftBitmap = ImageCodecs.[Default].Decode("test1.jpg")   
            ReadBarcodesUsingIterationsThresholdMode(barcodeImage)   
        End Using   
    End Sub   
   
    ''' <summary>
    ''' Reads barcodes from image using several iterations with different thresholds.
    ''' </summary>
    Private Shared Sub ReadBarcodesUsingIterationsThresholdMode(barcodeImage As VintasoftBitmap)   
        ' create barcode reader
        Using reader As New BarcodeReader()   
            ' specify that reader must search for Code39, Code128 and DataMatrix barcodes only
            reader.Settings.ScanBarcodeTypes = BarcodeType.Code39 Or BarcodeType.Code128 Or BarcodeType.DataMatrix   
   
            ' specify that reader must search for horizontal and vertical barcodes only
            reader.Settings.ScanDirection = ScanDirection.Horizontal Or ScanDirection.Vertical   
   
            ' specify that reader must search for 3 barcodes
            reader.Settings.ExpectedBarcodes = 3   
   
            ' specify that reader must use 9 iterations for barcode reading,
            ' minimum threshold is 200, maximum threashold 600, threshold step is 50
            reader.Settings.AutomaticRecognition = False   
            reader.Settings.ThresholdMode = ThresholdMode.Iterations   
            reader.Settings.ThresholdIterations = 9   
            reader.Settings.ThresholdMin = 200   
            reader.Settings.ThresholdMax = 600   
   
            ' read barcodes from image
            Dim infos As IBarcodeInfo() = reader.ReadBarcodes(barcodeImage)   
   
            ' show barcode recognition results
   
            Console.WriteLine(String.Format("Recognition time {0} ms.", reader.RecognizeTime.TotalMilliseconds))   
   
            If infos.Length = 0 Then   
                Console.WriteLine("No barcodes found.")   
            Else   
                Console.WriteLine(String.Format("{0} barcodes found:", infos.Length))   
                Console.WriteLine()   
                For i As Integer = 0 To infos.Length - 1   
                    Dim info As IBarcodeInfo = infos(i)   
                    Console.WriteLine(String.Format("[{0}:{1}]", i, info.BarcodeType))   
                    Console.WriteLine(String.Format("Value:      {0}", info.Value))   
                    Console.WriteLine(String.Format("Confidence: {0}%", Math.Round(info.Confidence)))   
                    Console.WriteLine(String.Format("Threshold:  {0}", info.Threshold))   
                    Console.WriteLine(String.Format("Region:     {0}", info.Region))   
                    Console.WriteLine()   
                Next   
            End If   
        End Using   
    End Sub   
   
End Class


using System;

using Vintasoft.Imaging;

using Vintasoft.Barcode;

/// <summary>
/// Test that shows how to read barcodes from image using several iterations
/// with different thresholds.
/// </summary>
class ThresholdModeExample
{

    /// <summary>
    /// Runs the test.
    /// </summary>
    public static void Test()
    {
        using (VintasoftBitmap barcodeImage = ImageCodecs.Default.Decode("test1.jpg"))
        {
            ReadBarcodesUsingIterationsThresholdMode(barcodeImage);
        }
    }
    
    /// <summary>
    /// Reads barcodes from image using several iterations with different thresholds.
    /// </summary>
    static void ReadBarcodesUsingIterationsThresholdMode(VintasoftBitmap barcodeImage)
    {
        // create barcode reader
        using (BarcodeReader reader = new BarcodeReader())
        {
            // specify that reader must search for Code39, Code128 and DataMatrix barcodes only
            reader.Settings.ScanBarcodeTypes =
                BarcodeType.Code39 |
                BarcodeType.Code128 |
                BarcodeType.DataMatrix;

            // specify that reader must search for horizontal and vertical barcodes only
            reader.Settings.ScanDirection = ScanDirection.Horizontal | ScanDirection.Vertical;

            // specify that reader must search for 3 barcodes
            reader.Settings.ExpectedBarcodes = 3;

            // specify that reader must use 9 iterations for barcode reading,
            // minimum threshold is 200, maximum threashold 600, threshold step is 50
            reader.Settings.AutomaticRecognition = false;
            reader.Settings.ThresholdMode = ThresholdMode.Iterations;
            reader.Settings.ThresholdIterations = 9;
            reader.Settings.ThresholdMin = 200;
            reader.Settings.ThresholdMax = 600;

            // read barcodes from image
            IBarcodeInfo[] infos = reader.ReadBarcodes(barcodeImage);

            // show barcode recognition results

            Console.WriteLine(string.Format("Recognition time {0} ms.",
                reader.RecognizeTime.TotalMilliseconds));

            if (infos.Length == 0)
            {
                Console.WriteLine("No barcodes found.");
            }
            else
            {
                Console.WriteLine(string.Format("{0} barcodes found:", infos.Length));
                Console.WriteLine();
                for (int i = 0; i < infos.Length; i++)
                {
                    IBarcodeInfo info = infos[i];
                    Console.WriteLine(string.Format("[{0}:{1}]", i, info.BarcodeType));
                    Console.WriteLine(string.Format("Value:      {0}", info.Value));
                    Console.WriteLine(string.Format("Confidence: {0}%", Math.Round(info.Confidence)));
                    Console.WriteLine(string.Format("Threshold:  {0}", info.Threshold));
                    Console.WriteLine(string.Format("Region:     {0}", info.Region));
                    Console.WriteLine();
                }
            }
        }
    }

}

Требования

Целевые платформы: .NET 10; .NET 9; .NET 8; .NET 7; .NET 6; .NET Framework 4.8, 4.7, 4.6, 4.5, 4.0, 3.5

Смотрите также