Python报错UnboundLocalError: local variable ‘val‘ referenced before assignment

看下面的代码:

def get_frame(self):
    KSIZE = 11
    ALPHA = 2
    kernel = cv2.getGaussianKernel(KSIZE, 0)
    kernel = -ALPHA * kernel @ kernel.T
    kernel[KSIZE // 2, KSIZE // 2] += 1 + ALPHA

    filtered = cv2.filter2D(self.img, -1, kernel)
    gray = cv2.cvtColor(filtered, cv2.COLOR_BGR2GRAY)
    faces = self.facec.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        fc = gray[y:y+h, x:x+w]

        roi = cv2.resize(fc, (48, 48))
        pred = self.model.predict_emotion(roi[np.newaxis, :, :, np.newaxis])

    return pred

此时调用get_frame()函数时,如果输入参数不对,pred就可能没有返回值,这时就会报错:UnboundLocalError: local variable ‘val’ referenced before assignment

我们应该怎么做才能保证,get_frame()函数无论怎么调用都有返回值呢?
我们可以给它一个默认的返回值。改写如下:

    self.pred = 'Neutral'

def get_frame(self):
    KSIZE = 11
    ALPHA = 2
    kernel = cv2.getGaussianKernel(KSIZE, 0)
    kernel = -ALPHA * kernel @ kernel.T
    kernel[KSIZE // 2, KSIZE // 2] += 1 + ALPHA

    filtered = cv2.filter2D(self.img, -1, kernel)
    gray = cv2.cvtColor(filtered, cv2.COLOR_BGR2GRAY)
    faces = self.facec.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        fc = gray[y:y+h, x:x+w]

        roi = cv2.resize(fc, (48, 48))
        self.pred = self.model.predict_emotion(roi[np.newaxis, :, :, np.newaxis])
    return self.pred
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值