1. 程式人生 > 其它 >將xml中目標框繪製到原圖上

將xml中目標框繪製到原圖上

技術標籤:好用的python小程式python

在這裡插入圖片描述
做目標檢測的首要前提是對自己的資料瞭如指掌,有時候使用其他人的資料集,第一時間可能不知道其他人的打標籤標準是什麼,那麼我們可以可視出來目標框,把標籤檔案裡的座標繪製到原圖上,下面程式只需要給定圖片、標籤和儲存位置,就可以直接使用。

# -*- coding: utf-8 -*-
from __future__ import division
import os
import xml.dom.minidom
import cv2
import sys
import numpy as np
# from imp import reload
# reload(sys)
def read_xml(ImgPath, AnnoPath, Savepath): imagelist = os.listdir(AnnoPath) for image in imagelist: image_pre, ext = os.path.splitext(image) # imgfile = +'/'+ image_pre+ '.JPG' imgfile = os.path.join(ImgPath,image_pre+ '.jpg') # xmlfile = AnnoPath +'/'+ image_pre+ '.xml'
xmlfile = os.path.join(AnnoPath, image_pre + '.xml') print(imgfile) print(xmlfile) # im = cv2.imread(imgfile) im = cv2.imdecode(np.fromfile(imgfile,dtype=np.uint8),cv2.IMREAD_UNCHANGED)#imdecode()讀取影象資料並轉換成圖片格式 #fromfile()讀資料時需要使用者指定元素型別,並對陣列的形狀進行適當的修改,cv2.IMREAD_UNCHANGED載入影象
DomTree = xml.dom.minidom.parse(xmlfile)#讀取xml檔案中的值 annotation = DomTree.documentElement #documentElement 屬性可返回文件的根節點。 filenamelist = annotation.getElementsByTagName('filename')#getElementById()可以訪問Documnent中的某一特定元素,顧名思義,就是通過ID來取得元素,所以只能訪問設定了ID的元素。 filename = filenamelist[0].childNodes[0].data objectlist = annotation.getElementsByTagName('object') i = 1 for objects in objectlist: namelist = objects.getElementsByTagName('name') objectname = namelist[0].childNodes[0].data #通過xml檔案給影象加目標框 bndbox = objects.getElementsByTagName('bndbox') for box in bndbox: try: x1_list = box.getElementsByTagName('xmin') x1 = int(x1_list[0].childNodes[0].data) y1_list = box.getElementsByTagName('ymin') y1 = int(y1_list[0].childNodes[0].data) x2_list = box.getElementsByTagName('xmax') x2 = int(x2_list[0].childNodes[0].data) y2_list = box.getElementsByTagName('ymax') y2 = int(y2_list[0].childNodes[0].data) minX = x1 minY = y1 maxX = x2 maxY = y2 if(i % 3 == 0): color = (128,0,0) elif (i % 3 == 1): color = (153, 51, 0) elif (i % 3 == 2): color = (255, 204, 0) elif (i % 3 == 3): color = (0, 51, 0) elif (i % 9 == 4): color = (51, 204, 204) elif (i % 9 == 5): color = (128, 0, 128) elif (i % 9 == 6): color = (0, 255, 255) elif (i % 9 == 7): color = (60, 179, 113) elif (i % 9 == 8): color = (255, 127, 80) elif (i % 9 == 9): color = (0, 255, 0) cv2.rectangle(im,(minX,minY),(maxX,maxY),color,8) if not os.path.exists(Savepath): os.makedirs(Savepath) path = os.path.join(Savepath, image_pre + '.jpg') font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(im, objectname, (minX,minY - 7), font, 0.7, (0, 0, 255), 2) cv2.imencode(".jpg",im)[1].tofile(path) i += 1 except Exception as e: print(e) if __name__ == "__main__": img_path = r'F:\VOC2007_test\JPEGImages/' xml_path = r'F:\VOC2007_test\Annotations/' save_path = r'F:\VOC2007_test\save/' read_xml(img_path, xml_path,save_path)

我們還可以通過修改演算法,讓相同類別的標籤框繪製成同樣的顏色,程式碼如下:

# -*- coding: utf-8 -*-
from __future__ import division
import os
import xml.dom.minidom
import cv2
import sys
import numpy as np


def read_xml(ImgPath, AnnoPath, Savepath):
    imagelist = os.listdir(AnnoPath)
    for image in imagelist:
        image_pre, ext = os.path.splitext(image)
        # imgfile =  +'/'+ image_pre+ '.JPG'
        imgfile = os.path.join(ImgPath,image_pre+ '.jpg')
        # xmlfile = AnnoPath +'/'+ image_pre+ '.xml'
        xmlfile = os.path.join(AnnoPath, image_pre + '.xml')
        print(imgfile)
        print(xmlfile)
        # im = cv2.imread(imgfile)
        im = cv2.imdecode(np.fromfile(imgfile,dtype=np.uint8),cv2.IMREAD_UNCHANGED)#imdecode()讀取影象資料並轉換成圖片格式
        #fromfile()讀資料時需要使用者指定元素型別,並對陣列的形狀進行適當的修改,cv2.IMREAD_UNCHANGED載入影象
        DomTree = xml.dom.minidom.parse(xmlfile)#讀取xml檔案中的值
        annotation = DomTree.documentElement #documentElement 屬性可返回文件的根節點。
        filenamelist = annotation.getElementsByTagName('filename')#getElementById()可以訪問Documnent中的某一特定元素,顧名思義,就是通過ID來取得元素,所以只能訪問設定了ID的元素。
        filename = filenamelist[0].childNodes[0].data
        objectlist = annotation.getElementsByTagName('object')
        i = 1
        for objects in objectlist:
            namelist = objects.getElementsByTagName('name')
            objectname = namelist[0].childNodes[0].data #通過xml檔案給影象加目標框
            bndbox = objects.getElementsByTagName('bndbox')
            for box in bndbox:
                try:
                    x1_list = box.getElementsByTagName('xmin')
                    x1 = int(x1_list[0].childNodes[0].data)

                    y1_list = box.getElementsByTagName('ymin')
                    y1 = int(y1_list[0].childNodes[0].data)

                    x2_list = box.getElementsByTagName('xmax')
                    x2 = int(x2_list[0].childNodes[0].data)

                    y2_list = box.getElementsByTagName('ymax')
                    y2 = int(y2_list[0].childNodes[0].data)

                    minX = x1
                    minY = y1
                    maxX = x2
                    maxY = y2
              
                     if objectname=="類別1":
                        color = (255, 0, 80)
                    if objectname=="類別2":
                        color = (255,0,255)
                    if objectname=="類別3":
                        color = (51, 204, 204)
                    if objectname=="類別4":
                        color = (255, 204, 0)

                    cv2.rectangle(im,(minX,minY),(maxX,maxY),color,8)
             
                    if not os.path.exists(Savepath):
                        os.makedirs(Savepath)
                    path = os.path.join(Savepath, image_pre + '.jpg')
                    font = cv2.FONT_HERSHEY_SIMPLEX
                    cv2.putText(im, objectname, (minX,minY - 7), font, 0.7, (0, 0, 255), 2)
                    #print(path)
                    # cv2.imwrite(path, im)
                    cv2.imencode(".jpg",im)[1].tofile(path)
                    i += 1
                except Exception as e:
                    print(e)

if __name__ == "__main__":
    img_path = r'F:\VOC2007_test\JPEGImages/'
    xml_path = r'F:\VOC2007_test\Annotations/'
    save_path = r'F:\VOC2007_test\save/'
    read_xml(img_path, xml_path,save_path)