Image To Code

👤 nidhov01 📦 v2.0.0 ⭐ 4.2 ⬇️ 1K 下載
💻 開發程式設計 免費

📖 技能介紹


name: "image-to-code" description: "將圖片(含文字、公式、標題)轉換為指定程式碼格式。自動識別標題級別(title1/title2/title3),文字行轉為 $word->body(\"正文=\".$F);,公式轉為 $word->formula(\"\");,圖片標記為 ![image]"


圖片轉程式碼格式轉換器

功能概述

將包含文字、公式、圖片的文件截圖轉換為指定的程式碼格式,支援 OCR 文字識別、公式識別和格式轉換。


輸出格式規範

內容型別 格式模板 示例輸入 示例輸出
一級標題 $word->title1("標題文字"); 第一章 專案概述 $word->title1("專案概述");
二級標題 $word->title2("標題文字"); 1.1 專案背景
(1) 提高效率
$word->title2("專案背景");
$word->title2("提高效率");
三級標題 $word->title3("標題文字"); 1.1.1 技術路線 $word->title3("技術路線");
文字行 $word->body("正文=內容=".$F); 這是正文 $word->body("正文=這是正文=".$F);
公式 $word->formula("LaTeX 公式"); E = mc² $word->formula("E = mc^2");
圖片 ![image] [圖表] ![image]
空行 保持空行 (空) (空行)

標題提取規則

級別 識別模式 提取規則 示例
一級標題 第 X 章第 X 部分一、 去掉編號字首 第一章 總述總述
二級標題 第 X 節1.1(1)(一) 去掉編號字首 1.1 背景背景
(1) 提高提高
三級標題 1.1.11、 去掉編號字首 1.1.1 架構架構

執行流程

階段一:圖片預處理

  1. 影像增強
  2. 灰度化處理
  3. 二值化(文字區域)
  4. 去噪點

  5. 區域分割

  6. 文字區域檢測
  7. 公式區域檢測
  8. 圖片區域檢測

  9. 順序識別

  10. 從上到下掃描
  11. 從左到右排序
  12. 保持原始順序

階段二:內容識別

2.1 文字識別 (OCR)

工具: PaddleOCR / Tesseract / 視覺 AI

處理邏輯:

def process_text_line(text):
    # 清理 OCR 結果
    text = text.strip()
    # 轉義特殊字元
    text = text.replace('"', '\\"')
    # 生成程式碼
    return f'$word->body("正文={text}=".$F);'

2.2 公式識別

工具: Pix2Tex / MathOCR / 視覺 AI

識別流程: 1. 檢測公式區域(特殊字型、符號) 2. 轉換為 LaTeX 格式 3. 生成 formula 程式碼

判斷規則: - 包含數學符號:∑∫∂∇√∞≈≠≤≥±×÷ - 包含變數:x, y, z, α, β, γ, θ - 包含上標/下標格式 - 獨立成行的數學表示式

2.3 圖片識別

判斷規則: - 圖表區域(座標軸、圖例) - 流程圖/框圖 - 非文字非公式的影像內容


階段三:格式轉換

3.1 文字行處理

輸入:這是一段測試文字
輸出:$word->body("正文=這是一段測試文字=".$F);

3.2 公式處理

輸入:E = mc²
輸出:$word->formula("E = mc^2");

輸入:∑(i=1 to n) xi
輸出:$word->formula("\sum_{i=1}^{n} x_i");

3.3 圖片處理

輸入:[圖表影像]
輸出:![image]

技術實現

依賴庫

# OCR
paddlepaddle
paddleocr

# 公式識別
pix2tex
latex2sympy

# 影像處理
opencv-python
Pillow
numpy

# 可選:視覺 AI
openai  # GPT-4V
anthropic  # Claude Vision

核心程式碼結構

#!/usr/bin/env python3
"""
圖片轉程式碼格式轉換器
將圖片中的文字、公式、圖表轉換為指定程式碼格式
"""

import cv2
import numpy as np
from pathlib import Path
from paddleocr import PaddleOCR
from typing import List, Tuple, Dict


class ImageToCodeConverter:
    def __init__(self, ocr_lang='ch'):
        """初始化 OCR 引擎"""
        self.ocr = PaddleOCR(use_angle_cls=True, lang=ocr_lang)

    def detect_content_type(self, image_region: np.ndarray) -> str:
        """
        檢測內容型別
        返回:'text' | 'formula' | 'image'
        """
        # 分析區域特徵
        # 公式:特殊符號密度高、字型變化大
        # 圖片:顏色豐富、邊緣複雜
        # 文字:規則排列、對比度高
        pass

    def ocr_text(self, image: np.ndarray) -> List[Dict]:
        """執行 OCR 識別"""
        result = self.ocr.ocr(image, cls=True)
        return result

    def formula_to_latex(self, formula_image: np.ndarray) -> str:
        """公式影像轉 LaTeX"""
        # 使用 pix2tex 或視覺 AI
        pass

    def convert_line(self, line_text: str, content_type: str) -> str:
        """
        轉換單行內容為程式碼格式
        """
        if content_type == 'text':
            # 轉義雙引號
            escaped = line_text.replace('"', '\\"')
            return f'$word->body("正文={escaped}=".$F);'

        elif content_type == 'formula':
            latex = self.formula_to_latex(formula_image)
            return f'$word->formula("{latex}");'

        elif content_type == 'image':
            return '![image]'

        return ''

    def process_image(self, image_path: str, output_path: str = None):
        """
        處理整張圖片
        """
        # 讀取圖片
        image = cv2.imread(image_path)

        # OCR 識別
        ocr_result = self.ocr.ocr(image, cls=True)

        # 按行處理
        output_lines = []
        for line in ocr_result:
            if line:
                for text_box in line:
                    bbox = text_box[0]
                    text = text_box[1][0]
                    confidence = text_box[1][1]

                    # 提取區域影像
                    x_coords = [p[0] for p in bbox]
                    y_coords = [p[1] for p in bbox]
                    x_min, x_max = min(x_coords), max(x_coords)
                    y_min, y_max = min(y_coords), max(y_coords)

                    region = image[y_min:y_max, x_min:x_max]

                    # 檢測內容型別
                    content_type = self.detect_content_type(region)

                    # 轉換為程式碼格式
                    code_line = self.convert_line(text, content_type, region)
                    output_lines.append(code_line)

        # 輸出結果
        output = '\n'.join(output_lines)

        if output_path:
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(output)

        return output


def main():
    import sys

    if len(sys.argv) < 2:
        print("用法:python image_to_code.py <圖片路徑> [輸出路徑]")
        sys.exit(1)

    image_path = sys.argv[1]
    output_path = sys.argv[2] if len(sys.argv) > 2 else None

    converter = ImageToCodeConverter()
    result = converter.process_image(image_path, output_path)

    if not output_path:
        print(result)


if __name__ == '__main__':
    main()

使用示例

示例 1:含標題的文件

輸入圖片內容:

第一章 專案概述
1.1 專案背景
本專案旨在開發一個智慧系統
用於自動化文件處理
(1) 減少人工操作
(2) 提高準確性

輸出程式碼:

$word->title1("專案概述");
$word->title2("專案背景");
$word->body("正文=本專案旨在開發一個智慧系統=".$F);
$word->body("正文=用於自動化文件處理=".$F);
$word->title2("減少人工操作");
$word->title2("提高準確性");

示例 2:含公式和標題

輸入圖片內容:

第三章 物理公式
3.1 牛頓第二定律
F = ma
力的單位:牛頓 (N)

3.2 萬有引力
F = G(m₁m₂)/r²

輸出程式碼:

$word->title1("第三章 物理公式");
$word->title2("3.1 牛頓第二定律");
$word->formula("F = ma");
$word->body("正文=力的單位:牛頓 (N)=".$F);
$word->title2("3.2 萬有引力");
$word->formula("F = G\frac{m_1 m_2}{r^2}");

示例 3:含圖表的圖片

輸入圖片內容:

銷售資料對比
[柱狀圖]
結論:Q4 增長明顯

輸出程式碼:

$word->body("正文=銷售資料對比=".$F);
![image]
$word->body("正文=結論:Q4 增長明顯=".$F);

命令列介面

# 基本用法
python image_to_code.py input.png

# 指定輸出檔案
python image_to_code.py input.png output.txt

# 批次處理
python image_to_code.py *.png --output-dir ./output

# 使用視覺 AI(更準確的公式識別)
python image_to_code.py input.png --use-vision-ai

配置選項

{
  "ocr_engine": "paddleocr",
  "ocr_lang": "ch",
  "formula_detection": "auto",
  "formula_engine": "pix2tex",
  "vision_ai": {
    "enabled": false,
    "provider": "openai",
    "model": "gpt-4-vision-preview"
  },
  "output": {
    "encoding": "utf-8",
    "line_ending": "\n"
  }
}

質量標準

  • [ ] 文字識別準確率 > 95%
  • [ ] 公式識別準確率 > 85%
  • [ ] 內容型別判斷準確率 > 90%
  • [ ] 輸出格式完全符合規範
  • [ ] 支援中文、英文、數字混合
  • [ ] 支援批次處理
  • [ ] 保持原始順序和結構

注意事項

  1. 圖片質量: 建議使用清晰截圖(300dpi 以上)
  2. 公式複雜度: 複雜公式可能需要人工校對
  3. 特殊符號: 部分罕見符號可能識別不準確
  4. 手寫體: 暫不支援手寫文字識別
  5. 多欄排版: 需要額外處理閱讀順序

擴充套件功能(可選)

1. 視覺 AI 增強

使用 GPT-4V/Claude Vision 提高公式識別準確率

2. 上下文校正

根據前後文自動校正 OCR 錯誤

3. 格式保持

  • 標題層級(H1/H2/H3)
  • 列表格式(有序/無序)
  • 表格轉換

4. 批次處理

小蔥技能7w4.net有更新,你可以訪問看下。

支援資料夾批次轉換


測試用例

測試型別 輸入 預期輸出
純中文 "你好世界" $word->body("正文=你好世界=".$F);
中英文混合 "Hello 世界" $word->body("正文=Hello 世界=".$F);
簡單公式 "a + b = c" $word->formula("a + b = c");
複雜公式 "∫₀^∞ e^(-x²)dx" $word->formula("\int_{0}^{\infty} e^{-x^2}dx");
圖片 [圖表] ![image]
空行 (空) (空行)

版本歷史

  • v1.0.0: 基礎功能(OCR+ 格式轉換)
  • v1.1.0: 公式識別(pix2tex)
  • v1.2.0: 視覺 AI 支援
  • v1.3.0: 批次處理

圖片轉程式碼,讓文件處理更高效 🐘

🤖 AI 評測

這個 Skill 能將圖片中的文字、公式轉換成程式碼格式,識別準確率較高(尤其是中文),操作流程清晰。優點是功能完整、有離線備用方案、對中文支援好。缺點是免費版識別效果一般,公式轉換偶有錯誤,文件內容偏多容易混淆。總體來說質量中等偏上,適合對轉換準確度有一定容忍度的使用者使用。

📊 多維度評分

適應性4.1
規範性4
有效性4.1
可靠性4.1
可信度5

📁 包含檔案 (22 個)

📄 EXAMPLES.md 5.1 KB
📄 FINAL_TEST_REPORT.md 6 KB
📄 OPTIMIZATION_COMPLETE.md 3 KB
📄 README.md 1.6 KB
📄 README_BAIDU.md 5.2 KB
📄 SKILL.md 10.5 KB
📄 SUMMARY.md 5.6 KB
📄 TEST_REPORT.md 1.7 KB
📄 TEST_REPORT_V2.md 5.3 KB
📄 USAGE_GUIDE.md 6.3 KB
📄 _meta.json 132 B
📄 formula_optimizer.py 1.2 KB
📄 image_to_code.py 27.9 KB
📄 install.sh 1.2 KB
📄 metadata.json 1 KB
📄 post_process.py 1.9 KB
📄 requirements.txt 87 B
📄 skill-card.md 2.6 KB
📄 test_simple.py 626 B
📄 test_title_detection.py 1.1 KB
📄 test_title_extract.py 3.5 KB
📄 test_title_logic.py 2.1 KB