最近我在测试sentdex的机器学习代码时,遇到了如下的错误:
Traceback (most recent call last):File "C:\Users\---\Desktop\Images\Foundations Picture\imagerecognition (1).py", line 61, in whatNumIsThisloadExamps = open('numArEx.txt','r').read()IOError: [Errno 2] No such file or directory: 'numArEx.txt'
至于我的代码,编写如下:
from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltimport time#check if it worksfrom collections import Counterdef createExamples(): #下面,文件会在运行脚本后自动创建 numberArrayExamples = open('numArEx.txt','a') #不同的疾病 numbersWeHave = range(0,7) #同一种疾病的不同图片 versionsWeHave = range(1,4) #在目录中创建示例文件 for eachNum in numbersWeHave: for eachVer in versionsWeHave: #print str(eachNum)+'.'+str(eachVer) imgfilePath = ''+str(eachNum)+'.'+str(eachVer)+'.png' ei = Image.open(imgFilePath) eiar = np.array(ei) eiar1 = str(eiar.tolist()) lineToWrite = str(eachNum)+'::'+eiar1+'\n' numberArrayExamples.write(lineToWrite)#将数组转换为黑白def threshold(imageArray): balanceAr = [] newAr = imageArray #对于每种颜色,将较亮的颜色变为白色,较暗的颜色变为黑色。 for eachRow in imageArray: for eachPix in eachRow: avgNum = reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3]) balanceAr.append(avgNum) balance = reduce(lambda x, y: x + y, balanceAr/len(balanceAr)) #改变颜色 for eachRow in newAr: for eachPix in eachRow: if reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3]) > balance: eachPix[0] = 255 eachPix[1] = 255 eachPix[2] = 255 eachPix[3] = 255 else: eachPix[0] = 0 eachPix[0] = 0 eachPix[0] = 0 eachPix[0] = 255 return newAr#模式识别。它比较图片 def whatNumIsThis(filePath): matchAr = [] loadExamps = open('numArEx.txt','r').read() loadExamps = loadExamps.split('\n') i = Image.open(filePath) iar = np.array(i) iarl = iar.tolist() inQuestion = str(iarl) for eachExample in loadExamps: if len(eachExample) > 3: splitEx = eachExample.split('::') currentNum = splitEx[0] currentAr = splitEx[1] eachPixEx = currentAr.split('],') eachPixInQ = inQuestion.split('],') x = 0 while x < len(eachPixEx): if eachPixEx[x] == eachPixInQ[x]: matchedAr.append(int(currentNum)) x += 1 print matchedAr x = Counter(matchedAr) print x graphX = [] graphY = [] for eachThing in x: print eachThing graphX.append(eachThing) print x[eachThing] graphY.append(x[eachThing]) fig = plt.figure() ax1 = plt.subplot2grid((4,4),(0,0), rowspan=1, colspan=4) ax2 = plt.subplot2grid((4,4),(1,0), rowspan=3, colspan=4) ax1.imshow(iar) ax2.bar(graphX,graphY, align='center') #将y轴限制在400 plt.ylim(400) xloc = plt.MaxNLocator(12) ax2.xaxis.set_major_locator(xloc)#在这里导入图片whatNumIsThis('Foundations Picture/0.1.png')
当我阅读此代码的指南时,它说newArEx.txt文件应该会自动创建,所以我对为什么会出现这个错误感到困惑。能有人解释一下吗?谢谢。
回答:
你要求它加载txt文件,但你还没有创建它。你需要先运行createExamples()
。然后你才能运行whatNumIsThis()
。另外,你的缩进仍然有问题。在createExamples()
中,你命名的变量是imgfilePath
,但你调用的是imgFilePath
。