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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值