Tensorflow 读取XML文件内容并对图片等比例缩放
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow 读取XML文件内容并对图片等比例缩放
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
根據XML文件中對圖片標記的信息讀取,并顯示在圖片中。
xml 文件內容:
<annotation><folder>OXIIIT</folder><filename>samoyed_100.jpg</filename><source><database>OXFORD-IIIT Pet Dataset</database><annotation>OXIIIT</annotation><image>flickr</image></source><size><width>500</width><height>334</height><depth>3</depth></size><segmented>0</segmented><object><name>dog</name><pose>Frontal</pose><truncated>0</truncated><occluded>0</occluded><bndbox><xmin>136</xmin><ymin>1</ymin><xmax>344</xmax><ymax>304</ymax></bndbox><difficult>0</difficult></object> </annotation>目標原圖片:
實現代碼:
import tensorflow as tf import matplotlib.pyplot as plt from lxml import etree from matplotlib.patches import Rectangle img = tf.io.read_file(r'./images/samoyed_100.jpg') # 讀取圖片 img = tf.image.decode_jpeg(img) # 對圖像進行解碼 plt.imshow(img) plt.show()xml = open(r'./xmls/samoyed_100.xml').read() # 讀取 xml文件 sel = etree.HTML(xml) # 對 xml 文件進行解析 width = sel.xpath('//size/width/text()')[0] height = sel.xpath('//size/height/text()')[0] xmin = sel.xpath('//bndbox/xmin/text()')[0] ymin = sel.xpath('//bndbox/ymin/text()')[0] xmax = sel.xpath('//bndbox/xmax/text()')[0] ymax = sel.xpath('//bndbox/ymax/text()')[0] width = int(width) height = int(height) xmin = int(xmin) ymin = int(ymin) xmax = int(xmax) ymax = int(ymax) plt.imshow(img.numpy()) rect = Rectangle((xmin, ymin), (xmax - xmin), (ymax - ymin), fill=False, color='red') # fill=False 不需要填充 ax = plt.gca() # 獲取當前圖像 ax.axes.add_patch(rect) # 添加矩形框 plt.show()得到
對圖片進行比例縮放:
img = tf.image.resize(img, [224, 224]) img = img / 255 # 標準化 xmin = (xmin / width) * 224 ymin = (ymin / height) * 224 xmax = (xmax / width) * 224 ymax = (ymax / height) * 224plt.imshow(img.numpy()) rect = Rectangle((xmin, ymin), (xmax - xmin), (ymax - ymin), fill=False, color='red') ax = plt.gca() ax.axes.add_patch(rect) plt.show()縮放后:
總結
以上是生活随笔為你收集整理的Tensorflow 读取XML文件内容并对图片等比例缩放的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Tensorflow tf.keras.
- 下一篇: TensorFlow ImportErr