我试图用一个图像和一个xml文件运行它,但效果很好,但是当我尝试使用图像目录和xml文件中的mutliple文件时,会抛出错误。我尝试使用glob读取多个图像,但是它没有用。我想从图像文件夹中创建多个裁剪图像,并且相应地,我想通过更新原始xml文件来创建多个xml文件。 我的代码是:
import random, os
from PIL import Image
import xml.etree.ElementTree as ET
import glob
original_img = "./images"
original_xml = "./xml"
cropped_path = "./croptest1"
newxml_path = "./newxml"
tilesPerImage=5
def crop_cxml(img,xml):
#Take image
#im = Image.open(img)
for i in range(1, tilesPerImage+1):
iname = ifile.replace('.', '_{:02d}.'.format(i))
xname = xfile.replace('.', '_{:02d}.'.format(i))
tree = ET.parse(xml)
root = tree.getroot()
#crop the original image
w, h = img.size
p = 0.5
dx = int(w*p)
dy = int(h*p)
x = random.randint(0, w-dx-1)
y = random.randint(0, h-dy-1)
img.crop((x,y, x+dx, y+dy))\
.save(os.path.join(cropped_path, iname))
#create new xml
xmins = tree.findall('object/bndbox/xmin')
ymins = tree.findall('object/bndbox/ymin')
xmaxs = tree.findall('object/bndbox/xmax')
ymaxs = tree.findall('object/bndbox/ymax')
print('New Values:')
for o_xmin in xmins:
xmin=int(o_xmin.text)
if x+dx<xmin:
xmin=-1
else:
xmin=max(xmin-x,0)
o_xmin.text=str(xmin)
print(o_xmin.text)
for o_ymin in ymins:
ymin=int(o_ymin.text)
if y+dy<ymin:
ymin=-1
else:
ymin=max(ymin-y,0)
o_ymin.text=str(ymin)
print(o_ymin.text)
for o_xmax in xmaxs:
xmax=int(o_xmax.text)
if x>xmax:
xmax=-1
elif xmax<x+dx:
xmax=xmax-x
else:
xmax=dx
o_xmax.text=str(xmax)
print(o_xmax.text)
for o_ymax in ymaxs:
ymax=int(o_ymax.text)
if y>ymax:
ymax=-1
elif ymax<y+dy:
ymax=ymax-y
else:
ymax=dy
o_ymax.text=str(ymax)
print(o_ymax.text)
print('Size of original image:')
print(w,h)
print('Values of x and y:')
print(x,y)
print('Size of cropped image:')
print(dx,dy)
value = '-1'
objects = root.findall('object')
for object in objects:
xmin1 = object.find('./bndbox/xmin')
ymin1 = object.find('./bndbox/ymin')
xmax1 = object.find('./bndbox/xmax')
ymax1 = object.find('./bndbox/ymax')
if value in xmin1.text:
root.remove(object)
if value in ymin1.text:
root.remove(object)
if value in xmax1.text:
root.remove(object)
if value in ymax1.text:
root.remove(object)
tree.write(open(os.path.join(newxml_path , xname), 'wb'))
ifiles = os.listdir(original_img)
xfiles = os.listdir(original_xml)
#xfiles = glob.glob("*.xml")
for ifile in ifiles:
for xfile in xfiles:
with Image.open(os.path.join(original_img, ifile)) as img:
with open(xfile, 'r', encoding="utf-8") as xml:
crop_cxml(img,xml)
我得到的错误是:
File "/Users/sripdeep/Desktop/Tongue_Cancer/TCcrop-xml.py", line 49, in crop_cxml
xmin=int(o_xmin.text)
ValueError: invalid literal for int() with base 10: 'None'
答案 0 :(得分:1)
如mzjn所评论,您有一个None值,无法将其转换为int。
您可以使用可以处理这些情况的函数(请参见下面的代码)
def as_int(val):
try:
res = int(val)
return res
except ValueError:
return -1
# here you need to use a value that represent invalid int for you.
# -1 is just an a example