Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

refactor: move backend-only utils to mineru/backend/utils/

jinzhenj3a723fbc3649
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 417abe6e..babf7b56 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -17,7 +17,6 @@ from PIL import Image
from tqdm import tqdm
from ...data.data_reader_writer import DataWriter
-from ...utils.boxbase import calculate_overlap_area_2_minbox_area_ratio
from ...utils.config_reader import get_device, get_processing_window_size
from ...utils.enum_class import BlockType as MineruBlockType
from ...utils.enum_class import ImageType, NotExtractType
@@ -41,6 +40,7 @@ from ..pipeline.model_init import (
run_ocr_det_inference,
run_ocr_rec_inference,
)
+from ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio
from ..utils.middle_json_utils import append_pages
from ..utils.runtime_utils import exclude_progress_bar_idle_time
from ..vlm.vlm_analyze import (
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index 0db22d2b..e7b885ad 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -9,12 +9,12 @@ from loguru import logger
from PIL import Image
from ...types import Block, Line, Span
-from ...utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
from ...utils.enum_class import BlockType, ContentType, NotExtractType
from ...utils.guess_suffix_or_lang import guess_language_by_text
-from ...utils.span_block_fix import fix_text_block
-from ...utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
-from ...utils.visual_magic_model_utils import (
+from ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
+from ..utils.span_block_fix import fix_text_block
+from ..utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
+from ..utils.visual_magic_model_utils import (
GENERIC_CHILD_TYPES,
IMAGE_BLOCK_BODY,
VISUAL_MAIN_TYPES,
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 51c139dc..09de2a9f 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -8,7 +8,7 @@ from urllib.parse import urlparse
from ...types import EMPTY_BBOX, Block, Line, Span
from ...utils.enum_class import BlockType, ContentType
-from ...utils.magic_model_utils import tie_up_category_by_index
+from ..utils.magic_model_utils import tie_up_category_by_index
class MagicModel:
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 1fdb4c38..7bca00b2 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -3,13 +3,13 @@ from typing import Any
from ...data.data_reader_writer import DataWriter
from ...types import Block, PageInfo, Span
-from ...utils.char_utils import full_to_half
from ...utils.cut_image import cut_image_and_table
from ...utils.enum_class import BlockType, ContentType
from ...utils.hash_utils import bytes_md5
from ...utils.pdfium_guard import pdfium_guard
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ...version import __version__
+from ..utils.char_utils import full_to_half
from ..utils.html_image_utils import replace_inline_table_images
from ..utils.middle_json_utils import append_pages, apply_post_ocr, build_middle_json
from ..utils.runtime_utils import cross_page_table_merge
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index a3142fb3..90462f65 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -4,18 +4,18 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
from ...types import Block, Line, Span
-from ...utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratio
from ...utils.enum_class import BlockType, ContentType
from ...utils.guess_suffix_or_lang import guess_language_by_text
-from ...utils.span_block_fix import (
+from ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratio
+from ..utils.span_block_fix import (
is_vertical_text_block_by_spans,
line_sort_spans_by_left_to_right,
merge_spans_to_line,
merge_spans_to_vertical_line,
vertical_line_sort_spans_from_top_to_bottom,
)
-from ...utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
-from ...utils.visual_magic_model_utils import (
+from ..utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
+from ..utils.visual_magic_model_utils import (
fallback_inline_caption_fragments,
fallback_leading_table_continuation_captions,
find_best_visual_parent,
diff --git a/mineru/utils/boxbase.py b/mineru/backend/utils/boxbase.py
similarity index 100%
rename from mineru/utils/boxbase.py
rename to mineru/backend/utils/boxbase.py
diff --git a/mineru/utils/char_utils.py b/mineru/backend/utils/char_utils.py
similarity index 95%
rename from mineru/utils/char_utils.py
rename to mineru/backend/utils/char_utils.py
index c048dd8e..66dacf94 100644
--- a/mineru/utils/char_utils.py
+++ b/mineru/backend/utils/char_utils.py
@@ -7,7 +7,7 @@ LINE_END_HYPHEN_CHARS = "-\u00ad\u2010\u2011\u2043"
LINE_END_HYPHEN_RE = re.compile(rf"[A-Za-z]+[{re.escape(LINE_END_HYPHEN_CHARS)}]\s*$")
-def is_hyphen_at_line_end(line: str) -> bool:
+def _is_hyphen_at_line_end(line: str) -> bool:
"""判断文本行是否以英文单词的跨行断词符结尾。
只识别字母后紧跟行末 hyphen 的断词场景,不处理词内连字符或普通破折号。
@@ -15,7 +15,7 @@ def is_hyphen_at_line_end(line: str) -> bool:
return bool(LINE_END_HYPHEN_RE.search(line))
-def full_to_half_exclude_marks(text: str) -> str:
+def _full_to_half_exclude_marks(text: str) -> str:
"""Convert full-width characters to half-width characters using code point manipulation.
Args:
diff --git a/mineru/utils/magic_model_utils.py b/mineru/backend/utils/magic_model_utils.py
similarity index 100%
rename from mineru/utils/magic_model_utils.py
rename to mineru/backend/utils/magic_model_utils.py
diff --git a/mineru/backend/utils/runtime_utils.py b/mineru/backend/utils/runtime_utils.py
index 4f292a17..748bae5e 100644
--- a/mineru/backend/utils/runtime_utils.py
+++ b/mineru/backend/utils/runtime_utils.py
@@ -8,7 +8,7 @@ from typing import Any
from loguru import logger
from ...types import PageInfo
-from ...utils.table_merge import merge_table
+from .table_merge import merge_table
def cross_page_table_merge(pdf_info: list[PageInfo]) -> None:
diff --git a/mineru/utils/span_block_fix.py b/mineru/backend/utils/span_block_fix.py
similarity index 97%
rename from mineru/utils/span_block_fix.py
rename to mineru/backend/utils/span_block_fix.py
index 4e1f9a2d..88235b56 100644
--- a/mineru/utils/span_block_fix.py
+++ b/mineru/backend/utils/span_block_fix.py
@@ -1,8 +1,8 @@
# Copyright (c) Opendatalab. All rights reserved.
from typing import Any
-from .enum_class import ContentType
-from .ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_threshold
+from ...utils.enum_class import ContentType
+from ...utils.ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_threshold
VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2
VERTICAL_SPAN_IN_BLOCK_THRESHOLD = 0.8
diff --git a/mineru/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
similarity index 92%
rename from mineru/utils/span_pre_proc.py
rename to mineru/backend/utils/span_pre_proc.py
index 8e5b1b52..1b2b844c 100644
--- a/mineru/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -11,11 +11,12 @@ import cv2
import numpy as np
from loguru import logger
+from ...utils.enum_class import BlockType, ContentType
+from ...utils.image_utils import calculate_contrast
+from ...utils.pdf_image_tools import get_crop_img
+from ...utils.pdf_text_tool import get_lines_from_chars, get_page_chars
+from ...utils.pdfium_guard import close_pdfium_child, pdfium_guard
from .boxbase import calculate_overlap_area_in_bbox1_area_ratio
-from .enum_class import BlockType, ContentType
-from .pdf_image_tools import get_crop_img
-from .pdf_text_tool import get_lines_from_chars, get_page_chars
-from .pdfium_guard import close_pdfium_child, pdfium_guard
MAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535
@@ -407,28 +408,3 @@ def chars_to_content(span: dict[str, Any]) -> None:
span["content"] = content.strip()
del span["chars"]
-
-
-def calculate_contrast(img: np.ndarray, img_mode: str) -> float:
- """
- 计算给定图像的对比度。
- :param img: 图像,类型为numpy.ndarray
- :Param img_mode = 图像的色彩通道,'rgb' 或 'bgr'
- :return: 图像的对比度值
- """
- if img_mode == "rgb":
- # 将RGB图像转换为灰度图
- gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
- elif img_mode == "bgr":
- # 将BGR图像转换为灰度图
- gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- else:
- raise ValueError("Invalid image mode. Please provide 'rgb' or 'bgr'.")
-
- # 计算均值和标准差
- mean_value = np.mean(gray_img)
- std_dev = np.std(gray_img)
- # 对比度定义为标准差除以平均值(加上小常数避免除零错误)
- contrast = std_dev / (mean_value + 1e-6)
- # logger.debug(f"contrast: {contrast}")
- return round(float(contrast), 2)
diff --git a/mineru/utils/table_continuation.py b/mineru/backend/utils/table_continuation.py
similarity index 100%
rename from mineru/utils/table_continuation.py
rename to mineru/backend/utils/table_continuation.py
diff --git a/mineru/utils/table_merge.py b/mineru/backend/utils/table_merge.py
similarity index 99%
rename from mineru/utils/table_merge.py
rename to mineru/backend/utils/table_merge.py
index 394ca8aa..725ca7c2 100644
--- a/mineru/utils/table_merge.py
+++ b/mineru/backend/utils/table_merge.py
@@ -7,9 +7,9 @@ from typing import Any
from bs4 import BeautifulSoup, Tag
-from ..backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text
+from ...utils.enum_class import BlockType, SplitFlag
+from ..vlm.vlm_middle_json_mkcontent import merge_para_with_text
from .char_utils import full_to_half
-from .enum_class import BlockType, SplitFlag
from .table_continuation import is_table_continuation_text
MAX_HEADER_ROWS = 5
diff --git a/mineru/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.py
similarity index 99%
rename from mineru/utils/visual_magic_model_utils.py
rename to mineru/backend/utils/visual_magic_model_utils.py
index 4ea728df..d051911d 100644
--- a/mineru/utils/visual_magic_model_utils.py
+++ b/mineru/backend/utils/visual_magic_model_utils.py
@@ -4,8 +4,8 @@ from __future__ import annotations
import re
from typing import Any
+from ...utils.enum_class import BlockType
from .boxbase import bbox_center_distance, bbox_distance, calculate_overlap_area_in_bbox1_area_ratio
-from .enum_class import BlockType
from .table_continuation import is_table_continuation_text
IMAGE_BLOCK_BODY = "image_block_body"
diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py
index 0fb648f6..33ac888b 100644
--- a/mineru/backend/vlm/vlm_magic_model.py
+++ b/mineru/backend/vlm/vlm_magic_model.py
@@ -7,10 +7,10 @@ from loguru import logger
from mineru_vl_utils.structs import ContentBlock, ExtractResult
from ...types import Block, Line, Span
-from ...utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
from ...utils.enum_class import BlockType, ContentType
from ...utils.guess_suffix_or_lang import guess_language_by_text
-from ...utils.visual_magic_model_utils import (
+from ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
+from ..utils.visual_magic_model_utils import (
GENERIC_CHILD_TYPES,
IMAGE_BLOCK_BODY,
VISUAL_MAIN_TYPES,
diff --git a/mineru/model/table/rec/unet_table/main.py b/mineru/model/table/rec/unet_table/main.py
index 3bb779b4..c61aa5f8 100644
--- a/mineru/model/table/rec/unet_table/main.py
+++ b/mineru/model/table/rec/unet_table/main.py
@@ -4,28 +4,28 @@ import logging
import os
import time
import traceback
-from dataclasses import dataclass, asdict
+from dataclasses import asdict, dataclass
+from typing import Any, Dict, List, Optional, Union
-from typing import List, Optional, Union, Dict, Any
-import numpy as np
import cv2
-from PIL import Image
-from loguru import logger
+import numpy as np
from bs4 import BeautifulSoup
-
-from mineru.utils.span_pre_proc import calculate_contrast
-from .table_structure_unet import TSRUnet
+from loguru import logger
+from PIL import Image
from mineru.utils.enum_class import ModelPath
+from mineru.utils.image_utils import calculate_contrast
from mineru.utils.models_download_utils import auto_download_and_get_model_root_path
+
from .table_recover import TableRecover
+from .table_structure_unet import TSRUnet
from .utils import InputType, LoadImage, VisTable
from .utils_table_recover import (
+ box_4_2_poly_to_box_4_1,
+ gather_ocr_list_by_row,
match_ocr_cell,
plot_html_table,
- box_4_2_poly_to_box_4_1,
sorted_ocr_boxes,
- gather_ocr_list_by_row,
)
@@ -71,18 +71,14 @@ class WiredTableRecognition:
return WiredTableOutput("", None, None, 0.0)
try:
- table_res, logi_points = self.table_recover(
- rotated_polygons, row_threshold, col_threshold
- )
+ table_res, logi_points = self.table_recover(rotated_polygons, row_threshold, col_threshold)
# 将坐标由逆时针转为顺时针方向,后续处理与无线表格对齐
polygons[:, 1, :], polygons[:, 3, :] = (
polygons[:, 3, :].copy(),
polygons[:, 1, :].copy(),
)
if not need_ocr:
- sorted_polygons, idx_list = sorted_ocr_boxes(
- [box_4_2_poly_to_box_4_1(box) for box in polygons]
- )
+ sorted_polygons, idx_list = sorted_ocr_boxes([box_4_2_poly_to_box_4_1(box) for box in polygons])
return WiredTableOutput(
"",
sorted_polygons,
@@ -98,9 +94,7 @@ class WiredTableRecognition:
t_rec_ocr_list = self.sort_and_gather_ocr_res(t_rec_ocr_list)
cell_box_det_map = {
- t_box_ocr["cell_idx"]: [
- ocr_box_and_text[1] for ocr_box_and_text in t_box_ocr["t_ocr_res"]
- ]
+ t_box_ocr["cell_idx"]: [ocr_box_and_text[1] for ocr_box_and_text in t_box_ocr["t_ocr_res"]]
for t_box_ocr in t_rec_ocr_list
}
pred_html = plot_html_table(logi_points, cell_box_det_map, polygons)
@@ -136,23 +130,16 @@ class WiredTableRecognition:
# row_start,row_end,col_start,col_end
"t_logic_box": logi_points[i].tolist(),
# [[xmin,xmax,ymin,ymax], text]
- "t_ocr_res": [
- [box_4_2_poly_to_box_4_1(ocr_det[0]), ocr_det[1]]
- for ocr_det in ocr_res_list
- ],
+ "t_ocr_res": [[box_4_2_poly_to_box_4_1(ocr_det[0]), ocr_det[1]] for ocr_det in ocr_res_list],
}
res.append(dict_res)
return res
def sort_and_gather_ocr_res(self, res):
for i, dict_res in enumerate(res):
- _, sorted_idx = sorted_ocr_boxes(
- [ocr_det[0] for ocr_det in dict_res["t_ocr_res"]], threhold=0.3
- )
+ _, sorted_idx = sorted_ocr_boxes([ocr_det[0] for ocr_det in dict_res["t_ocr_res"]], threhold=0.3)
dict_res["t_ocr_res"] = [dict_res["t_ocr_res"][i] for i in sorted_idx]
- dict_res["t_ocr_res"] = gather_ocr_list_by_row(
- dict_res["t_ocr_res"], threhold=0.3
- )
+ dict_res["t_ocr_res"] = gather_ocr_list_by_row(dict_res["t_ocr_res"], threhold=0.3)
return res
# def fill_blank_rec(
@@ -187,7 +174,7 @@ class WiredTableRecognition:
logger.warning(f"No OCR engine provided for box {i}: {box}")
continue
# 从img中截取对应的区域
- x1, y1, x2, y2 = int(box[0][0])+1, int(box[0][1])+1, int(box[2][0])-1, int(box[2][1])-1
+ x1, y1, x2, y2 = int(box[0][0]) + 1, int(box[0][1]) + 1, int(box[2][0]) - 1, int(box[2][1]) - 1
if x1 >= x2 or y1 >= y2 or x1 < 0 or y1 < 0:
# logger.warning(f"Invalid box coordinates: {x1, y1, x2, y2}")
continue
@@ -195,10 +182,10 @@ class WiredTableRecognition:
if (x2 - x1) / (y2 - y1) > 20 or (y2 - y1) / (x2 - x1) > 20:
# logger.warning(f"Box {i} has invalid aspect ratio: {x1, y1, x2, y2}")
continue
- img_crop = bgr_img[int(y1):int(y2), int(x1):int(x2)]
+ img_crop = bgr_img[int(y1) : int(y2), int(x1) : int(x2)]
# 计算span的对比度,低于0.20的span不进行ocr
- if calculate_contrast(img_crop, img_mode='bgr') <= 0.17:
+ if calculate_contrast(img_crop, img_mode="bgr") <= 0.17:
cell_box_map[i] = [[box, "", 0.1]]
# logger.debug(f"Box {i} skipped due to low contrast.")
continue
@@ -231,7 +218,7 @@ class WiredTableRecognition:
# 处理ocr结果
ocr_text, ocr_score = ocr_res
# logger.debug(f"OCR result for box {i}: {ocr_text} with score {ocr_score}")
- if ocr_score < 0.6 or ocr_text in ['1','口','■','(204号', '(20', '(2', '(2号', '(20号', '号', '(204']:
+ if ocr_score < 0.6 or ocr_text in ["1", "口", "■", "(204号", "(20", "(2", "(2号", "(20号", "号", "(204"]:
# logger.warning(f"Low confidence OCR result for box {i}: {ocr_text} with score {ocr_score}")
box = sorted_polygons[i]
cell_box_map[i] = [[box, "", 0.1]]
@@ -253,8 +240,8 @@ def count_table_cells_physical(html_code):
# 简单计数td和th标签的数量
html_lower = html_code.lower()
- td_count = html_lower.count('<td')
- th_count = html_lower.count('<th')
+ td_count = html_lower.count("<td")
+ th_count = html_lower.count("<th")
return td_count + th_count
@@ -284,11 +271,7 @@ class UnetTableModel:
try:
wired_table_results = self.wired_table_model(np_img, ocr_result)
- wired_structure_results = (
- self.wired_table_model(np_img, need_ocr=False)
- if return_metadata
- else None
- )
+ wired_structure_results = self.wired_table_model(np_img, need_ocr=False) if return_metadata else None
# viser = VisTable()
# save_html_path = f"outputs/output.html"
@@ -318,11 +301,13 @@ class UnetTableModel:
# logger.debug(f"wireless table ocr text count: {wireless_text_count}, wired table ocr text count: {wired_text_count}")
# 使用HTML解析器计算空单元格数量
- wireless_soup = BeautifulSoup(wireless_html_code, 'html.parser') if wireless_html_code else BeautifulSoup("", 'html.parser')
- wired_soup = BeautifulSoup(wired_html_code, 'html.parser') if wired_html_code else BeautifulSoup("", 'html.parser')
+ wireless_soup = (
+ BeautifulSoup(wireless_html_code, "html.parser") if wireless_html_code else BeautifulSoup("", "html.parser")
+ )
+ wired_soup = BeautifulSoup(wired_html_code, "html.parser") if wired_html_code else BeautifulSoup("", "html.parser")
# 计算空单元格数量(没有文本内容或只有空白字符)
- wireless_blank_count = sum(1 for cell in wireless_soup.find_all(['td', 'th']) if not cell.text.strip())
- wired_blank_count = sum(1 for cell in wired_soup.find_all(['td', 'th']) if not cell.text.strip())
+ wireless_blank_count = sum(1 for cell in wireless_soup.find_all(["td", "th"]) if not cell.text.strip())
+ wired_blank_count = sum(1 for cell in wired_soup.find_all(["td", "th"]) if not cell.text.strip())
# logger.debug(f"wireless table blank cell count: {wireless_blank_count}, wired table blank cell count: {wired_blank_count}")
# 计算非空单元格数量
@@ -332,7 +317,7 @@ class UnetTableModel:
switch_flag = False
if wireless_non_blank_count > wired_non_blank_count:
# 假设非空表格是接近正方表,使用非空单元格数量开平方作为表格规模的估计
- wired_table_scale = round(wired_non_blank_count ** 0.5)
+ wired_table_scale = round(wired_non_blank_count**0.5)
# logger.debug(f"wireless non-blank cell count: {wireless_non_blank_count}, wired non-blank cell count: {wired_non_blank_count}, wired table scale: {wired_table_scale}")
# 如果无线表非空格的数量比有线表多一列或以上,需要切换到无线表
wired_scale_plus_2_cols = wired_non_blank_count + (wired_table_scale * 2)
@@ -346,7 +331,9 @@ class UnetTableModel:
switch_flag
or (0 <= gap_of_len <= 5 and wired_len <= round(wireless_len * 0.75)) # 两者相差不大但有线模型结果较少
or (gap_of_len == 0 and wired_len <= 4) # 单元格数量完全相等且总量小于等于4
- or (wired_text_count <= wireless_text_count * 0.6 and wireless_text_count >=10) # 有线模型填入的文字明显少于无线模型
+ or (
+ wired_text_count <= wireless_text_count * 0.6 and wireless_text_count >= 10
+ ) # 有线模型填入的文字明显少于无线模型
):
# logger.debug("fall back to wireless table model")
html_code = wireless_html_code
diff --git a/mineru/utils/image_utils.py b/mineru/utils/image_utils.py
new file mode 100644
index 00000000..1d34ffd9
--- /dev/null
+++ b/mineru/utils/image_utils.py
@@ -0,0 +1,27 @@
+import cv2
+import numpy as np
+
+
+def calculate_contrast(img: np.ndarray, img_mode: str) -> float:
+ """
+ 计算给定图像的对比度。
+ :param img: 图像,类型为numpy.ndarray
+ :Param img_mode = 图像的色彩通道,'rgb' 或 'bgr'
+ :return: 图像的对比度值
+ """
+ if img_mode == "rgb":
+ # 将RGB图像转换为灰度图
+ gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
+ elif img_mode == "bgr":
+ # 将BGR图像转换为灰度图
+ gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ else:
+ raise ValueError("Invalid image mode. Please provide 'rgb' or 'bgr'.")
+
+ # 计算均值和标准差
+ mean_value = np.mean(gray_img)
+ std_dev = np.std(gray_img)
+ # 对比度定义为标准差除以平均值(加上小常数避免除零错误)
+ contrast = std_dev / (mean_value + 1e-6)
+ # logger.debug(f"contrast: {contrast}")
+ return round(float(contrast), 2)