import os
import cv2 as cv
import xml.etree.ElementTree as ET
def xml_to_jpg(imgs_path, xmls_path, out_path):
imgs_list = os.listdir(imgs_path)
xmls_list = os.listdir(xmls_path)
if len(imgs_list) <= len(xmls_list):
for imgName in imgs_list:
temp1 = imgName.split('.')[0]
temp1_ = imgName.split('.')[1]
if temp1_!='jpg' and temp1_ !='jpeg':
continue
for xmlName in xmls_list:
temp2 = xmlName.split('.')[0]
temp2_ = xmlName.split('.')[1]
if temp2_ != 'xml':
continue
if temp2!=temp1:
continue
else:
img_path = os.path.join(imgs_path, imgName)
xml_path = os.path.join(xmls_path, xmlName)
img = cv.imread(img_path)
labelled = img
root = ET.parse(xml_path).getroot()
for obj in root.iter('object'):
bbox = obj.find('bndbox')
xmin = int(bbox.find('xmin').text.strip())
ymin = int(bbox.find('ymin').text.strip())
xmax = int(bbox.find('xmax').text.strip())
ymax = int(bbox.find('ymax').text.strip())
labelled = cv.rectangle(labelled, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2)
cv.imwrite(out_path + '\\' +imgName, labelled)
break
else:
for xmlName in xmls_list:
temp1 = xmlName.split('.')[0]
temp1_ = xmlName.split('.')[1]
if temp1_ != 'xml':
continue
for imgName in imgs_list:
temp2 = imgName.split('.')[0]
temp2_ = imgName.split('.')[1]
if temp2_ != 'jpg' and temp2_ != 'jpeg':
continue
if temp2 != temp1:
continue
else:
img_path = os.path.join(imgs_path, imgName)
xml_path = os.path.join(xmls_path, xmlName)
img = cv.imread(img_path)
labelled = img
root = ET.parse(xml_path).getroot()
for obj in root.iter('object'):
bbox = obj.find('bndbox')
xmin = int(bbox.find('xmin').text.strip())
ymin = int(bbox.find('ymin').text.strip())
xmax = int(bbox.find('xmax').text.strip())
ymax = int(bbox.find('ymax').text.strip())
labelled = cv.rectangle(labelled, (xmin, ymin), (xmax, ymax), (0, 0, 255), 1)
cv.imwrite(out_path + '\\' +imgName, labelled)
break
if __name__ == '__main__':
imgs_path = r'C:\Users\WJY\Desktop\video_stream0505\video_stream0505\FlowManagement02\pic'
xmls_path = r'C:\Users\WJY\Desktop\video_stream0505\video_stream0505\FlowManagement02\label'
retangele_img_path = r'C:\Users\WJY\Desktop\video_stream0505\video_stream0505\FlowManagement02\retangle'
xml_to_jpg(imgs_path, xmls_path, retangele_img_path)