general_tool.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. 通用处理工具,字符串切分
  3. """
  4. from pathlib import Path
  5. import cv2
  6. def divide_string(s, num_parts):
  7. """
  8. 切割字符串为指定均分的部分
  9. :param s: 待切割的字符串
  10. :param num_parts: 切割份数
  11. :return: 切分结果
  12. """
  13. n = len(s)
  14. part_size = n // num_parts
  15. sizes = [part_size + 1 if i < n % num_parts else part_size for i in range(num_parts)]
  16. parts = []
  17. start = 0
  18. for size in sizes:
  19. parts.append(s[start:start + size])
  20. start += size
  21. return parts
  22. def find_relative_directories(root_dir, target_dir):
  23. """
  24. 查找指定目录下的目标目录相对路径
  25. :param root_dir: 根目录
  26. :param target_dir: 目标目录
  27. :return: 根目录到目标目录的相对路径
  28. """
  29. root_path = Path(root_dir)
  30. yolox_paths = []
  31. # 递归查找指定目录
  32. for path in root_path.rglob(target_dir):
  33. if path.is_dir():
  34. # 计算相对路径
  35. relative_path = path.relative_to(root_path)
  36. yolox_paths.append(relative_path)
  37. return yolox_paths
  38. def detect_and_decode_qr_code(img_path):
  39. """
  40. 从图片中提取二维码中的内容
  41. :param img_path: 待提取二维码内容的图片地址
  42. :return: 提取信息
  43. """
  44. image = cv2.imread(img_path)
  45. # Initialize the QRCode detector
  46. qr_code_detector = cv2.QRCodeDetector()
  47. # Detect and decode the QR code
  48. decoded_text, points, _ = qr_code_detector.detectAndDecode(image)
  49. if points is not None:
  50. # Convert to integer type
  51. points = points[0].astype(int)
  52. # Draw the bounding box on the image (optional)
  53. for i in range(len(points)):
  54. cv2.line(image, tuple(points[i]), tuple(points[(i + 1) % len(points)]), (255, 0, 0), 2)
  55. return decoded_text, points
  56. else:
  57. return None, None
  58. def get_file_extension(filename):
  59. """
  60. 获取文件扩展名
  61. :param filename: 文件名
  62. :return: 扩展名
  63. """
  64. return filename.rsplit('.', 1)[1].lower()