当前位置:首页>python>python 图片转表格

python 图片转表格

  • 2026-10-11 05:53:30
python 图片转表格
我们有时候遇到别人将表格的内容以图片的形式发送过来,这个时候用微信识别出来的是文字,但格式被破坏了。这个时候我们用python的paddleOCR来识别,然后再生成表格。就能更好地处理表格数据。这个适合电脑上有python的用户,在本地处理数据更加安全。如果数据不涉及机密推荐一个网址https://web.baimiaoapp.com/image-to-excel直接上传就可以处理,相当方便。
from paddleocr import PaddleOCRimport pandas as pdimport osimport cv2import numpy as npfrom openpyxl import Workbookfrom openpyxl.styles import Font, Alignment, Border, Side, PatternFillfrom openpyxl.utils import get_column_letterimport reimport warningswarnings.filterwarnings('ignore')# ===================== 配置参数 =====================class Config:    # 文件路径    MODEL_DIR = r"C:\Users\admin\.paddleocr"    IMG_PATH = r"C:\Users\admin\Desktop\gongzi.png"    OUTPUT_EXCEL = r"C:\Users\admin\Desktop\工资表识别结果.xlsx"    # OCR参数    LINE_THRESHOLD = 15  # 同行判定阈值(像素)    COLUMN_GAP = 20      # 列分割阈值    # 图片预处理参数    ENHANCE_CONTRAST = True      # 是否增强对比度    DESKEW = True                # 是否校正倾斜    REMOVE_NOISE = True          # 是否去噪    BINARIZE = True              # 是否二值化    # 表格识别参数    MIN_CELL_AREA = 100          # 最小单元格面积    MERGE_HEADER = True          # 是否合并表头    AUTO_CORRECT = True          # 是否自动纠错    USE_STRUCTURE_ANALYSIS = True # 是否使用表格结构分析cfg = Config()# ===================== 图片预处理模块 =====================class ImagePreprocessor:    @staticmethod    def enhance_contrast(img):        """增强对比度"""        lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)        l, a, b = cv2.split(lab)        clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))        l = clahe.apply(l)        enhanced = cv2.merge([l, a, b])        return cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR)    @staticmethod    def remove_noise(img):        """去除噪点"""        return cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)    @staticmethod    def correct_skew(img):        """校正图片倾斜"""        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)        edges = cv2.Canny(gray, 50, 150, apertureSize=3)        lines = cv2.HoughLines(edges, 1, np.pi/180, 200)        if lines is not None:            angles = []            for line in lines:                rho, theta = line[0]                angle = theta * 180 / np.pi - 90                if -45 < angle < 45:                    angles.append(angle)            if angles:                median_angle = np.median(angles)                if abs(median_angle) > 0.5:                    h, w = img.shape[:2]                    center = (w // 2, h // 2)                    matrix = cv2.getRotationMatrix2D(center, median_angle, 1.0)                    img = cv2.warpAffine(img, matrix, (w, h),                                         borderMode=cv2.BORDER_REPLICATE)        return img    @staticmethod    def binarize_image(img):        """二值化处理"""        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)        # 自适应阈值        binary = cv2.adaptiveThreshold(gray, 255,                                       cv2.ADAPTIVE_THRESH_GAUSSIAN_C,                                      cv2.THRESH_BINARY, 11, 2)        return binary    @classmethod    def preprocess(cls, img_path):        """完整的预处理流程"""        img = cv2.imread(img_path)        if img is None:            raise ValueError(f"无法读取图片:{img_path}")        print("原始图片尺寸:", img.shape)        if cfg.REMOVE_NOISE:            img = cls.remove_noise(img)            print("✓ 去噪完成")        if cfg.DESKEW:            img = cls.correct_skew(img)            print("✓ 倾斜校正完成")        if cfg.ENHANCE_CONTRAST:            img = cls.enhance_contrast(img)            print("✓ 对比度增强完成")        # 保留原始彩色图像用于结构分析        color_img = img.copy()        if cfg.BINARIZE:            binary_img = cls.binarize_image(img)            print("✓ 二值化完成")        else:            binary_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)        return color_img, binary_img# ===================== 表格结构分析模块 =====================class TableStructureAnalyzer:    @staticmethod    def detect_lines(binary_img):        """检测表格线"""        # 检测横线        horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1))        horizontal_lines = cv2.morphologyEx(binary_img, cv2.MORPH_OPEN,                                            horizontal_kernel, iterations=2)        # 检测竖线        vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 40))        vertical_lines = cv2.morphologyEx(binary_img, cv2.MORPH_OPEN,                                          vertical_kernel, iterations=2)        # 合并横竖线        table_structure = cv2.add(horizontal_lines, vertical_lines)        return horizontal_lines, vertical_lines, table_structure    @staticmethod    def find_cells(table_structure):        """查找单元格"""        contours, _ = cv2.findContours(table_structure,                                       cv2.RETR_TREE,                                       cv2.CHAIN_APPROX_SIMPLE)        cells = []        for contour in contours:            x, y, w, h = cv2.boundingRect(contour)            area = w * h            if area > cfg.MIN_CELL_AREA:                cells.append({                    'x': x, 'y': y,                     'width': w, 'height': h,                    'center_x': x + w//2,                    'center_y': y + h//2                })        return cells# ===================== OCR识别模块 =====================class OCRProcessor:    def __init__(self):        self.ocr = PaddleOCR(            use_angle_cls=True,            lang="ch",            show_log=False,            use_gpu=False,            det_db_thresh=0.3,            det_db_box_thresh=0.3,            det_db_unclip_ratio=1.8,            det_model_dir=os.path.join(cfg.MODEL_DIR, "ch_PP-OCRv4_det_infer"),            rec_model_dir=os.path.join(cfg.MODEL_DIR, "ch_PP-OCRv4_rec_infer"),            cls_model_dir=os.path.join(cfg.MODEL_DIR, "ch_ppocr_mobile_v2.0_cls_infer")        )    def recognize(self, img):        """执行OCR识别"""        # 对于二值化图像,转换为3通道        if len(img.shape) == 2:            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)        result = self.ocr.ocr(img, cls=True)        return self._parse_result(result)    def _parse_result(self, ocr_result):        """解析OCR结果"""        text_info = []        if ocr_result and ocr_result[0]:            for item in ocr_result[0]:                box = item[0]                text = item[1][0]                confidence = item[1][1]                # 计算文本框的中心和范围                x_coords = [point[0] for point in box]                y_coords = [point[1] for point in box]                text_info.append({                    'text': text,                    'confidence': confidence,                    'x_min': min(x_coords),                    'x_max': max(x_coords),                    'y_min': min(y_coords),                    'y_max': max(y_coords),                    'center_x': sum(x_coords) / 4,                    'center_y': sum(y_coords) / 4,                    'box': box                })        return text_info# ===================== 表格重建模块 =====================class TableReconstructor:    @staticmethod    def group_by_rows(text_info, threshold=None):        """将文本按行分组"""        if threshold is None:            threshold = cfg.LINE_THRESHOLD        if not text_info:            return []        # 按y坐标排序        sorted_texts = sorted(text_info, key=lambda x: x['center_y'])        rows = []        current_row = [sorted_texts[0]]        for text in sorted_texts[1:]:            if abs(text['center_y'] - current_row[-1]['center_y']) < threshold:                current_row.append(text)            else:                # 按x坐标排序当前行                current_row.sort(key=lambda x: x['center_x'])                rows.append(current_row)                current_row = [text]        # 添加最后一行        current_row.sort(key=lambda x: x['center_x'])        rows.append(current_row)        return rows    @staticmethod    def align_columns(rows):        """列对齐处理"""        if not rows:            return [], []        # 收集所有文本的x坐标        all_x_positions = []        for row in rows:            for cell in row:                all_x_positions.append(cell['center_x'])        # 使用聚类方法找到列边界        all_x_positions.sort()        column_boundaries = TableReconstructor._cluster_positions(all_x_positions)        # 构建表格矩阵        table_matrix = []        for row in rows:            row_data = [''] * len(column_boundaries)            for cell in row:                col_idx = TableReconstructor._find_column(cell['center_x'],                                                          column_boundaries)                if col_idx is not None and col_idx < len(row_data):                    if row_data[col_idx]:                        row_data[col_idx] += ' ' + cell['text']                    else:                        row_data[col_idx] = cell['text']            table_matrix.append(row_data)        return table_matrix, column_boundaries    @staticmethod    def _cluster_positions(positions, gap_threshold=None):        """聚类x坐标以确定列"""        if gap_threshold is None:            gap_threshold = cfg.COLUMN_GAP        if not positions:            return []        clusters = [[positions[0]]]        for pos in positions[1:]:            if pos - clusters[-1][-1] < gap_threshold:                clusters[-1].append(pos)            else:                clusters.append([pos])        # 返回每个聚类的中心        return [np.mean(cluster) for cluster in clusters]    @staticmethod    def _find_column(x_pos, boundaries):        """找到x坐标对应的列索引"""        min_dist = float('inf')        col_idx = 0        for i, boundary in enumerate(boundaries):            dist = abs(x_pos - boundary)            if dist < min_dist:                min_dist = dist                col_idx = i        # 设置合理的距离阈值        if min_dist > 100:  # 如果距离太远,可能是新列            return None        return col_idx    @staticmethod    def merge_headers(rows, max_header_rows=3):        """智能合并表头"""        if len(rows) <= max_header_rows:            return rows        # 检测表头行(通常前几行包含特殊格式)        header_rows = rows[:max_header_rows]        data_rows = rows[max_header_rows:]        # 合并表头        merged_header = []        num_columns = max(len(row) for row in header_rows)        for col in range(num_columns):            header_texts = []            for row in header_rows:                if col < len(row) and row[col].strip():                    header_texts.append(row[col].strip())            merged_header.append('_'.join(header_texts) if header_texts else f'列{col+1}')        return [merged_header] + data_rows    @staticmethod    def clean_table(table_matrix):        """清理表格数据"""        cleaned = []        for row in table_matrix:            # 过滤空行            if any(cell.strip() for cell in row):                # 清理每个单元格                cleaned_row = [TableReconstructor._clean_text(cell) for cell in row]                cleaned.append(cleaned_row)        return cleaned    @staticmethod    def _clean_text(text):        """清理文本"""        # 去除多余空格        text = re.sub(r'\s+', ' ', text.strip())        # 修正常见OCR错误        text = text.replace('O', '0').replace('l', '1').replace('I', '1')        text = text.replace(':', ':').replace(',', ',')        return text# ===================== Excel导出模块 =====================class ExcelExporter:    @staticmethod    def export_to_excel(table_data, output_path, headers=None):        """导出为格式化的Excel文件"""        wb = Workbook()        ws = wb.active        # 设置样式        header_font = Font(name='微软雅黑', size=11, bold=True, color='FFFFFF')        header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')        header_alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)        cell_font = Font(name='微软雅黑', size=10)        cell_alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)        thin_border = Border(            left=Side(style='thin'),            right=Side(style='thin'),            top=Side(style='thin'),            bottom=Side(style='thin')        )        # 写入表头        if headers:            for col, header in enumerate(headers, 1):                cell = ws.cell(row=1, column=col, value=header)                cell.font = header_font                cell.fill = header_fill                cell.alignment = header_alignment                cell.border = thin_border            start_row = 2        else:            start_row = 1        # 写入数据        for row_idx, row_data in enumerate(table_data, start_row):            for col_idx, value in enumerate(row_data, 1):                cell = ws.cell(row=row_idx, column=col_idx, value=value)                cell.font = cell_font                cell.alignment = cell_alignment                cell.border = thin_border                # 数值列右对齐                if value and value.replace('.', '').replace('-', '').isdigit():                    cell.alignment = Alignment(horizontal='right', vertical='center')        # 自动调整列宽        for col in ws.columns:            max_length = 0            column = col[0].column_letter            for cell in col:                try:                    if len(str(cell.value)) > max_length:                        max_length = len(str(cell.value))                except:                    pass            adjusted_width = min(max_length + 2, 30)            ws.column_dimensions[column].width = adjusted_width        # 冻结首行        if headers:            ws.freeze_panes = 'A2'        wb.save(output_path)        print(f"✓ Excel文件已保存至: {output_path}")# ===================== 主程序 =====================def main():    print("=" * 60)    print("图片表格识别系统 v1.0")    print("=" * 60)    # 1. 图片预处理    print("\n【步骤1】图片预处理...")    preprocessor = ImagePreprocessor()    color_img, binary_img = preprocessor.preprocess(cfg.IMG_PATH)    # 2. 表格结构分析    print("\n【步骤2】表格结构分析...")    if cfg.USE_STRUCTURE_ANALYSIS:        analyzer = TableStructureAnalyzer()        h_lines, v_lines, table_structure = analyzer.detect_lines(binary_img)        cells = analyzer.find_cells(table_structure)        print(f"✓ 检测到 {len(cells)} 个单元格")        # 根据检测到的单元格动态调整阈值        if cells:            avg_cell_height = np.mean([c['height'] for c in cells])            cfg.LINE_THRESHOLD = max(int(avg_cell_height * 0.5), 10)            print(f"✓ 自动调整行阈值: {cfg.LINE_THRESHOLD}")    # 3. OCR识别    print("\n【步骤3】OCR文字识别...")    ocr_processor = OCRProcessor()    # 对原始彩色图像和预处理图像分别识别,取最佳结果    text_info_color = ocr_processor.recognize(color_img)    text_info_binary = ocr_processor.recognize(binary_img)    # 合并识别结果,优先使用高置信度结果    text_info = text_info_color if len(text_info_color) > len(text_info_binary) else text_info_binary    print(f"✓ 识别到 {len(text_info)} 个文本区域")    if len(text_info) < 10:        print("⚠ OCR识别文本过少,尝试调整参数...")        # 使用更激进的预处理        enhanced_img = cv2.convertScaleAbs(color_img, alpha=1.5, beta=30)        text_info = ocr_processor.recognize(enhanced_img)        print(f"✓ 增强后识别到 {len(text_info)} 个文本区域")    # 4. 表格重建    print("\n【步骤4】表格重建...")    reconstructor = TableReconstructor()    # 按行分组    rows = reconstructor.group_by_rows(text_info)    print(f"✓ 分组为 {len(rows)} 行")    # 列对齐    table_matrix, column_boundaries = reconstructor.align_columns(rows)    print(f"✓ 识别到 {len(column_boundaries)} 列")    # 清理数据    table_matrix = reconstructor.clean_table(table_matrix)    # 合并表头    if cfg.MERGE_HEADER and len(table_matrix) > 1:        table_matrix = reconstructor.merge_headers(table_matrix)        print("✓ 表头合并完成")    # 5. 数据处理和导出    print("\n【步骤5】数据导出...")    if len(table_matrix) > 1:        headers = table_matrix[0]        data = table_matrix[1:]        print(f"✓ 表头: {len(headers)} 列")        print(f"✓ 数据行: {len(data)} 行")    else:        headers = None        data = table_matrix        print("⚠ 未检测到明确表头,使用自动列名")    # 预览前几行数据    print("\n【数据预览】")    preview_rows = min(5, len(data))    if headers:        print("表头:", headers[:10], "..." if len(headers) > 10 else "")    for i in range(preview_rows):        print(f"第{i+1}行:", data[i][:10], "..." if len(data[i]) > 10 else "")    # 导出Excel    ExcelExporter.export_to_excel(data, cfg.OUTPUT_EXCEL, headers)    print("\n" + "=" * 60)    print("识别完成!")    print(f"输出文件: {cfg.OUTPUT_EXCEL}")    print("=" * 60)if __name__ == "__main__":    try:        main()    except Exception as e:        print(f"\n❌ 程序运行出错: {str(e)}")        import traceback        traceback.print_exc()

最新文章

随机文章