根据LabelImg标注的方框大小批量裁剪图片
生活随笔
收集整理的這篇文章主要介紹了
根据LabelImg标注的方框大小批量裁剪图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
根據LabelImg標注的方框大小批量裁剪圖片
用LabelImg軟件在windows下標注了圖片了后,可以根據標注的大小進行圖片的裁剪,下圖是LabelImg軟件圖
代碼
代碼可實現對圖片批量裁剪處理,并且裁剪后的圖片進行了重新命名
import os import xml.dom.minidom from xml.etree import ElementTree as ET import cv2xml_path = 'Datasets/test/contamination' pic_path = 'Datasets/test/contamination'count = 0 s = {} # 對xml文件和圖片文件進行排序,不排序可能導致圖片和xml文件對應不上 xml_files = os.listdir(xml_path) xml_files.sort() pic_files = os.listdir(pic_path) pic_files.sort()for xmlFile in xml_files:if not os.path.isdir(xmlFile):print(xmlFile)# 找到xml文件中的bndbox屬性if xmlFile.endswith('.xml'):per = ET.parse(os.path.join(xml_path, xmlFile))p_value = per.findall('./object/bndbox')# 獲得完整xml中的bndbox的路徑dom = xml.dom.minidom.parse(os.path.join(xml_path, xmlFile))root = dom.documentElement# 通過元素名獲取name的屬性值xml_name = root.getElementsByTagName('name')# xml_object = root.getElementByTagName('object')# 這里case實際為name的第一個child_datafor i in range(len(xml_name)):if xml_name[i].firstChild.data == 'case':values = p_value[i].getchildren()# 獲取坐標值for child in values:s[child.tag] = child.text# 分別將四個點的坐標賦值給四個變量x_min = dict.get(s, 'xmin')y_min = dict.get(s, 'ymin')x_max = dict.get(s, 'xmax')y_max = dict.get(s, 'ymax')# 處理圖片for bmpFile in pic_files:if not os.path.isdir(bmpFile):print(bmpFile)if bmpFile.endswith('.bmp'):if count < 10:# 讀取圖片img = cv2.imread(pic_path + '/' + '000' + str(count) + '.bmp')# 根據獲得的xml中的坐標信息裁剪圖片crop = img[int(y_min):int(y_max), int(x_min):int(x_max)]# 裁剪完成,寫入圖像cv2.imwrite('./Datasets/Test_of_pic_crop/contamination/' + '00' + str(count) + '.bmp', crop)elif 10 <= count < 100:img = cv2.imread(pic_path + '/' + '00' + str(count) + '.bmp')crop = img[int(y_min):int(y_max), int(x_min):int(x_max)]cv2.imwrite('./Datasets/Test_of_pic_crop/contamination/' + '0' + str(count) + '.bmp', crop)else:img = cv2.imread(pic_path + '/' + '0' + str(count) + '.bmp')crop = img[int(y_min):int(y_max), int(x_min):int(x_max)]cv2.imwrite('./Datasets/Test_of_pic_crop/contamination/' + str(count) + '.bmp', crop)count += 1break示例圖片
xml文件:
<annotation><folder>broken_large</folder><filename>0002.bmp</filename><path>C:\Users\13357\Desktop\test\broken_large\0002.bmp</path><source><database>Unknown</database></source><size><width>2592</width><height>1944</height><depth>3</depth></size><segmented>0</segmented><object><name>case</name><pose>Unspecified</pose><truncated>0</truncated><difficult>0</difficult><bndbox><xmin>1554</xmin><ymin>343</ymin><xmax>2195</xmax><ymax>1810</ymax></bndbox></object> </annotation>截切前圖片:
裁剪后圖片:
這里裁剪用到了上面xml文件的xmin、ymin、xmax、ymax四個點的坐標:
總結
以上是生活随笔為你收集整理的根据LabelImg标注的方框大小批量裁剪图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ISO20000与ISO27001认证如
- 下一篇: 非易失性存储器的分类和未来发展预测