Skip to content

Commit 1e77f9b

Browse files
update
1 parent 23f709c commit 1e77f9b

File tree

10 files changed

+303
-2
lines changed

10 files changed

+303
-2
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ pip3 install dynamsoft_barcode_reader_bundle
4343
| ----------- | ----------- |
4444
| [`ReadAnImage`](Samples/read_an_image.py) | Shows the simplest way to read barcodes from an image file and output barcode format and text. |
4545
| [`ReadMultipleImages`](Samples/read_multiple_images.py) | Shows the simplest way to read barcodes from directory with image files and output barcode format and text. |
46+
| [`GeneralSettings`](Samples/general_settings.py) | Shows how to adjust general scan settings, e.g., barcode format, barcode count, scan region. |
47+
| [`ReadDPMBarcode`](Samples/read_dpm_barcode.py) | Shows how to read DPM (Direct Part Mark) barcodes. |
48+
| [`VideoDecoding`](Samples/video_decoding.py.py) | Shows how to decode barcodes from live video or video file. |
4649

4750
## Documentation
4851

Samples/ReadDPM.json

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
{
2+
"CaptureVisionTemplates" :
3+
[
4+
{
5+
"Name" : "ReadDPM",
6+
"ImageROIProcessingNameArray" :
7+
[
8+
"roi_read_dpm"
9+
],
10+
"MaxParallelTasks" : 0,
11+
"Timeout" : 3000
12+
}
13+
],
14+
"TargetROIDefOptions" :
15+
[
16+
{
17+
"Name" : "roi_read_dpm",
18+
"TaskSettingNameArray" :
19+
[
20+
"task_read_dpm"
21+
]
22+
}
23+
],
24+
"BarcodeReaderTaskSettingOptions": [
25+
{
26+
"Name" : "task_read_dpm",
27+
"ExpectedBarcodesCount" : 1,
28+
"BarcodeFormatIds" : [ "BF_DATAMATRIX" ],
29+
"LocalizationModes" : [
30+
{
31+
"Mode": "LM_STATISTICS_MARKS"
32+
},
33+
{
34+
"Mode": "LM_CONNECTED_BLOCKS"
35+
}
36+
],
37+
"DPMCodeReadingModes":
38+
[
39+
{
40+
"Mode": "DPMCRM_GENERAL"
41+
}
42+
]
43+
}
44+
]
45+
}

Samples/general_settings.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import os
2+
from dynamsoft_barcode_reader_bundle import *
3+
if __name__ == "__main__":
4+
try:
5+
# 1.Initialize license.
6+
# The string "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" here is a free public trial license. Note that network connection is required for this license to work.
7+
# You can also request a 30-day trial license in the customer portal: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=samples&package=python
8+
err_code, err_str = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9")
9+
if err_code != EnumErrorCode.EC_OK and err_code != EnumErrorCode.EC_LICENSE_CACHE_USED:
10+
print("License initialization failed: ErrorCode:", err_code, ", ErrorString:", err_str)
11+
else:
12+
# 2. Create an instance of CaptureVisionRouter.
13+
cvr_instance = CaptureVisionRouter()
14+
15+
# 3. General settings (including barcode format, barcode count and scan region) through SimplifiedCaptureVisionSettings
16+
# 3.1 Obtain current runtime settings of instance.
17+
err_code, err_str, settings = cvr_instance.get_simplified_settings(EnumPresetTemplate.PT_READ_BARCODES)
18+
19+
# 3.2 Set the expected barcode format you want to read.
20+
settings.barcode_settings.barcode_format_ids = EnumBarcodeFormat.BF_POSTALCODE | EnumBarcodeFormat.BF_DOTCODE
21+
22+
# 3.3 Set the expected barcode count you want to read.
23+
settings.barcode_settings.expected_barcodes_count = 10
24+
25+
# 3.4 Set the grayscale transformation modes.
26+
settings.barcode_settings.grayscale_transformation_modes[0] = EnumGrayscaleTransformationMode.GTM_AUTO
27+
28+
# 3.5 Set the ROI(region of interest) to speed up the barcode reading process.
29+
# Note: DBR supports setting coordinates by pixels or percentages. The origin of the coordinate system is the upper left corner point.
30+
settings.roi_measured_in_percentage = 1
31+
points = settings.roi.points
32+
points[0].x = 0
33+
points[0].y = 0
34+
points[1].x = 100
35+
points[1].y = 0
36+
points[2].x = 100
37+
points[2].y = 100
38+
points[3].x = 0
39+
points[3].y = 100
40+
41+
# 3.6 Apply the new settings to the instance.
42+
err_code, err_str = cvr_instance.update_settings(EnumPresetTemplate.PT_READ_BARCODES, settings)
43+
if err_code != EnumErrorCode.EC_OK:
44+
print("Update settings failed: ErrorCode:", err_code, ", ErrorString:", err_str)
45+
# 4.Replace by your own image path
46+
image_path = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "../images/AllSupportedBarcodeTypes.png"
47+
48+
# 5.Decode barcodes from an image file.
49+
result = cvr_instance.capture(image_path, EnumPresetTemplate.PT_READ_BARCODES)
50+
51+
# 6.Output the barcode text.
52+
if result.get_error_code() != EnumErrorCode.EC_OK:
53+
print("Error:", result.get_error_code(), result.get_error_string())
54+
barcode_result = result.get_decoded_barcodes_result()
55+
if barcode_result is None or barcode_result.get_items() == 0:
56+
print("No barcode detected.")
57+
else:
58+
items = barcode_result.get_items()
59+
print("Decoded", len(items), "barcodes.")
60+
for index,item in enumerate(items):
61+
print()
62+
print("Barcode", index)
63+
print("Barcode Format:", item.get_format_string())
64+
print("Barcode Text:", item.get_text())
65+
except Exception as e:
66+
print(e)

Samples/read_an_image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
print("License initialization failed: ErrorCode:", errorCode, ", ErrorString:", errorMsg)
1111
else:
1212
cvr = CaptureVisionRouter()
13-
result = cvr.capture("../Images/GeneralBarcodes.png", EnumPresetTemplate.PT_READ_BARCODES.value)
13+
result = cvr.capture("../images/GeneralBarcodes.png", EnumPresetTemplate.PT_READ_BARCODES)
1414
if result.get_error_code() != EnumErrorCode.EC_OK:
1515
print("Error:", result.get_error_code(), result.get_error_string())
1616
barcode_result = result.get_decoded_barcodes_result()

Samples/read_dpm_barcode.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import os
2+
from dynamsoft_barcode_reader_bundle import *
3+
4+
if __name__ == "__main__":
5+
try:
6+
# 1 Initialize license.
7+
# The string "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" here is a free public trial license. Note that network connection is required for this license to work.
8+
# You can also request a 30-day trial license in the customer portal: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=samples&package=python
9+
errorCode, errorMsg = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9")
10+
if errorCode != EnumErrorCode.EC_OK and errorCode != EnumErrorCode.EC_LICENSE_CACHE_USED:
11+
raise Exception("License initialization failed: ErrorCode: "+ str(errorCode) + ", ErrorString:" + errorMsg)
12+
else:
13+
cvr_instance = CaptureVisionRouter()
14+
template_path = os.path.dirname(os.path.abspath(__file__)) + os.path.sep +"ReadDPM.json"
15+
errorCode, errorMsg = cvr_instance.init_settings_from_file(template_path)
16+
if errorCode != EnumErrorCode.EC_OK:
17+
raise Exception("Init template failed: " + errorMsg)
18+
19+
# 2 Replace with your own dpm barcode image path
20+
image_path = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "../images/dpm.jpg"
21+
22+
# 3 Decode barcodes from an image file by current runtime settings. The second parameter value "" means to decode through the current PublicRuntimeSettings.
23+
result = cvr_instance.capture(image_path,"")
24+
25+
# 4 Output the barcode format and barcode text.
26+
if result.get_error_code() != EnumErrorCode.EC_OK:
27+
print("Error:", result.get_error_code(), result.get_error_string())
28+
barcode_result = result.get_decoded_barcodes_result()
29+
if barcode_result is None or barcode_result.get_items() == 0:
30+
print("No barcode detected.")
31+
else:
32+
items = barcode_result.get_items()
33+
print("Decoded", len(items), "barcodes.")
34+
for index,item in enumerate(items):
35+
print()
36+
print("Barcode", index)
37+
print("Barcode Format:", item.get_format_string())
38+
print("Barcode Text:", item.get_text())
39+
40+
except Exception as e:
41+
print(e)

Samples/read_multiple_images.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,5 @@ def on_image_source_state_received(self, state: int) -> None:
4949

5050
errorCode, errorMsg = cvr.start_capturing("", True)
5151
if errorCode != EnumErrorCode.EC_OK:
52-
print("error:", errorMsg)
52+
print("Error:", errorMsg)
5353
input("Press Enter to quit...")

Samples/video_decoding.py

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
from dynamsoft_barcode_reader_bundle import *
2+
import cv2
3+
import os
4+
class MyCapturedResultReceiver(CapturedResultReceiver):
5+
6+
def __init__(self):
7+
super().__init__()
8+
9+
def on_decoded_barcodes_received(self, result: DecodedBarcodesResult) -> None:
10+
if result.get_error_code() != EnumErrorCode.EC_OK:
11+
print("Error:", result.get_error_string())
12+
else:
13+
items = result.get_items()
14+
if len(items) != 0:
15+
tag: ImageTag = result.get_original_image_tag()
16+
if tag is not None:
17+
print("ImageID:",tag.get_image_id())
18+
print("Decoded", len(items), "barcodes.")
19+
for index,item in enumerate(items):
20+
print("Result", index+1)
21+
print("Barcode Format:", item.get_format_string())
22+
print("Barcode Text:", item.get_text())
23+
print()
24+
class MyVideoFetcher(ImageSourceAdapter):
25+
26+
def __init__(self):
27+
super().__init__()
28+
29+
def has_next_image_to_fetch(self) -> bool:
30+
return True
31+
32+
def decode_video(use_video_file: bool = False, video_file_path: str = "") -> None:
33+
cvr_instance = CaptureVisionRouter()
34+
35+
fetcher = MyVideoFetcher()
36+
fetcher.set_max_image_count(100)
37+
fetcher.set_buffer_overflow_protection_mode(EnumBufferOverflowProtectionMode.BOPM_UPDATE)
38+
fetcher.set_colour_channel_usage_type(EnumColourChannelUsageType.CCUT_AUTO)
39+
cvr_instance.set_input(fetcher)
40+
41+
filter = MultiFrameResultCrossFilter()
42+
filter.enable_result_cross_verification(EnumCapturedResultItemType.CRIT_BARCODE, True)
43+
filter.enable_result_deduplication(EnumCapturedResultItemType.CRIT_BARCODE, True)
44+
filter.set_duplicate_forget_time(EnumCapturedResultItemType.CRIT_BARCODE, 5000)
45+
cvr_instance.add_result_filter(filter)
46+
47+
receiver = MyCapturedResultReceiver()
48+
cvr_instance.add_result_receiver(receiver)
49+
50+
error_code, error_msg = cvr_instance.start_capturing(EnumPresetTemplate.PT_READ_BARCODES, False)
51+
if error_code != EnumErrorCode.EC_OK:
52+
print("Error:", error_msg)
53+
else:
54+
video_width = 0
55+
video_height = 0
56+
vc: cv2.VideoCapture = None
57+
if not use_video_file:
58+
# a. Decode video from camera
59+
vc = cv2.VideoCapture(0)
60+
else:
61+
# # b. Decode video file
62+
vc = cv2.VideoCapture(video_file_path)
63+
64+
video_width = int(vc.get(cv2.CAP_PROP_FRAME_WIDTH))
65+
video_height = int(vc.get(cv2.CAP_PROP_FRAME_HEIGHT))
66+
vc.set(3, video_width) #set width
67+
vc.set(4, video_height) #set height
68+
69+
if not vc.isOpened():
70+
cvr_instance.stop_capturing(False, True)
71+
return
72+
73+
windowName = "Video Barcode Reader"
74+
75+
image_id = 0
76+
while True:
77+
image_id += 1
78+
rval, frame = vc.read()
79+
if rval == False:
80+
break
81+
tag = FileImageTag("",0,0)
82+
tag.set_image_id(image_id)
83+
image = ImageData(frame.tobytes(), frame.shape[1], frame.shape[0], frame.strides[0], EnumImagePixelFormat.IPF_RGB_888, 0, tag)
84+
fetcher.add_image_to_buffer(image)
85+
cv2.imshow(windowName, frame)
86+
# 'ESC' for quit
87+
key = cv2.waitKey(1)
88+
if key == 27:
89+
break
90+
91+
cvr_instance.stop_capturing(False, True)
92+
cv2.destroyWindow(windowName)
93+
94+
def get_mode_and_path():
95+
use_video_file = False
96+
video_file_path = ""
97+
while True:
98+
try:
99+
mode = int(
100+
input(
101+
">> Choose a Mode Number:\n"
102+
"1. Decode video from camera.\n"
103+
"2. Decode video from file.\n"
104+
">> 1 or 2:\n"
105+
))
106+
if mode == 1 or mode == 2:
107+
if mode == 1:
108+
use_video_file = False
109+
break
110+
111+
use_video_file = True
112+
while True:
113+
video_file_path = input(">> Input your video full path:\n").strip('\'"')
114+
if not os.path.exists(video_file_path):
115+
print("Error:File not found.\n")
116+
continue
117+
break
118+
break
119+
else:
120+
raise ValueError
121+
except ValueError:
122+
print("Error:Wrong input.\n")
123+
continue
124+
125+
return use_video_file, video_file_path
126+
127+
if __name__ == "__main__":
128+
129+
print("-------------------start------------------------")
130+
131+
try:
132+
# Initialize license.
133+
# The string "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" here is a free public trial license. Note that network connection is required for this license to work.
134+
# You can also request a 30-day trial license in the customer portal: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=samples&package=python
135+
errorCode, errorMsg = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9")
136+
if errorCode != EnumErrorCode.EC_OK and errorCode != EnumErrorCode.EC_LICENSE_CACHE_USED:
137+
print("License initialization failed: ErrorCode:", errorCode, ", ErrorString:", errorMsg)
138+
else:
139+
# Decode video from file or camera
140+
use_video_file, video_file_path = get_mode_and_path()
141+
decode_video(use_video_file, video_file_path)
142+
143+
except Exception as e:
144+
print(e)
145+
146+
print("-------------------over------------------------")
335 KB
Loading

images/DPM.png

128 KB
Loading

images/dpm.jpg

64.8 KB
Loading

0 commit comments

Comments
 (0)