Reputation: 49
I am new to python & requesting help from experts in this community. I am trying to display the output of the following script in my Tkinter GUI. I have followed many solutions provided on the StackOverflow, but unfortunately, I am unable to implement those solutions in my code. I need help in displaying the output of the following script in my Tkinter GUI. So I can display the output in a Tkinter widget.
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()
Help Required section:
diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100)
Difference_per_label.config(text='diff_per ' + filename + "_&_" + templateFilename + ' saved')
diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100)
& print('diff_per ' + filename + "_&_" + templateFilename + ' saved')
so that if nothing is present in the folder it will throw exception command.Note:
Any help would be appreciated. Thanks in advance.
Req: Please close the answer only if all the solutions of Help Required section: is resolved.
Upvotes: 2
Views: 2944
Reputation: 142641
print()
only sends text on screen. It never returns displayed text.
To assign to variable use it without print()
- ie.
diffvalue = "Image similarity %ge of_{}_&_{}_is {}".format(filename, templateFilename, score * 100)
And now you can display text in Label
or Text
or Listbox
To append text to Label
you have to get old text from Label
, concatenate new text to old text, and put all again to Label
- ie
new_text = 'diff_per {}_&_{} saved'.format(filename, templateFilename)
Difference_per_label["text"] = Difference_per_label["text"] + "\n" + new_text
or shorter wiht +=
Difference_per_label["text"] += "\n" + new_text
Because tkinter
(and other GUIs) doesn't update widget in window when you change text in label but when it ends function executed by Button and it returns to mainloop so you may have to use root.update()
after changing text in Label to force mainloop()
to redraw windgets in window.
To throw exception you need raise()
, not try/except
which is used to catch exception.
And to test if there is no file you would have to get all data from os.listdir()
as list, filter list with endswith()
and check if list is empty.
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"))
Upvotes: 1