def createTestMat(dirName, classNum, testNum, ImageSize): """ 创建测试集 :param dirName: 文件夹名称 :param classNum: 哪一类 :param testNum: 每类中用来测试的图像数量 :param ImageSize: 图像大小 :return: 第classNum类的测试集 """ testMat = np.zeros((testNum, ImageSize)) index = 0 for i in range(1, testNum + 1): dic = './' + str(dirName) + '/' + str(classNum) + '/' + 's' + str( i) + '.bmp' img = ImageSet.HistogramEqualization('./' + str(dirName) + '/' + str(classNum) + '/' + 's' + str(i) + '.bmp') # cv2.imshow(str(classNum) + '/' + 's', img) # name=str(classNum) + '/' + 's'+ str(i) # print('name',name) # cv2.waitKey(0) tempImg = np.reshape(img, (-1, 1)) # 每张图转化为一列 if index == 0: testMat = tempImg index += 1 else: testMat = np.column_stack((testMat, tempImg)) testMat = np.mat(testMat) # 列合并,然后转为矩阵 index += 1 return testMat
def createImageMat(dirName, classNum, classInNum, ImageNum, ImageSize): """ 创建训练集矩阵 :param dirName:包含数据集的文件夹名称 :param classNum: 类数目 :param classInNum: 每类包含的图像数目 :param ImageNum: 图像总数 :param ImageSize: 每张图像的大小 :return: 图像矩阵,#每张图像对应的标签 """ dataMat = np.zeros((ImageNum, ImageSize)) # 生成用0填充的数据集(数组),维度为图像数目*图像大小 # label = np.zeros((1,ImageNum)) label = [] index = 0 for classnum in range(1, classNum + 1): for classinnum in range(1, classInNum + 1): img = ImageSet.HistogramEqualization('./' + str(dirName) + '/' + str(classnum) + '/' + 's' + str(classinnum) + '.bmp') # print('均衡化后的图像矩阵',img) tempImg = np.reshape(img, (-1, 1)) # 每张图转化为一列 if index == 0: dataMat = tempImg label.append(str(classnum)) # label[:,index]=classnum index += 1 else: dataMat = np.column_stack((dataMat, tempImg)) dataMat = np.mat(dataMat) # 列合并,然后转为矩阵 label.append(str(classnum)) # label[:, index] = classnum index += 1 # print('index',index) return dataMat, label
def compare(dataMat, testImg, label): """ :param dataMat:样本矩阵 :param testImg: 测试图像矩阵,最原始形式(未均衡化处理) :param label: 标签矩阵 :return: 结果文件名 """ testImg = ImageSet.HistogramEqualization(testImg) testImg = np.reshape(testImg, (-1, 1)) lowMat, redVects = PCA.pca(dataMat, 0.99) print(' 变换矩阵维度', redVects.shape) print('测试图像维度', testImg.shape) # redVects=np.reshape(redVects, (-1, 1)) testImg = redVects.T * testImg ######### print('样本变化后的维度', testImg.shape) disList = [] testVec = np.reshape(testImg, (1, -1)) print('testVec', testVec.shape) for sample in lowMat.T: disList.append(np.linalg.norm(testVec - sample)) print('disList', disList) sortIndex = np.argsort(disList) return label[sortIndex[0]]
def testPic(dataMat, label): # def testPic(dataMat, label, disc_set, disc_value, redVects, Train_LDA): print("thread") j = 0 isRight = 0 isRight2 = 0 testTimes = 0 while True: testImgSet = './pic/s0.bmp' if not os.path.isfile(testImgSet): continue disc_set, disc_value, meanFace = LDA.pca(dataMat, 40) redVects, Train_LDA = LDA.lda(dataMat, label, 40, 17, 11, 11 * 17) # LDA投影空间,最终的训练集 # testImgSet = createImageSet.createTestMat('Yale', testInClass, testNum, testInClass, 100 * 100) testImgSet = ImageSet.HistogramEqualization(testImgSet) # print("shape", testImgSet.shape) testImgSet = np.reshape(testImgSet, (-1, 1)) testImgSet = disc_set.T.dot(testImgSet) testImgSet = redVects.T.dot(testImgSet) disList = [] testVec = np.reshape(testImgSet, (1, -1)) for sample in Train_LDA.T: disList.append(np.linalg.norm(testVec - sample)) # print('disList', disList) sortIndex = np.argsort(disList) print(label[sortIndex[0]]) if 16 == int(label[sortIndex[0]]): isRight = isRight + 1 if 17 == int(label[sortIndex[0]]): isRight2 = isRight2 + 1 os.remove('./pic/s0.bmp') j = j + 1 # j = j + 1 # 在脸上检测眼睛 (40, 40)是设置最小尺寸,再小的部分会不检测 # eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, 0, (40, 40)) # 把眼睛画出来 # for(ex, ey, ew, eh) in eyes: # cv2.rectangle(img, (x+ex, y+ey), (x+ex+ew, y+ey+eh), (0, 255, 0), 2) if j == 5: if isRight >= 4 or isRight2 >= 4: if isRight >= 4: print("欢迎你,史长顺!") # break camera.release() cv2.destroyAllWindows() break if isRight2 >= 4: print("欢迎你,饶丝雨!") # break camera.release() cv2.destroyAllWindows() break else: if isRight < 4: isRight = 0 testTimes += 1 print("测试失败") if testTimes >= 5: # break camera.release() j = 0 if isRight2 < 4: isRight2 = 0 testTimes += 1 print("测试失败2") if testTimes >= 5: # break camera.release() j = 0
def upload(): if (g.currentUser.acctype == 'Participant'): err = "You don't have permissions to upload" return index(err) setname = request.form.get('filename') setname = re.sub('[^A-Za-z0-9]+', '', setname) imagefiles = request.files.getlist('imagefile') study = request.form.get('study') for dicom in imagefiles: fullname = setname + '-' + str(dicom.filename.strip('.dcm')) # save locally temp to convert from dicom to jpg format tempsaved = path.dirname(path.realpath(__file__)) + '/temp/' if not path.exists(tempsaved): makedirs(tempsaved) dicom.save(tempsaved + fullname) try: output = subprocess.check_output([ 'identify', '-format', '%[dcm:PixelSpacing],', str(tempsaved + fullname) ]) matched_lines = [line for line in output.split(',')] rows, cols = matched_lines[0].strip().split('\\') rows = float(rows) cols = float(cols) resize = "" if (rows == cols): # no resize needed resize = "100%x100%" elif (cols > rows): factor = (cols / rows) * 100 resize = str(factor) + "%x100%" elif (rows > cols): factor = (rows / cols) * 100 resize = "100%x" + str(factor) + "%" except: resize = "100%x100%" convert = subprocess.call([ 'mogrify', '-resize', resize, '-format', 'jpg', tempsaved + fullname ]) set_size = len(fnmatch.filter(listdir(tempsaved), '*.jpg')) if convert != 0: return load_upload_page( error="Unable to convert image, needs a DICOM (.dcm) format") # create UNIQUE image set for this user and setname in database imageset = ImageSet(user_id=g.currentUser.userID, name=fullname, study=study) try: imageset.create() except Exception as e: err = e[1] if "Duplicate" in err: err = "Image set name and DICOM already used for this user" # empty the temp files dir and return error message for img in glob.glob(tempsaved + fullname + '*'): remove(img) return load_upload_page(error=err) # save all in set as blobs in images table in database in correct order for index in range(set_size): if (set_size > 1): picture = tempsaved + fullname + "-" + str(index) + ".jpg" else: picture = tempsaved + fullname + ".jpg" picture = path.abspath(picture) contents = file_get_contents(picture) image = Image(set_id=imageset.id, image=contents) image.create() if set_size > 2: remove(picture) # delete temp files remove(tempsaved + fullname) # delete original return redirect("/" + "?search=" + setname, code=302)
for classnum in range(1, classNum + 1): print('第', classnum, '类') Count += compare(disc_set, Train_LDA, redVects, label, testNum, classnum, 5) print('Final correctCount:', Count / 16) if __name__ == '__main__': # for i in range(1, 11): # dataMat, label = createImageSet.createImageMat('Yale', 16, 11, 176, 100 * 100) # getResult(dataMat, label, 5, 16) # disc_set, disc_value = LDA.pca(dataMat, 50) # redVects, Train_LDA = LDA.lda(dataMat, label, 50, 16, 11, 11 * 16) # LDA投影空间,最终的训练集 testImgSet = './pic/s0.bmp' testImg = ImageSet.HistogramEqualization(testImgSet) testImg = np.reshape(testImg, (-1, 1)) lowMat, redVects = PCA.pca(dataMat, 0.99) testImg = redVects.T * testImg disList = [] testVec = np.reshape(testImg, (1, -1)) for sample in lowMat.T: disList.append(np.linalg.norm(testVec - sample)) sortIndex = np.argsort(disList) # # testImgSet = './Yale/16/s1.bmp' # # testImgSet = createImageSet.createTestMat('Yale', testInClass, testNum, testInClass, 100 * 100) # testImgSet = ImageSet.HistogramEqualization(testImgSet) # testImgSet = np.reshape(testImgSet, (-1, 1)) # testImgSet = disc_set.T.dot(testImgSet) # testImgSet = redVects.T.dot(testImgSet) # disList = []