Dynamsoft / barcode-reader-python-samples

Samples for Dynamsoft Barcode Reader SDK Python Edition
Other
41 stars 21 forks source link

result points returned not showing the localized bar code properly with opencv #24

Closed bmabir17 closed 3 years ago

bmabir17 commented 3 years ago

I am trying to visualize the results of the scanned bar/QR Codes with opencv. But the localization_result.localization_points returned is not giving the correct position of the Codes in the image. Below is the output that i am getting. Screenshot from 2020-11-18 19-02-18 The result is always found on the top right corner of the image. Can anyone please explain how the result points data can be configured properly?

Below is my python visualization code

import os
import sys
import cv2
import json
from typing import List
from dbr import *
import glob
import random
import pandas as pd

def showResult(image,result):

    cv2.namedWindow("DynamoSoft Result", cv2.WINDOW_NORMAL)

    points = result["points"]
    cv2.line(image, points[0], points[1], color, thickness)
    cv2.line(image, points[1], points[2], color, thickness)
    cv2.line(image, points[2], points[3], color, thickness)
    cv2.line(image, points[3], points[0], color, thickness)
    cv2.putText(image, result['parsed'], points[0], cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255)) 

    # image = cv2.resize(image, (1560, 940))
    cv2.imshow("DynamoSoft Result",image)
    #add wait key. window waits till user press any key
    cv2.waitKey(0)
    #and finally destroy/Closing all open windows
    cv2.destroyWindow("DynamoSoft Result") 

# you can replace the following variables' value with yours.
license_key = "my_key"
#license_server = "Input the name/IP of the license server"
json_file = r"./settings.json"
image = r"./../test_images/IMG_0273.JPG"
# image_folder = r"./../test_images/画像元データ/*/"
image_folder = r"./../test_images/画像元データ/12.部品単体_TMコントロールECU_ラベル2/"

# To show results on image
thickness = 2
color = (0,255,0)

reader = BarcodeReader()

reader.init_license(license_key)
error = reader.init_runtime_settings_with_file(json_file)

if error[0] != EnumErrorCode.DBR_OK:
    print(error[1])

full_results = []
for idx, img in enumerate(glob.glob(os.path.join(image_folder, "*.*"))):
    result_dict = []
    print(f"Reading {img}")
    # print('Test', idx+1)
    print(40*'#')

    try:
        image = cv2.imread(img)
        text_results:List[TextResult] = reader.decode_buffer(image)

        if text_results != None:

            for text_result in text_results:
                result_list = {}
                result_list["filename"]= img
                result_list["format"] = text_result.barcode_format_string 
                result_list["parsed"] = text_result.barcode_text
                result_list["points"] = text_result.localization_result.localization_points

                print("Barcode Format :")
                print(text_result.barcode_format_string)
                print("Barcode Text :")
                print(text_result.barcode_text)
                print("Localization Points : ")
                print(text_result.localization_result.localization_points)
                print(text_result.localization_result.result_coordinate_type)
                print("-------------")
                showResult(image,result_list)
                result_dict.append(result_list)
    except BarcodeReaderError as bre:
        print(bre)

    full_results.append(result_dict)
    # print(full_results)
    print(40*'#')
# print(full_results)

And this is the settings.json file that i am using

// https://demo.dynamsoft.com/DBR/BarcodeReaderDemo.aspx
{
    "ImageParameter": {
      "AccompanyingTextRecognitionModes": [
        {
          "Mode": "ATRM_SKIP"
        }
      ],
      "BarcodeColourModes": [
        {
          "LightReflection": 1,
          "Mode": "BICM_DARK_ON_LIGHT"
        }
      ],
      "BarcodeComplementModes": [
        {
          "Mode": "BCM_SKIP"
        }
      ],
      "BarcodeFormatIds": [
        "BF_ALL"
      ],
      "BarcodeFormatIds_2": [
        "BF2_POSTALCODE",
        "BF2_DOTCODE"
      ],
      "BinarizationModes": [
        {
          "BlockSizeX": 0,
          "BlockSizeY": 0,
          "EnableFillBinaryVacancy": 1,
          "ImagePreprocessingModesIndex": -1,
          "Mode": "BM_LOCAL_BLOCK",
          "ThreshValueCoefficient": 10
        },
        {
          "BlockSizeX": 0,
          "BlockSizeY": 0,
          "EnableFillBinaryVacancy": 0,
          "ImagePreprocessingModesIndex": -1,
          "Mode": "BM_LOCAL_BLOCK",
          "ThreshValueCoefficient": 15
        }
      ],
      "ColourClusteringModes": [
        {
          "Mode": "CCM_SKIP"
        }
      ],
      "ColourConversionModes": [
        {
          "BlueChannelWeight": -1,
          "GreenChannelWeight": -1,
          "Mode": "CICM_GENERAL",
          "RedChannelWeight": -1
        }
      ],
      "DPMCodeReadingModes": [
        {
          "Mode": "DPMCRM_GENERAL"
        }
      ],
      "DeblurLevel": 9,
      "DeformationResistingModes": [
        {
          "Level": 5,
          "Mode": "DRM_GENERAL"
        }
      ],
      "Description": "",
      "ExpectedBarcodesCount": 999,
      "FormatSpecificationNameArray": null,
      "GrayscaleTransformationModes": [
        {
          "Mode": "GTM_ORIGINAL"
        },
        {
          "Mode": "GTM_INVERTED"
        }
      ],
      "ImagePreprocessingModes": [
        {
          "Mode": "IPM_GENERAL"
        }
      ],
      "IntermediateResultSavingMode": {
        "Mode": "IRSM_MEMORY"
      },
      "IntermediateResultTypes": [
        "IRT_NO_RESULT"
      ],
      "LocalizationModes": [
        {
          "Mode": "LM_CONNECTED_BLOCKS"
        },
        {
          "Mode": "LM_SCAN_DIRECTLY",
          "ScanDirection": 0,
          "ScanStride": 0
        },
        {
          "Mode": "LM_STATISTICS"
        },
        {
          "Mode": "LM_LINES"
        },
        {
          "Mode": "LM_STATISTICS_MARKS"
        },
        {
          "Mode": "LM_STATISTICS_POSTAL_CODE"
        }
      ],
      "MaxAlgorithmThreadCount": 4,
      "Name": "default",
      "PDFRasterDPI": 300,
      "PDFReadingMode": {
        "Mode": "PDFRM_AUTO"
      },
      "Pages": "",
      "RegionDefinitionNameArray": [
        "default"
      ],
      "RegionPredetectionModes": [
        {
          "Mode": "RPM_GENERAL"
        }
      ],
      "ResultCoordinateType": "RCT_PERCENTAGE",
      "ReturnBarcodeZoneClarity": 0,
      "ScaleDownThreshold": 99999,
      "ScaleUpModes": [
        {
          "Mode": "SUM_AUTO"
        }
      ],
      "TerminatePhase": "TP_BARCODE_RECOGNIZED",
      "TextAssistedCorrectionMode": {
        "BottomTextPercentageSize": 0,
        "LeftTextPercentageSize": 0,
        "Mode": "TACM_VERIFYING",
        "RightTextPercentageSize": 0,
        "TopTextPercentageSize": 0
      },
      "TextFilterModes": [
        {
          "MinImageDimension": 65536,
          "Mode": "TFM_GENERAL_CONTOUR",
          "Sensitivity": 0
        }
      ],
      "TextResultOrderModes": [
        {
          "Mode": "TROM_CONFIDENCE"
        },
        {
          "Mode": "TROM_POSITION"
        },
        {
          "Mode": "TROM_FORMAT"
        }
      ],
      "TextureDetectionModes": [
        {
          "Mode": "TDM_GENERAL_WIDTH_CONCENTRATION",
          "Sensitivity": 5
        }
      ],
      "Timeout": 99999
    },
    "RegionDefinition": {
      "BarcodeFormatIds": [
        "BF_ALL"
      ],
      "BarcodeFormatIds_2": [
        "BF2_POSTALCODE",
        "BF2_DOTCODE"
      ],
      "Bottom": 100,
      "ExpectedBarcodesCount": 0,
      "FormatSpecificationNameArray": null,
      "Left": 0,
      "MeasuredByPercentage": 1,
      "Name": "default",
      "Right": 100,
      "Top": 0
    },
    "Version": "3.0"
  }
yushulx commented 3 years ago

@bmabir17 There's something wrong with your template. The returned points will be correct if you delete the RegionDefinition part:


"RegionDefinition": {
      "BarcodeFormatIds": [
        "BF_ALL"
      ],
      "BarcodeFormatIds_2": [
        "BF2_POSTALCODE",
        "BF2_DOTCODE"
      ],
      "Bottom": 100,
      "ExpectedBarcodesCount": 0,
      "FormatSpecificationNameArray": null,
      "Left": 0,
      "MeasuredByPercentage": 1,
      "Name": "default",
      "Right": 100,
      "Top": 0
    },

image

bmabir17 commented 3 years ago

@yushulx Thank you so much. It works properly now :smile:

claire-chan commented 3 years ago

Hi @bmabir17, you set the scan region and the value of Top/Left/Right/Bottom is measured by percentage in the settings.json file, so the unit of the result points is also in percentage, not in pixel. If you would like to get the result points in pixel, you will need to change the value of ResultCoordinateType to "RCT_PIXEL" in the settings.json file.

bmabir17 commented 3 years ago

@claire-chan Thank you for your solution. I think its far more accurate solution for this problem and have implemented it.