我是靠谱客的博主 魔幻盼望,最近开发中收集的这篇文章主要介绍tensor如何转为图像_怎么把NumPy数组图像转换成TensorFlow图像?,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

# test.pyimportosimporttensorflowastfimportnumpyasnpimportcv2# module-level variables ##############################################################################################RETRAINED_LABELS_TXT_FILE_LOC=os.getcwd()+"/"+"retrained_labels.txt"RETRAINED_GRAPH_PB_FILE_LOC=os.getcwd()+"/"+"retrained_graph.pb"TEST_IMAGES_DIR=os.getcwd()+"/test_images"#######################################################################################################################defmain():# get a list of classifications from the labels fileclassifications=[]# for each line in the label file . . .forcurrentLineintf.gfile.GFile(RETRAINED_LABELS_TXT_FILE_LOC):# remove the carriage returnclassification=currentLine.rstrip()# and append to the listclassifications.append(classification)# end for# show the classifications to prove out that we were able to read the label file successfullyprint("classifications = "+str(classifications))# load the graph from filewithtf.gfile.FastGFile(RETRAINED_GRAPH_PB_FILE_LOC,'rb')asretrainedGraphFile:# instantiate a GraphDef objectgraphDef=tf.GraphDef()# read in retrained graph into the GraphDef objectgraphDef.ParseFromString(retrainedGraphFile.read())# import the graph into the current default Graph, note that we don't need to be concerned with the return value_=tf.import_graph_def(graphDef,name='')# end with# if the test image directory listed above is not valid, show an error message and bailifnotos.path.isdir(TEST_IMAGES_DIR):print("the test image directory does not seem to be a valid directory, check file / directory paths")return# end ifwithtf.Session()assess:# for each file in the test images directory . . .forfileNameinos.listdir(TEST_IMAGES_DIR):# if the file does not end in .jpg or .jpeg (case-insensitive), continue with the next iteration of the for loopifnot(fileName.lower().endswith(".jpg")orfileName.lower().endswith(".jpeg")):continue# end if# show the file name on std outprint(fileName)# get the file name and full path of the current image fileimageFileWithPath=os.path.join(TEST_IMAGES_DIR,fileName)# attempt to open the image with OpenCVopenCVImage=cv2.imread(imageFileWithPath)# if we were not able to successfully open the image, continue with the next iteration of the for loopifopenCVImageisNone:print("unable to open "+fileName+" as an OpenCV image")continue# end if# show the OpenCV imagecv2.imshow(fileName,openCVImage)# get the final tensor from the graphfinalTensor=sess.graph.get_tensor_by_name('final_result:0')# ToDo: find a way to convert from a NumPy array / OpenCV image to a TensorFlow image# instead of opening the file twice, these attempts don't work# attempt 1:# openCVImageAsArray = np.asarray(openCVImage, np.float32)# tfImage = tf.convert_to_tensor(openCVImageAsArray, np.float32)# attempt 2:# tfImage = np.array(openCVImage)[:, :, 0:3]# open the image in TensorFlowtfImage=tf.gfile.FastGFile(imageFileWithPath,'rb').read()# run the network to get the predictionspredictions=sess.run(finalTensor,{'DecodeJpeg/contents:0':tfImage})# sort predictions from most confidence to least confidencesortedPredictions=predictions[0].argsort()[-len(predictions[0]):][::-1]print("---------------------------------------")# keep track of if we're going through the next for loop for the first time so we can show more info about# the first prediction, which is the most likely prediction (they were sorted descending above)onMostLikelyPrediction=True# for each prediction . . .forpredictioninsortedPredictions:strClassification=classifications[prediction]# if the classification (obtained from the directory name) ends with the letter "s", remove the "s" to change from plural to singularifstrClassification.endswith("s"):strClassification=strClassification[:-1]# end if# get confidence, then get confidence rounded to 2 places after the decimalconfidence=predictions[0][prediction]# if we're on the first (most likely) prediction, state what the object appears to be and show a % confidence to two decimal placesifonMostLikelyPrediction:scoreAsAPercent=confidence*100.0print("the object appears to be a "+strClassification+", "+"{0:.2f}".format(scoreAsAPercent)+"% confidence")onMostLikelyPrediction=False# end if# for any prediction, show the confidence as a ratio to five decimal placesprint(strClassification+" ("+"{0:.5f}".format(confidence)+")")# end for# pause until a key is pressed so the user can see the current image (shown above) and the prediction infocv2.waitKey()# after a key is pressed, close the current window to prep for the next time aroundcv2.destroyAllWindows()# end for# end with# write the graph to file so we can view with TensorBoardtfFileWriter=tf.summary.FileWriter(os.getcwd())tfFileWriter.add_graph(sess.graph)tfFileWriter.close()# end main#######################################################################################################################if__name__=="__main__":main()

最后

以上就是魔幻盼望为你收集整理的tensor如何转为图像_怎么把NumPy数组图像转换成TensorFlow图像?的全部内容,希望文章能够帮你解决tensor如何转为图像_怎么把NumPy数组图像转换成TensorFlow图像?所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部