You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pydoc生成OpenCV项目API文档仅识别def定义函数忽略cv2函数问题求助

问题原因

pydoc 默认仅会将当前模块下使用 def 声明的函数、class 声明的类,以及模块/类/函数开头的 docstring 纳入生成范围,你遇到的忽略问题由两个原因导致:

  • OpenCV 提供的 cv2.VideoCapture 属于第三方模块导入的对象,pydoc 默认不会把外部导入对象纳入当前模块的文档
  • 你写在 cap = cv2.VideoCapture(...)、cap.read() 后面的三引号内容属于普通字符串字面量,只有放在模块、函数、类的最开头位置的三引号才会被识别为 docstring,其他位置的会被直接忽略。
适配pydoc的解决方法

你可以通过以下修改让相关内容被pydoc收录:

方法1:封装OpenCV操作为自定义函数(最推荐)

将OpenCV相关操作封装为你自己的模块函数,pydoc会直接识别这些函数和对应的docstring,示例修改如下:

import cv2

# 原有initState、finalState函数保持不变
def initState(A, B, C, D, E, P1, P2, P3, P4, P5):
    """if all blocks are there and good recognized, if not shows message.
        :param A: 对象A的识别状态,1为识别成功
        :type A: int
        ... 其余参数可按相同格式逐一补充
        :return: 无返回值,直接在帧图像上绘制提示文本
     """
    if (A == 1 and B == 1 and C == 1 and D == 1 and E == 1 and P1 == 1 and P2 == 1 and P3 == 1 and P4 == 1 and P5 == 1):
        cv2.putText(frame, "initial state top",
                    (100, 100), font, 1, (0, 0, 255))
    else:
        cv2.putText(frame, "Sorry, not recognized",
                    (100, 100), font, 1, (0, 0, 255))

def finalState(A, B, C, D, E, P1, P2, P3, P4, P5):
    """knowing if final state is completed, must be recognized in the moment, if not recognized nothing will be shown.
        :param A: 对象A的识别状态,1为识别成功
        :type A: int
        ... 其余参数可按相同格式逐一补充
        :return: 状态符合要求时返回1,否则无返回值
    """
    if (A == 1 and B == 1 and C == 1 and D == 1 and E == 1 and P1 == 1 and P2 == 1 and P3 == 1 and P4 == 1 and P5 == 1):
        cv2.putText(frame, "final state top", (100, 100), font, 1, (0, 0, 255))
        return 1

def init_video_capture(source: str | int = 'exp11111.mp4') -> cv2.VideoCapture:
    """
    创建视频采集对象,可用于控制视频读取、摄像头调用等操作
    :param source: 视频源,可传入设备索引(整数,调用摄像头时使用)或视频文件路径
    :return: OpenCV的VideoCapture实例对象
    """
    return cv2.VideoCapture(source)

def read_frame(cap: cv2.VideoCapture) -> tuple[bool, cv2.Mat]:
    """
    逐帧读取视频内容
    :param cap: 已初始化的VideoCapture对象
    :return: 第一个返回值为bool类型,表示帧读取是否成功;第二个返回值为读取到的帧图像
    """
    return cap.read()

# 业务逻辑部分调用自定义函数
cap = init_video_capture()
while True:
    ret, frame = read_frame(cap)
    if not ret:
        break

修改后执行 pydoc -w 即可看到init_video_capture、read_frame两个和OpenCV操作相关的函数被纳入文档。

方法2:显式声明导出成员+手动绑定docstring

如果不想修改现有代码结构,可以在模块开头声明__all__变量将需要收录的全局对象加入导出列表,同时手动给对象绑定docstring:

# 模块开头加入
__all__ = ["initState", "finalState", "cap"]

# 原有代码
cap = cv2.VideoCapture('exp11111.mp4')
# 手动绑定文档
cap.__doc__ = """
    创建视频采集对象,可用于控制视频读取、摄像头调用等操作
    :param: 可传入设备索引或视频文件路径
"""

这种方式无需封装函数,执行pydoc -w后cap对象会被纳入当前模块的文档列表。

补充说明

如果后续有更复杂的文档生成需求,比如需要批量关联第三方库的API说明、支持自定义文档格式,可以换用Sphinx等更专业的Python文档生成工具,灵活性远高于pydoc。

内容的提问来源于stack exchange,提问作者Muhammad Aqib Mukhtar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:48:04