python - 在 Tkinter GUI 中显示 Python 脚本的输出

标签 python opencv user-interface image-processing tkinter

我是 python 新手,请求该社区专家的帮助。我正在尝试在我的 Tkinter GUI 中显示以下脚本的输出。我遵循了 StackOverflow 上提供的许多解决方案,但不幸的是,我无法在我的代码中实现这些解决方案。我需要帮助在我的 Tkinter GUI 中显示以下脚本的输出。这样我就可以在 Tkinter 小部件中显示输出。

import os
import tkinter as tk
import cv2
import numpy as np
from PIL import Image
from PIL import ImageTk

class Difference_Button(Sample_Button, Button):
   def on_click_diff_per_button(self, diff_per):
      threshold = 0.8  # set threshold
       resultsDirectory = 'Data/Differece_images'
       sourceDirectory = os.fsencode('Data/images')
       templateDirectory = os.fsencode('Data/Sample_images')
       detectedCount = 0

       for file in os.listdir(sourceDirectory):
           filename = os.fsdecode(file)
           if filename.endswith(".jpg") or filename.endswith(".png"):

               print(filename)

               img = cv2.imread('Data/images/' + filename)
               im_grayRef = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

               for templateFile in os.listdir(templateDirectory):
                   templateFilename = os.fsdecode(templateFile)

                   if filename.endswith(".jpg") or filename.endswith(".png"):
                       Sample_image = cv2.imread('Data/Sample_images/' + templateFilename, 0)
                       #im_graySam = cv2.cvtColor(Sample_image, cv2.COLOR_BGR2GRAY)
                       cv2.waitKey(0)
                       w, h = Sample_image.shape[::-1]

                       score = cv2.matchTemplate(im_grayRef,Sample_image,cv2.TM_CCOEFF_NORMED)
                       #diff = (diff * 255).astype("uint8")
                       cv2.waitKey(0)
                       diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100)
                       # res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
                       loc = np.where(score >= threshold)

                       if (len(loc[0])):
                           detectedCount = detectedCount + 1
                           for pt in zip(*loc[::-1]):
                               cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
                       cv2.imwrite(resultsDirectory + '/diff_per_' + filename + '.jpg', img)
                       Difference_per_label.config(text='diff_per ' + filename + "_&_" + templateFilename + ' saved')
                       print('diff_per ' + filename + "_&_" + templateFilename + ' saved')
                           # break
               #print('detected positive ' + str(detectedCount))
               continue
           else:
               continue


if __name__ == '__main__':


   root = tk.Tk()
   root.title('Image GUI')
   root.geometry('1280x960')
   os.makedirs('Data/Differece_images', exist_ok=True)
   pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
   pw_left.pack(side='left',anchor='nw')
   pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
   pw_left.pack(side='left', anchor='nw')
   frame7 = tk.Frame(pw_left, bd=2, relief="ridge")
   frame7.pack()
   difference_button = Difference_Button(root, frame7)
   Difference_per_label = tk.Label(frame7, text='print', width=40, bg='white', height = '5')
   Difference_per_label.pack(fill=tk.X)
   Diff_label = tk.Label(frame7, textvariable= 'diffvalue', width=40, bg='white', height = '5')
   Diff_label.pack(fill=tk.X)
   Difference_button = tk.Button(frame7, text='Difference',
                                 command=lambda: difference_button.on_click_diff_per_button(Difference_per_label))
   Difference_button.pack(side='bottom', padx=5, pady=5)
   root.mainloop()

需要帮助部分:

  • 如何在 Tkinter 中显示以下命令输出 diffvalue = print("图像相似度 %ge of_"+ filename + "_&_"+ templateFilename + "_is", Score * 100)
  • 以下命令未显示全部 从开始到结束的结果。它只显示最后一个 输出。 Difference_per_label.config(text='diff_per ' + 文件名 + "_&_"+ templateFilename + ' 已保存')
  • 完成后,我想对语句更正标签应用 try except 逻辑,即当前显示为 diffvalue = print("Image相似性 %ge of_"+ filename + "_&_"+ templateFilename + "_is", Score * 100) & print('diff_per ' + filename + "_&_"+ templateFilename + ' saving') 这样,如果文件夹中没有任何内容它会抛出异常命令。

注意:

  • 图像相似度 %ge of_:已修复
  • 文件名:变量
  • _&_:已修复
  • 模板文件名:变量
  • _is:已修复
  • 分数*100:根据差异百分比而变化

如有任何帮助,我们将不胜感激。提前致谢。

要求:只有当需要帮助部分:的所有解决方案都得到解决后,才请关闭答案。

最佳答案

print()只在屏幕上发送文本。它永远不会返回显示的文本。
要分配给变量,请使用不带 print() 的变量- 即。

diffvalue = "Image similarity %ge of_{}_&_{}_is {}".format(filename, templateFilename, score * 100)

现在您可以在 Label 中显示文本或TextListbox

<小时/>

将文本附加到 Label您必须从 Label 获取旧文本,将新文本连接到旧文本,然后再次将所有内容放入 Label -即

new_text = 'diff_per {}_&_{} saved'.format(filename, templateFilename)
Difference_per_label["text"] = Difference_per_label["text"] + "\n" + new_text

或更短的 +=

Difference_per_label["text"] += "\n" + new_text
<小时/>

因为tkinter当您更改标签中的文本时(和其他 GUI)不会更新窗口中的小部件,但当它结束由按钮执行的函数并返回到主循环时,因此您可能必须使用 root.update()更改标签中的文本以强制 mainloop() 后在窗口中重画windgets。

<小时/>

要抛出异常,您需要 raise() ,不是try/except用于捕获异常。

要测试是否没有文件,您必须从 os.listdir() 获取所有数据作为列表,使用 endswith() 过滤列表并检查列表是否为空。

import os

sourceDirectory = '.'

all_files = os.listdir(sourceDirectory)
all_files = [os.fsdecode(file) for file in all_files]
#all_files = map(os.fsdecode, all_files)
all_files = [file for file in all_files if file.lower().endswith((".jpg",".png"))]

#if len(all_files) == 0:
if not all_files:
    raise(Exception("No Files"))

关于python - 在 Tkinter GUI 中显示 Python 脚本的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59387264/

相关文章:

python - openpyxl - 字符样式

python - 计算数据框列中 True/False 的出现次数

python - 无法在 matplotlib x 轴上显示 Pandas 日期索引

c++ - 无法使用大小和类型参数调用 OpenCV 的 Mat::zeros

c++ - 创建单个 exe 的免费 G​​UI 框架?

python - 尝试使用 Python (win32com.client) 从 Outlook 2007 发送邮件

opencv - 在 OpenCV 2.3.0 中计算阈值 IplImage 中 "White Blobs"数量的最佳方法

python - 通过在Python中使用背景减法进行质心跟踪

java - 删除或隐藏单元格中的值

c++ - GTkmm 3.0 如何在框架或窗口之间切换