-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathvideo_decoding.py
More file actions
205 lines (178 loc) · 7.69 KB
/
Copy pathvideo_decoding.py
File metadata and controls
205 lines (178 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from dynamsoft_barcode_reader_bundle import *
try:
import cv2
except ModuleNotFoundError:
raise SystemExit(
"OpenCV is required for this sample.\n"
"Install it with:\n"
" python -m pip install opencv-python\n"
)
import os
def can_show_preview_window() -> bool:
if os.name == "nt":
return True
return bool(
os.environ.get("DISPLAY")
or os.environ.get("WAYLAND_DISPLAY")
or os.environ.get("MIR_SOCKET")
)
def silence_opencv():
# OpenCV 4.5+
if hasattr(cv2, "setLogLevel"):
try:
cv2.setLogLevel(0) # LOG_LEVEL_SILENT
return
except Exception:
pass
if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"):
try:
cv2.utils.logging.setLogLevel(
cv2.utils.logging.LOG_LEVEL_SILENT
)
except Exception:
pass
class MyCapturedResultReceiver(CapturedResultReceiver):
def __init__(self):
super().__init__()
def on_decoded_barcodes_received(self, result: DecodedBarcodesResult) -> None:
if result.get_error_code() == EnumErrorCode.EC_UNSUPPORTED_JSON_KEY_WARNING:
print("Warning:", result.get_error_string())
elif result.get_error_code() != EnumErrorCode.EC_OK:
print("Error:", result.get_error_string())
items = result.get_items()
if len(items) != 0:
tag: ImageTag = result.get_original_image_tag()
if tag is not None:
print("ImageID:",tag.get_image_id())
print("Decoded", len(items), "barcodes.")
for index,item in enumerate(items):
print("Result", index+1)
print("Barcode Format:", item.get_format_string())
print("Barcode Text:", item.get_text())
print()
class MyVideoFetcher(ImageSourceAdapter):
def __init__(self):
super().__init__()
def has_next_image_to_fetch(self) -> bool:
return True
def decode_video(use_video_file: bool = False, video_file_path: str = "") -> None:
cvr_instance = CaptureVisionRouter()
fetcher = MyVideoFetcher()
fetcher.set_max_image_count(100)
fetcher.set_buffer_overflow_protection_mode(EnumBufferOverflowProtectionMode.BOPM_UPDATE)
fetcher.set_colour_channel_usage_type(EnumColourChannelUsageType.CCUT_AUTO)
cvr_instance.set_input(fetcher)
filter = MultiFrameResultCrossFilter()
filter.enable_result_cross_verification(EnumCapturedResultItemType.CRIT_BARCODE, True)
filter.enable_result_deduplication(EnumCapturedResultItemType.CRIT_BARCODE, True)
filter.set_duplicate_forget_time(EnumCapturedResultItemType.CRIT_BARCODE, 5000)
cvr_instance.add_result_filter(filter)
receiver = MyCapturedResultReceiver()
cvr_instance.add_result_receiver(receiver)
error_code, error_msg = cvr_instance.start_capturing(EnumPresetTemplate.PT_READ_BARCODES, False)
if error_code != EnumErrorCode.EC_OK:
print("Error:", error_msg)
else:
video_width = 0
video_height = 0
vc: cv2.VideoCapture = None
if not use_video_file:
# a. Decode video from camera
vc = cv2.VideoCapture(0)
if not vc.isOpened():
cvr_instance.stop_capturing(False, True)
raise RuntimeError("Camera not found or cannot be opened")
else:
# # b. Decode video file
vc = cv2.VideoCapture(video_file_path)
if not vc.isOpened():
cvr_instance.stop_capturing(False, True)
raise RuntimeError("File not found or cannot be opened")
video_width = int(vc.get(cv2.CAP_PROP_FRAME_WIDTH))
video_height = int(vc.get(cv2.CAP_PROP_FRAME_HEIGHT))
vc.set(3, video_width) #set width
vc.set(4, video_height) #set height
if not vc.isOpened():
cvr_instance.stop_capturing(False, True)
return
windowName = "Video Barcode Reader"
show_preview = can_show_preview_window()
if not show_preview:
print("Warning: GUI display not available, running in headless mode without preview window.")
image_id = 0
while True:
image_id += 1
rval, frame = vc.read()
if rval == False:
break
tag = FileImageTag("",0,0)
tag.set_image_id(image_id)
image = ImageData(frame.tobytes(), frame.shape[1], frame.shape[0], frame.strides[0], EnumImagePixelFormat.IPF_RGB_888, 0, tag)
fetcher.add_image_to_buffer(image)
if show_preview:
try:
cv2.imshow(windowName, frame)
# 'ESC' for quit
key = cv2.waitKey(1)
if key == 27:
break
except cv2.error as e:
print("Warning: OpenCV GUI is unavailable. Switch to headless mode. Details:", e)
show_preview = False
except Exception as e:
print("Warning: Failed to show preview window. Switch to headless mode. Details:", e)
show_preview = False
cvr_instance.stop_capturing(True, True)
vc.release()
if show_preview:
try:
cv2.destroyWindow(windowName)
except Exception as e:
print("Warning: Failed to destroy preview window. Details:", e)
def get_mode_and_path():
use_video_file = False
video_file_path = ""
while True:
try:
mode = int(
input(
">> Choose a Mode Number:\n"
"1. Decode video from camera.\n"
"2. Decode video from file.\n"
">> 1 or 2:\n"
))
if mode == 1 or mode == 2:
if mode == 1:
use_video_file = False
break
use_video_file = True
while True:
video_file_path = input(">> Input your video full path:\n").strip(' \'"')
if not os.path.exists(video_file_path):
print("Error:File not found.\n")
continue
break
break
else:
raise ValueError
except ValueError:
print("Error:Wrong input.\n")
continue
return use_video_file, video_file_path
if __name__ == "__main__":
silence_opencv()
print("-------------------start------------------------")
try:
# Initialize license.
# The string "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" here is a free public trial license. Note that network connection is required for this license to work.
# 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
errorCode, errorMsg = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9")
if errorCode != EnumErrorCode.EC_OK and errorCode != EnumErrorCode.EC_LICENSE_WARNING:
print("License initialization failed: ErrorCode:", errorCode, ", ErrorString:", errorMsg)
else:
# Decode video from file or camera
use_video_file, video_file_path = get_mode_and_path()
decode_video(use_video_file, video_file_path)
except Exception as e:
print(e)
print("-------------------over------------------------")