2017-03-08 91 views
-1

我试图将GUI(tkinter)添加到我的脚本中,但无济于事。如果有人能帮助我,我会很感激。我正在使用Python 3.6,我认为最新的opencv?将GUI添加到Python脚本

我只在2周前开始编程。所以,有点新到这一切。基本上,我想创建一个窗口,从我的文件夹中选择图像,然后通过脚本进行处理,以便每当我想使用其他图像时,我都不必更改脚本。我希望这是有道理的..

这是我从youtube从Chris Dahms采取的脚本,并设法将其更改为我想要的。

import cv2 
import numpy as np 
import os 

import DetectChars 
import DetectPlates 
import PossiblePlate 

SCALAR_BLACK = (0.0, 0.0, 0.0) 
SCALAR_WHITE = (255.0, 255.0, 255.0) 
SCALAR_YELLOW = (0.0, 255.0, 255.0) 
SCALAR_GREEN = (0.0, 255.0, 0.0) 
SCALAR_CYAN = (255.0, 255.0, 0.0) 

showSteps = False 

def main(): 

blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()   

if blnKNNTrainingSuccessful == False:        
    print ("\nerror: KNN training was not successful\n")  
    return               

imgOriginalScene = cv2.imread("CAR/Malaysia/22.jpg") 

if imgOriginalScene is None: 
    print ("\nerror: image not read from file \n\n") 
    os.system("pause") 
    return 

if imgOriginalScene is None:        
    print ("\nerror: image not read from file \n\n")  
    os.system("pause")         
    return 

listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)   

listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)   

cv2.imshow("imgOriginalScene", imgOriginalScene)    

if len(listOfPossiblePlates) == 0:       
    print ("\nno license plates were detected\n")    
else:             



    listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True) 


    licPlate = listOfPossiblePlates[0] 

    cv2.imshow("Image Plate", licPlate.imgPlate)   
    cv2.imshow("Image Threshold", licPlate.imgThresh) 

    if len(licPlate.strChars) == 0:      
     print ("\nno characters were detected\n\n")  
     return          


    drawRedRectangleAroundPlate(imgOriginalScene, licPlate)   

    print ("\nlicense plate read from image = " + licPlate.strChars + "\n")  
    print ("----------------------------------------") 

    writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)  

    cv2.imshow("imgOriginalScene", imgOriginalScene)    

    cv2.imwrite("imgOriginalScene.png", imgOriginalScene)   



cv2.waitKey(0)    

return 

def drawRedRectangleAroundPlate(imgOriginalScene, licPlate): 

p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene)   

cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_RED, 2)  
cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), SCALAR_RED, 2) 
cv2.line(imgOriginalScene, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), SCALAR_RED, 2) 
cv2.line(imgOriginalScene, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), SCALAR_RED, 2) 


def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate): 
ptCenterOfTextAreaX = 0       
ptCenterOfTextAreaY = 0 

ptLowerLeftTextOriginX = 0       
ptLowerLeftTextOriginY = 0 

sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape 
plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape 

intFontFace = cv2.FONT_HERSHEY_SIMPLEX     
fltFontScale = float(plateHeight)/30.0      
intFontThickness = int(round(fltFontScale * 2))   

textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace, fltFontScale, intFontThickness)  


((intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg) = licPlate.rrLocationOfPlateInScene 

intPlateCenterX = int(intPlateCenterX)   
intPlateCenterY = int(intPlateCenterY) 

ptCenterOfTextAreaX = int(intPlateCenterX)   

if intPlateCenterY < (sceneHeight * 0.75):            
    ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(round(plateHeight * 1.6)) 
else:                     
    ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(round(plateHeight * 1.6))  


textSizeWidth, textSizeHeight = textSize    

ptLowerLeftTextOriginX = int(ptCenterOfTextAreaX - (textSizeWidth/2))   
ptLowerLeftTextOriginY = int(ptCenterOfTextAreaY + (textSizeHeight/2))   


cv2.putText(imgOriginalScene, licPlate.strChars, (ptLowerLeftTextOriginX, ptLowerLeftTextOriginY), intFontFace, fltFontScale, SCALAR_CYAN, intFontThickness) 



if __name__ == "__main__": 
main() 

cv2.waitKey() 
cv2.destroyAllWindows() 

预处理阶段

# Preprocess.py 

import numpy as np 
import math 

# module level variables ########################################################################## 
GAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5) 
ADAPTIVE_THRESH_BLOCK_SIZE = 19 
ADAPTIVE_THRESH_WEIGHT = 9 


def preprocess(imgOriginal): 
imgGrayscale = extractValue(imgOriginal) 

imgMaxContrastGrayscale = maximizeContrast(imgGrayscale) 

height, width = imgGrayscale.shape 

grayscaled = cv2.cvtColor(imgOriginal,cv2.COLOR_BGR2GRAY) 

imgBlurred = np.zeros((height, width, 1), np.uint8) 

imgBlurred, otsu = cv2.threshold(grayscaled,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) 

imgThresh = cv2.medianBlur(otsu,5) 

return imgGrayscale, imgThresh 
# end function 


def extractValue(imgOriginal): 
height, width, numChannels = imgOriginal.shape 

imgHSV = np.zeros((height, width, 3), np.uint8) 

imgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV) 

imgHue, imgSaturation, imgValue = cv2.split(imgHSV) 

return imgValue 
# end function 

def maximizeContrast(imgGrayscale): 

height, width = imgGrayscale.shape 

imgTopHat = np.zeros((height, width, 1), np.uint8) 
imgBlackHat = np.zeros((height, width, 1), np.uint8) 

structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) 

imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement) 
imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement) 

imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat) 
imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat) 

return imgGrayscalePlusTopHatMinusBlackHat 
# end function 
+0

尝试并更具体地了解您所寻找的内容,并且只包含与您的问题直接相关的代码。你会得到更多有用的答案,因为人们会知道你需要什么帮助。 – darrenvba

+0

我的不好,这是我第一次尝试在这里问问题。我想添加GUI到脚本。我想创建一个窗口,从我的文件夹中选取图像,然后通过脚本处理它,以便每当我想使用其他图像时,我都不必更改脚本。 我希望有道理..我会再次编辑说明.. 谢谢你的答复。 –

回答

0

如果所有你想要的窗口选择一个文件,然后这应该工作。

import Tkinter 
from Tkinter import * 
import tkSimpleDialog 
from tkFileDialog import askopenfilename 

master = Tk() 
master.withdraw() 
my_file = askopenfilename() 
mainloop() 
+1

谢谢你,它的工作原理..但是对于Python 3,只是改为tkinter,第三行改为从tkinter导入simpledialog,第四行改为从tkinter.filedialog导入askopenfilename并且它应该运行.. 再次感谢您帮助我 –

0

我建议Gtk3您的GUI。 这里有一个简单的Gtk窗口按钮:

#!/usr/bin/env python3 

import gi 
gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk 

class Window(Gtk.Window): 
    def __init__(self): 
     Gtk.Window.__init__(self) 
     self.connect('destroy', lambda q: Gtk.main_quit()) 

     button = Gtk.Button("Gtk.Button") 
     button.connect("clicked", self.on_button_clicked) 

     grid = Gtk.Grid() 
     grid.attach(button, 0, 0, 1, 1) 

     self.add(grid) 
     self.show_all() 

    def on_button_clicked(self, button): 
     print("Gtk.Button was clicked") 

w = Window() 
Gtk.main() 
+0

非常感谢你的回复。我会尝试在我的项目中使用它。在这里我撕裂同事和我的头发,因为我没有足够的能力来完成的东西..再次感谢你.. –