TypeError:/:'NoneType'和'int'的不支持的操作数类型

时间:2016-11-14 16:29:31

标签: python-2.7 opencv

我正在尝试从目录中的一组图像中获取平均值,但运行时出现此错误。

请帮我解决这个问题,下面是代码

import os
import cv2 as cv
import numpy as np
path = "C:\Users\Karanths\Desktop\Images1\Hasa1"
files=os.listdir("C:\Users\Karanths\Desktop\Images1\Hasa1")
means=[]
i=0
for f in files:
 fname=path+f
 img=cv.imread(fname,0)
 avg=np.mean(img)
 means.append(avg)
 np.savetxt("means.txt",means)

1 个答案:

答案 0 :(得分:0)

imread()只能读取图片。

如果您尝试阅读不同的文件格式或文件夹,则会获得img = None,然后您获得np.mean(None),这样您就会收到错误。

在使用img

之前,您必须先检查np.mean(img)
import os
import cv2 as cv
import numpy as np

means = []

path = "C:\\Users\\Karanths\\Desktop\\Images1\\Hasa1"

files = os.listdir(path)

for name in files:
    fullname = os.path.join(path, name)

    img = cv.imread(fullname, 0)

    if img is not None: # `if img:` doesn't work because it can be numpy array which works different
        avg = np.mean(img)
        means.append(avg)
    else:
        print('Unknow file format:', name)

np.savetxt("means.txt", means)