你所说的在脚本开头定义是指在if __name__ == '__main__':后面加上你给的代码吗
时间: 2023-07-21 11:09:09 浏览: 98
不,我的意思是在脚本的开头定义`main`函数,而不是在`if __name__ == '__main__':`后面添加代码。
以下是修改后的示例代码:
```python
import cv2
from PIL import Image
import numpy as np
import os
from pyzbar import pyzbar
def main(image_folder_path, output_file_name):
img_files = [f for f in os.listdir(image_folder_path) if f.endswith('.png')]
qr_codes_found = []
print("Image files:")
for img_file in img_files:
print(img_file)
for img_file in img_files:
img_path = os.path.join(image_folder_path, img_file)
img = cv2.imread(img_path)
barcodes = pyzbar.decode(img)
for barcode in barcodes:
if barcode.type == 'QRCODE':
qr_data = barcode.data.decode("utf-8")
qr_codes_found.append((img_file, qr_data))
unique_qr_codes = []
for file_name, qr_content in qr_codes_found:
if qr_content not in unique_qr_codes:
unique_qr_codes.append(qr_content)
with open(output_file_name, 'w') as f:
for qr_content in unique_qr_codes:
f.write("{}\n".format(qr_content))
if __name__ == '__main__':
image_folder_path = '/root/Pictures'
output_file_name = '/root/Pictures/qr_codes_found.txt'
main(image_folder_path, output_file_name)
```
这样,您可以将`main`函数放在开头,并在`if __name__ == '__main__':`代码块中调用它。这样做可以确保函数定义在使用之前。请确保将`image_folder_path`和`output_file_name`设置为正确的路径和文件名。
如果您仍然遇到问题,请提供完整的错误消息和调试信息,以便我可以更好地帮助您解决问题。
阅读全文