我的项目是关于形状检测,我必须检测给定图像中的不同矩形,然后将这些数据导入.qml文件,我已经能够这样做,但问题是输出在控制台中(我使用Spyder)是n个模板(.qml),n是图像中矩形的数量,在我的文件夹中只有一个.qml文件(控制台中的最后一个)
我不知道我的错误在哪里。 你会在下面找到我的代码摘录:
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)
感谢您的时间和帮助
答案 0 :(得分:1)
您需要在
中使用'a'
(追加)代替'w'
(写)
with open("main.qml", 'w') as output_file: