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

如何使用OpenCV获取图像frame_width?frame_width未定义报错怎么解决

问题原因

你触发的NameError报错核心原因是:frame_width、frame_height两个变量在使用前没有被定义,既没有在predict_gender函数内部声明赋值,也没有作为入参传入函数,Python解释器找不到对应变量的取值才会抛出错误。这个问题和tkinter库无关,不需要导入tkinter处理。

修复方案

根据你的使用场景二选一即可:

  • 场景1:需要固定所有图片的缩放尺寸
    直接在predict_gender函数开头定义两个变量的取值即可,示例代码如下:
"""Predict the gender of the faces showing in the image"""
def predict_gender(imag):
    # 自定义固定缩放尺寸,可根据需求调整数值
    frame_width = 640
    frame_height = 480
    # Read Input Image
    img = cv2.imread(imag)
    # resize the image, uncomment if you want to resize the image
    img = cv2.resize(img, (frame_width, frame_height))
    # Take a copy of the initial image and resize it
    frame = img.copy()
    print(frame.shape[1])
    # 以下逻辑冗余可删除:已经缩放到frame_width,不可能出现frame.shape[1] > frame_width的情况
    # if frame.shape[1] > frame_width:
    #     frame = image_resize(frame, width=frame_width)
    # predict the faces
    faces = get_faces(frame)
  • 场景2:需要灵活调整不同调用的缩放尺寸
    把两个变量改成函数入参,支持调用时自定义,也可以设置默认值:
"""Predict the gender of the faces showing in the image"""
# 设置默认宽高为640*480,调用时不传参就用默认值
def predict_gender(imag, frame_width=640, frame_height=480):
    # Read Input Image
    img = cv2.imread(imag)
    # resize the image, uncomment if you want to resize the image
    img = cv2.resize(img, (frame_width, frame_height))
    # Take a copy of the initial image and resize it
    frame = img.copy()
    print(frame.shape[1])
    # 冗余逻辑同上,可删除
    # predict the faces
    faces = get_faces(frame)

调用时如果需要修改尺寸,直接传参即可:

if __name__ == '__main__':
    # 自定义宽高为800*600调用
    predict_gender("/Users/$$$/Downloads/test.jpg", frame_width=800, frame_height=600)
    # 用默认尺寸调用
    # predict_gender("/Users/$$$/Downloads/test.jpg")

内容的提问来源于stack exchange,提问作者AIIMOOR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:57:04