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

Python手写数字识别项目报错:'int' object is not iterable 求助

手写数字识别系统代码错误排查

问题场景

基于Python机器学习的手写数字识别系统,用PyGame搭建手写输入界面,尝试在绘制的数字周围生成动态矩形时,执行以下代码行报错:

rect_min_Y, rect_max_Y = max(number_ycord[0]-BOUNDRYINC, ), min(number_ycord[-1]+BOUNDRYINC, WINDOWSIZEX)

错误信息:TypeError: 'int' object is not iterable

错误原因

  1. max函数参数缺失:max(number_ycord[0]-BOUNDRYINC, )中第二个参数为空,导致max只接收了一个int类型参数。max函数需要传入多个参数或可迭代对象,单个int无法被迭代,触发类型错误。
  2. Y轴边界取值错误:Y轴的最大边界应该用窗口高度WINDOWSIZEY,但代码中误用了窗口宽度WINDOWSIZEX,会导致矩形超出Y轴范围。

额外代码问题修正

除上述报错点,代码中还有几处问题需要修复:

  • img_arr切片语法错误:原代码[rect_min_x:rect_max_x, rect_min_Y, rect_max_Y]应为[rect_min_x:rect_max_x, rect_min_Y:rect_max_Y],才能正确截取矩形区域。
  • FONT未定义:需要初始化PyGame的字体模块并设置字体。
  • 文本渲染变量错误:testing.get_rect()应为textSurface.get_rect(),textRecObj拼写错误(修正为textRectObj)。
  • 预测逻辑触发条件错误:if event.type==PREDICT是无效判断,PREDICT是布尔变量,应改为if PREDICT:。
  • KEYDOWN事件处理位置错误:原代码写在MOUSEBUTTONUP分支内,应放到顶层事件循环中。
  • 增加空列表判断:避免未绘制内容时触发MOUSEBUTTONUP导致的索引错误。

修正后的完整代码

import pygame, sys
from pygame.locals import *
import numpy as np
from keras.models import load_model
import cv2

WINDOWSIZEX = 640
WINDOWSIZEY = 480

BOUNDRYINC = 5
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)

IMAGESAVE = False

MODEL = load_model("bestmodel.h5")

LABELS = {0:"Zero", 1:"One",
        2:"Two", 3:"Three",
        4:"Four", 5:"Five",
        6:"Six", 7:"Seven",
        8:"Eight", 9:"Nine"}

#Initialize pygame
pygame.init()
# 初始化字体
pygame.font.init()
FONT = pygame.font.SysFont('arial', 30)

DISPLAYSURF = pygame.display.set_mode((WINDOWSIZEX, WINDOWSIZEY))
pygame.display.set_caption("Digit Board")

number_xcord = []
number_ycord =[]

iswriting = False

imag_cnt = 1
PREDICT = True

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == MOUSEMOTION and iswriting:
            xcord, ycord = event.pos
            pygame.draw.circle(DISPLAYSURF, WHITE, (xcord, ycord), 4, 0)
            number_xcord.append(xcord)
            number_ycord.append(ycord)

        if event.type == MOUSEBUTTONDOWN:
            iswriting = True

        if event.type == MOUSEBUTTONUP:
            iswriting = False
            if not number_xcord or not number_ycord:
                continue  # 避免空列表报错
            number_xcord = sorted(number_xcord)
            number_ycord = sorted(number_ycord)

            rect_min_x, rect_max_x = max(number_xcord[0]-BOUNDRYINC, 0), min(WINDOWSIZEX, number_xcord[-1]+BOUNDRYINC)
            rect_min_Y, rect_max_Y = max(number_ycord[0]-BOUNDRYINC, 0), min(number_ycord[-1]+BOUNDRYINC, WINDOWSIZEY)

            number_xcord = []
            number_ycord = []

            # 修正切片语法
            img_arr = np.array(pygame.PixelArray(DISPLAYSURF))[rect_min_x:rect_max_x, rect_min_Y:rect_max_Y].T.astype(np.float32)

            if PREDICT:
                # 处理图像为模型输入格式
                image = cv2.resize(img_arr, (28,28))
                image = np.pad(image, (10,10), 'constant', constant_values = 0)
                image = cv2.resize(image, (28,28))/255

                label = str(LABELS[np.argmax(MODEL.predict(image.reshape(1,28,28), verbose=0))])

                textSurface = FONT.render(label, True, RED, WHITE)
                textRectObj = textSurface.get_rect()
                textRectObj.left , textRectObj.bottom = rect_min_x, rect_max_Y

                DISPLAYSURF.blit(textSurface, textRectObj)
        
        if event.type == KEYDOWN:
            if event.unicode == "n":
                DISPLAYSURF.fill(BLACK)
    
    pygame.display.update()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:10:38