不同python模板中if循环的输出
我的项目是关于形状检测,我必须检测给定图像中的不同矩形,然后将这些数据导入到.qml文件中,我已经能够这样做了,但问题是控制台(我使用Spyder)中的输出是n个模板(.qml),其中n是图像中矩形的数量,在我的文件夹中只有一个.qml文件(控制台中的最后一个) 我不知道我的错在哪里。 下面是我的代码摘录:不同python模板中if循环的输出,python,Python,我的项目是关于形状检测,我必须检测给定图像中的不同矩形,然后将这些数据导入到.qml文件中,我已经能够这样做了,但问题是控制台(我使用Spyder)中的输出是n个模板(.qml),其中n是图像中矩形的数量,在我的文件夹中只有一个.qml文件(控制台中的最后一个) 我不知道我的错在哪里。 下面是我的代码摘录: if shape == "rectangle": x,y,w,h = cv2.boundingRect(c) cv2.rectangle(image,
if shape == "rectangle":
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),0)
myfile.write('The cordinations of the rectangle are :\n')
myfile.write('x : '+str(x)+'\n')
myfile.write('y : '+str(y)+'\n')
myfile.write('width : '+str(w)+'\n')
myfile.write('height : '+str(h)+'\n')
# Open template file and pass string to 'data'.
# Will be in QML syntax except with the string.Template replace tags
# with the format of '$var'. The 'var' MUST correspond to the items
# that will be calculated (i.e. coordinates, sizes, ids, etc.)
with open('cordinations.txt', 'r') as my_template:
data = my_template.read()
# Print template for visual cue.
print('Template loaded:')
print(data)
# Pass 'data' to string.Template object data_template.
data_template = string.Template(data)
cordinates=[]
cordinates.append(dict(abscisse=x,ordonee=y,width=w,height=h))
t=Template("""
x: $abscisse
y: $ordonee
w: $width
h: $height
""")
print " Rectangle:"
print(" {")
for data in cordinates:
print (t.substitute(data))
print(" }")
# Open QML output file and fill its contents by string substitution
with open("main.qml", 'w') as output_file:
# Run string.Template substitution on data_template
# using data from 'values' as source and write to 'output_file'.
output_file.write('import QtQuick 2.2')
output_file.write('\nItem')
output_file.write(" \n{")
output_file.write(" id:\n")
output_file.write(' height: '+str(height)+'\n')
output_file.write(' width: '+str(width)+'\n')
if shape == 'rectangle':
output_file.write(' \n\n Rectangle')
output_file.write(" \n {")
output_file.write(' \n id:')
output_file.write(t.substitute(data))
output_file.write("}")
output_file.write("\n}")
output_file.close()
# Print QML generated code for visual cue.
with open('main.qml', 'r') as my_qml:
qml_code = my_qml.read()
print('QML code generated:')
print(qml_code)
# show the output image
cv2.imshow("Shapes", image)
cv2.waitKey(0)
感谢您的时间和帮助您需要在您的应用程序中使用
'a'
(追加)而不是'w'
(写入)
将open(“main.qml”,“w”)作为输出文件:
首先如果
不是循环,则它是一个条件小说明:您不需要在具有-范围的中手动关闭文件描述符(输出文件.close()
)。当您离开作用域时,它将自动完成。感谢您的澄清,我尝试了您的解决方案,但我遇到了以下错误:`with shape=='矩形':`AttributeError:\uuuuuu退出