在python中为不同的矩形生成不同的模板

时间:2018-05-03 07:29:49

标签: python qml shape

我必须检测给定图像中矩形的坐标,然后将这些数据导入.qml文件,我已经能够这样做了,但问题是我的代码生成了一个新的我的图像中每个矩形的模板,但我想要一个模板用于所有检测到的矩形。我不知道我是否应该添加另一个if条件或究竟是什么!我尝试在此行output_file.write(' \n\n Rectangle')之前添加for循环,但它没有用!

您将在下面找到我的代码摘录:

from tkFileDialog import askopenfilename # Open dialog box
from PIL import Image
from string import Template
def center_of_shape():
    # import the necessary packages
    from pyimagesearch.shapedetector import ShapeDetector
    import argparse
    import imutils
    import cv2
    import numpy as np
    import os
    import string
    outputname='cordinations.txt'
    myfile = open(outputname,'w')
    shapes=["rectangle", "circle", "triangle", "square"]
    # load the image and resize it to a smaller factor so that
    filename = askopenfilename(filetypes=[("image","*.png")])
    image=cv2.imread(filename,1)
    width, height,channels = image.shape
    resized = imutils.resize(image, width=300)
    ratio = image.shape[0] / float(resized.shape[0])
    # convert the resized image to grayscale, blur it slightly and threshold it
    gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
    edged = cv2.Canny(gray, 75, 200)
    # find contours in the thresholded image and initialize the
    cnts = cv2.findContours(thresh.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    sd = ShapeDetector()

    print("Item:")
    print("{")
    #loop over the contours
    for c in cnts:
       # compute the center of the contour, then detect the name of the
       # shape using only the contour
       M = cv2.moments(c)
       cX = int((M["m10"] / M["m00"]) * ratio)
       cY = int((M["m01"] / M["m00"]) * ratio)
       shape = sd.detect(c)
       c = c.astype("float")
       c *= ratio
       c = c.astype("int")        
       # Prints caracteristics of a rectangle
       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'.
           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", 'a') 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')
               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)

from Tkinter import *
rw=Tk()
rw.title("My application menu")

#define  labels 
l1=Label(rw, text="The menu")
l1.grid(row=0,column=2)
l1=Label(rw, text="  ")
l1.grid(row=1,column=2)
l1=Label(rw, text="Apply shape detection")
l1.grid(row=4,column=0)
btn2=Button(rw,text="Shape detection", width =14)
btn2.grid(row=4, column=3)
btn2.config(command=center_of_shape)

rw.mainloop()

感谢您的时间和精力。

0 个答案:

没有答案