Editing image the edited part of image remain unchanged - python

Everyone. I want to ask a question. How to make the edited photo able to change with cv2.trackbar (the bug is the trackbar currently doesn't change the edited photo)?
Here's the full code which I created
import tkinter as tk
from PIL import Image as PILImage
from PIL import ImageTk
from tkinter import Label
from tkinter import filedialog
from tkinter import ttk
from tkinter import Menu
import cv2
import matplotlib.pyplot as plt
import numpy as np
effectoption = ["Effect RGB",
"Effect HSV",
"Effect LAB",
"Effect RGBA", "Effect HLS"]
effectoption2 = ["Original(RGB)",
"Original(HSV)",
"Effect3"]
global image, edited
def insertbutton_cb():
global orima, editima
picpath = filedialog.askopenfilename(
title="Select An Image",
filetypes=(("JPG Files", "*.jpg"), ("GIF Files", "*.gif*"), ("PNG files", "*.png"), ("JPEG Files", "*.jpeg"))
)
if len(picpath) > 0:
image = cv2.imread(picpath)
edited = cv2.imread(picpath)
edited = np.array(edited)
#edited = PILImage.fromarray(edited.astype('uint8'))
print(picpath)
print('Original Dimensions : ',image.shape)
print(image)
print(edited)
scale_percent = 50 # percent of original size
width = int(image.shape[1] * scale_percent / 100)
height = int(image.shape[0] * scale_percent / 100)
width2 = int(edited.shape[1] * scale_percent / 100)
height2 = int(edited.shape[0] * scale_percent / 100)
dim = (width, height)
dim2 = (width2, height2)
image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
edited = cv2.resize(edited, dim2, interpolation = cv2.INTER_AREA)
#if effectoption[0] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
#elif effectoption[1] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HSV)
#elif effectoption[2] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2LAB)
#elif effectoption[3] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGBA)
#elif effectoption[4] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HLS)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGBA)
image = PILImage.fromarray(image)
edited = PILImage.fromarray(edited)
#xa, ya, za = np.shape(image)
#xb, yb, zb = np.shape(edited)
#image = np.ones((xa, ya, za), np.uint8)
#edited = np.ones((xb, yb, zb), np.uint8)
image = np.uint8(image)
edited = np.uint8(edited)
#hueSlider = tk.Scale(Frm2, label="Hue",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=huecb)
#hueSlider.pack(anchor=tk.N)
#saturationSlider = tk.Scale(Frm2, label="Saturation",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=satcb)
#saturationSlider.pack(anchor=tk.N)
#brightSlider = tk.Scale(Frm2, label="Brightness",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=brightcb)
#brightSlider.pack(anchor=tk.N)
#contrastSlider = tk.Scale(Frm2, label="Contrast",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=contrastcb)
#contrastSlider.pack(anchor=tk.N)
bright = 255
contrast = 100
saturation = 50
cv2.namedWindow('CV2 Photo Editor')
cv2.createTrackbar('Bright', 'CV2 Photo Editor', 255, 2 * 255, bccb)
cv2.createTrackbar('Contrast', 'CV2 Photo Editor', 255, 2 * 127, bccb)
cv2.createTrackbar('Saturation', 'CV2 Photo Editor', 255, 2 * 255, bccb)
functionbcs(edited, 0, 0, 0)
bccb(0, 0, 0)
teste = controller(edited, bright, contrast, saturation)
cv2.imshow('CV2 Photo Editor', teste)
#cv2.waitKey(0)
if orima is None or editima is None:
orima = Label(image=image)
orima.image = image
orima.pack(side="left", padx= 0, pady=0)
editima = Label(image=edited)
editima.image = edited
editima.pack(side="right", padx= 0, pady=0)
else:
orima.configure(image=image)
editima.configure(image=edited)
orima.image = image
editima.image = edited
def resetbutton_cb():
orima = None
editima = None
def savebutton_cb():
pass
def functionbcs(edited, bright=0, contrast=0, saturation=0):
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
bright = cv2.getTrackbarPos('Bright','CV2 Photo Editor')
contrast = cv2.getTrackbarPos('Contrast','CV2 Photo Editor')
saturation = cv2.getTrackbarPos('Saturation','CV2 Photo Editor')
edited = controller(edited, bright, contrast, saturation)
#print("Edited : " + edited)
print(edited)
cv2.imshow("Edited", edited)
def satcb(satpos = 0):
print(satpos)
def bccb(bright = 0, contrast=0, saturation=0):
print("B : " + str(bright))
bright = cv2.getTrackbarPos('Bright', 'CV2 Photo Editor')
print("C :" + str(contrast))
contrast = cv2.getTrackbarPos('Contrast', 'CV2 Photo Editor')
print("S :" + str(saturation))
saturation = cv2.getTrackbarPos('Saturation', 'CV2 Photo Editor')
def controller(effect, bright=1, contrast=1, saturation=1):
bright = int((bright - 0) * (255 - (-255)) / (510 - 0) + (-255))
contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
saturation = int((saturation - 0) * (100 - (-100)) / (200 - 0) + (-100))
if bright != 0:
if bright > 0:
shadow = bright
max = 255
else:
shadow = 0
max = 255 + bright
alf = (max - shadow) / 255
gam = shadow
cal = cv2.addWeighted(edited, alfa,
edited, 0, gam)
else:
cal = effect
if contrast != 0:
Alf2 = float(131 * (contrast + 127)) / (127 * (131 - contrast))
Gam2 = 127 * (1 - Alf2)
# The function addWeighted calculates
# the weighted sum of two arrays
cal = cv2.addWeighted(cal, Alf2,
cal, 0, Gam2)
cv2.putText(cal, 'B:{},C:{}, S:{}'.format(bright,
contrast, saturation), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('CV2 Photo Editor', effect)
return cal
def exitbutton_cb():
window.destroy()
cv2.destroyAllWindows()
window = tk.Tk()
window.title('Simple Photo Editing')
mb = Menu(window)
#file manager
fm = Menu(mb, tearoff=0)
fm.add_command(label="Open", command=insertbutton_cb)
fm.add_command(label="Save", command=savebutton_cb)
fm.add_separator()
#fm.add_command(label="Cancel Edit", command=pass)
fm.add_command(label="Exit", command=exitbutton_cb)
mb.add_cascade(label="File", menu=fm)
var1 = tk.StringVar(window)
var1.set(effectoption[0])
cr = ttk.Frame(window)
canvas = tk.Canvas(cr)
scrolling = ttk.Scrollbar(cr, orient="vertical", command=canvas.yview)
sw = window.winfo_screenwidth()
sh = window.winfo_screenheight()
Frm = tk.Frame(window, height=50, width=300)
Frm.pack(anchor=tk.N)
Frm2 = tk.Frame(window, height=25, width=100)
Frm2.pack(anchor=tk.NW)
#Frm3 = tk.Frame(window, height=50, width=500)
#Frm3.pack(anchor=tk.N)
#showWin = tk.Label(window, width=100, height=100)
#showWin.pack(side='left')
#showWin2 = tk.Label(window, width=100, height=100)
#showWin2.pack(side='left')
label = ttk.Label(
window, text="Simple Image Photo Editing"
)
resetbutton = tk.Button(Frm, text="Reset", padx=0, pady=0, command=resetbutton_cb)
resetbutton.grid(row=0, column=1)
savebutton = tk.Button(Frm, text="Save", padx=0, pady=0, command=savebutton_cb)
savebutton.grid(row=0, column=2)
orima = None
editima = None
opt = tk.OptionMenu(window, var1, *effectoption)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")
print(opt)
window.config(menu=mb)
cv2.waitKey(0)
tk.mainloop()
When I tried to apply the photo with cv2 slider, the edited image remain unchanged and the value despite the trackbar can slide normally but still won't change for the photo

Related

How to Use Python and tiknter to Read datamatrix from Webcam in python

Reader to create a simple Windows-styled GUI app to read datamatrixfrom the webcam video stream. i'm trying to use OpenCV for Python to capture webcam frames with tkinter GUI .I am trying with pylibdmtx which works well for images but lags and doesn't detect in video.
When using tkinter, we cannot keep drawing the frames in an infinite loop in the main thread. we can use OpenCV to capture a frame and decode the frame by calling the pylibdmtx. Note: before creating a TKImage with the frame, we have to convert the color space of the frame from BRG to RGB.
from tkinter import *
import time
from pylibdmtx.pylibdmtx import decode
import numpy as np
from PIL import Image, ImageTk
import cv2
import tkinter
from tkinter import ttk
from tkinter.ttk import Progressbar
w = Tk()
width_of_window = 427
height_of_window = 250
screen_width = w.winfo_screenwidth()
screen_height = w.winfo_screenheight()
x_coordinate = (screen_width / 2) - (width_of_window / 2)
y_coordinate = (screen_height / 2) - (height_of_window / 2)
w.geometry("%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate))
w.overrideredirect(1)
s = ttk.Style()
s.theme_use('clam')
s.configure("red.Horizontal.TProgressbar", foreground='red', background='#172884')
progress = Progressbar(w, style="red.Horizontal.TProgressbar", orient=HORIZONTAL, length=500, mode='determinate', )
def bar():
l4 = Label(w, text='Loading...', fg='white', bg=a)
lst4 = ('Calibri (Body)', 10)
l4.config(font=lst4)
l4.place(x=18, y=210)
import time
r = 0
for i in range(100):
progress['value'] = r
w.update_idletasks()
time.sleep(0.03)
r = r + 1
w.destroy()
progress.place(x=-10, y=235)
a = '#172884'
Frame(w, width=427, height=241, bg=a).place(x=0, y=0) # 249794
b1 = Button(w, width=10, height=1, text='Get Started', command=bar, border=0, fg=a, bg='white')
b1.place(x=170, y=200)
l1 = Label(w, text='TUNI', fg='#198cdd', bg=a)
lst1 = ('Calibri (Body)', 24, 'bold')
l1.config(font=lst1)
l1.place(x=50, y=80)
l1 = Label(w, text='TECH', fg='white', bg=a)
lst1 = ('Calibri (Body)', 24, 'bold')
l1.config(font=lst1)
l1.place(x=126, y=80)
l2 = Label(w, text='Engineering', fg='#198cdd', bg=a)
lst2 = ('Calibri (Body)', 9)
l2.config(font=lst2)
l2.place(x=55, y=115)
l3 = Label(w, text='services', fg='#198cdd', bg=a)
lst3 = ('Calibri (Body)', 9)
l3.config(font=lst3)
l3.place(x=130, y=115)
w.mainloop()
Detection_start = False
def start():
global Detection_start
Detection_start = not Detection_start
cameratest = tkinter.Tk()
cameratest.geometry("800x800")
cameratest.resizable(800, 600)
cameratest.title("CAMERA DISPLAY")
cameratest.configure(bg="#172884")
panel_image = tkinter.Label(cameratest, width=800, height=500)
panel_image.place(x=15, y=60)
message = "Press ''Start'' to search for code"
panel_text = tkinter.Label(cameratest, text=message, fg='green', bg=a)
poly = ('Times New Roman (Body)', 18)
panel_text.config(font=poly)
panel_text.grid(row=1, column=1, pady=1, padx=220)
Button_start = Button(cameratest, text="Start", command=start, fg=a)
poly1 = ('Times New Roman (Body)', 12)
Button_start.config(font=poly1)
Button_start.place(x=650, y=1)
cam = cv2.VideoCapture(0)
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
start()
cameratest.update()
ret, frame = cam.read()
# Update the image to tkinter...
t0 = time.time()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame = cv2.GaussianBlur(gray, (5, 5), 0)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
lower_white = np.array([170, 170, 170])
upper_white = np.array([255, 255, 255])
white_mask = cv2.inRange(frame, lower_white, upper_white)
ret, im_th = cv2.threshold(white_mask, 90, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(white_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3)
if Detection_start:
frame1 = cv2.resize(frame, (0, 0), fx=0.2, fy=0.2)
code = decode(frame1, max_count=1, corrections=3)
if code:
print((time.time() - t0) * 1000)
print(code)
print(code[0].data.decode('utf-8'))
print(code[0].rect)
x, y, w, h = code[0].rect
cv2.rectangle(frame, (x * 5, y * 5), (x * 5 + w * 5, y * 5 + h * 5), (0, 255, 0), 2)
else:
panel_text.configure(text="no code found ! ", fg='red')
else:
panel_text.configure(text="Press ''Start'' to search for code", fg='blue')
img_update = ImageTk.PhotoImage(Image.fromarray(frame))
panel_image.configure(image=img_update)
panel_image.image = img_update
panel_image.update()
I first ran the main loop with Tkinter, then in this loop I ran loop Opencv.
and in it sent frames to interfeis

How could I use a number incrementor to show a specific amount of images in tkinter?

I am trying to connect dice png files in a window, but I can not seem to connect the number incrementor that goes up to 10(for 10 images) to align with the said amount of dice. Is there a way to connect them?
This is a define function(firstDicePage()). Asks for the amount of dice you want to roll.
# enables and disables the minus and plus button
def changeMinusState():
if (btn2['state'] == NORMAL):
btn2['state'] = DISABLED
else:
btn2['state'] = NORMAL
def changePlusState():
if (btn1['state'] == NORMAL):
btn1['state'] = DISABLED
else:
btn1['state'] = NORMAL
def increase():
counter.set(min(10, counter.get() + 1))
def decrease():
counter.set(max(0, counter.get() - 1))
lbl = Label(firstWindow, textvariable = counter, font='Helvetica 16 bold')
lbl.place(x=450, y=330)
btn1 = Button(firstWindow, text="+", font='Helvetica 16 bold', padx = 8, pady = 5, command = increase, fg="dark green", bg = "white")
btn1.place(x=499, y=320)
btn2 = Button(firstWindow, text ="-", font='Helvetica 16 bold', padx = 11.1, pady = 5, command = decrease, fg="dark green", bg = "white")
btn2.place(x=375, y=320)
btn4 = Button(firstWindow, text = "Next", font='Helvetica 16 bold', command=lambda: secondDicePage())
btn4.place(x = 800 , y = 530)
btn5 = Button(firstWindow, text = "Select", font ='Helvetica 16 bold', command = lambda: [changeMinusState(), changePlusState()], bg='#ffffff',
activebackground = 'green', padx = 19, pady = 2)
btn5.place(x = 400, y = 385)
This define function connects to the first one. It has the dice.
Updated
def secondDicePage(num_dices):
secondWindow = tkinter.Toplevel(window) # Create new window.
secondWindow.title("Dice Roller Generator")
# Change Icon photo
image = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
secondWindow.iconphoto(False, image)
# Center
app_width = 900
app_height = 600
screen_width = secondWindow.winfo_screenwidth()
screen_height = secondWindow.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
secondWindow.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
images
dice = ['dice_1.png', 'dice_2.png', 'dice_3.png', 'dice_4.png', 'dice_5.png', 'dice_6.png']
# middle image
img1 = ImageTk.PhotoImage(Image.open("C:\\Users\\alexi\\Desktop\\Project Photos\\questionmark.png"))
lbl1 = Label(secondWindow, image=img1)
lbl1.img = img1 # Save reference to image.
lbl1.pack()
lbl1.place(x = 380 , y = 95)
lbl2 = Label(secondWindow, image=img1)
lbl2.img = img1 # Save reference to image.
lbl2.pack()
lbl2.place(x = 195 , y = 95)
lbl3 = Label(secondWindow, image=img1)
lbl3.img = img1 # Save reference to image.
lbl3.pack()
lbl3.place(x = 565 , y = 95)
lbl4 = Label(secondWindow, image=img1)
lbl4.img = img1 # Save reference to image.
lbl4.pack()
lbl4.place(x = 746 , y = 95)
lbl5 = Label(secondWindow, image=img1)
lbl5.img = img1 # Save reference to image.
lbl5.pack()
lbl5.place(x = 1 , y = 95)
lbl6 = Label(secondWindow, image=img1)
lbl6.img = img1 # Save reference to image.
lbl6.pack()
lbl6.place(x = 380 , y = 300)
lbl7 = Label(secondWindow, image=img1)
lbl7.img = img1 # Save reference to image.
lbl7.pack()
lbl7.place(x = 195 , y =300)
lbl8 = Label(secondWindow, image=img1)
lbl8.img = img1 # Save reference to image.
lbl8.pack()
lbl8.place(x = 565 , y = 300)
lbl9 = Label(secondWindow, image=img1)
lbl9.img = img1 # Save reference to image.
lbl9.pack()
lbl9.place(x = 746 , y = 300)
lbl10 = Label(secondWindow, image=img1)
lbl10.img = img1 # Save reference to image.
lbl10.pack()
lbl10.place(x = 1 , y = 300)
Function for labels
def rolling_dice1():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl1.configure(image = image1, bg = '#B9C6C9')
lbl1.image = image1
def rolling_dice2():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl2.configure(image = image1, bg = '#B9C6C9')
lbl2.image = image1
def rolling_dice3():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl3.configure(image = image1, bg = '#B9C6C9')
lbl3.image = image1
def rolling_dice4():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl4.configure(image = image1, bg = '#B9C6C9')
lbl4.image = image1
def rolling_dice5():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl5.configure(image = image1, bg = '#B9C6C9')
lbl5.image = image1
def rolling_dice6():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl6.configure(image = image1, bg = '#B9C6C9')
lbl6.image = image1
def rolling_dice7():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl7.configure(image = image1, bg = '#B9C6C9')
lbl7.image = image1
def rolling_dice8():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl8.configure(image = image1, bg = '#B9C6C9')
lbl8.image = image1
def rolling_dice9():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl9.configure(image = image1, bg = '#B9C6C9')
lbl9.image = image1
def rolling_dice10():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl10.configure(image = image1, bg = '#B9C6C9')
lbl10.image = image1
widgets
btn1 = Button(secondWindow, text = "Back", font='Helvetica 16 bold', command = secondWindow.destroy)
btn1.place(x = 30 , y = 530)
btn2 = Button(secondWindow, text = "Roll Dice", font='Helvetica 16 bold', command = lambda: [rolling_dice1(), rolling_dice2(), rolling_dice3(), rolling_dice4(), rolling_dice5(), rolling_dice6(), rolling_dice7(), rolling_dice8(),
rolling_dice9(), rolling_dice10()])
btn2.place(x = 400 , y = 30)

Tk Window closing not going to classes

I've been running my code on python idle while working on this and didn't receive any problems until I tried running it on visual studio. When running it the tk window just closes and it doesn't go to the classes it tells it too. I am still learning so I probably have some mistakes I would love to get any feedback.
import tkinter as tk
#Takes photos with certain char and if clicked another char program stops
from cv2 import *
import numpy as np
import cv2
import os
from datetime import datetime
now = datetime.now()
time = now.strftime("%H:%M:%S")
#sets the directory and text info
os.chdir(r"C:\Users\asdasd\Desktop\camera")
file_name = 'pic'
cam = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_TRIPLEX
org = (00,300)
fontScale = 1
color = (255,0,0)
thickness = 1
root= tk.Tk()
photo = tk.PhotoImage(file=r"C:\Users\asdas\Desktop\camera\pic.png")
root.iconphoto(False, photo)
root.geometry("+0+50")
print("created window")
#Creates window
canvas1 = tk.Canvas(root, width = 600, height = 600)
canvas1.pack()
canvas1.configure(bg='lightgray')
root.title("ShippingData")
root.lift()
#text label for batch #
label1 = tk.Label(root, text='Enter Batch# :')
label1.config(font=('helvetica', 15))
canvas1.create_window(65, 50, window=label1)
print("created window")
#creates input window for batch #
entry1 = tk.Entry (root)
canvas1.create_window(200, 50, window=entry1)
#text label for initials
label1 = tk.Label(root, text='Enter initials :')
label1.config(font=('helvetica', 15))
canvas1.create_window(65, 100, window=label1)
#creates input window for intials
entry2 = tk.Entry (root)
canvas1.create_window(200, 100, window=entry2)
#gets the info after start button is pressed
def getInfo ():
print("getinfo")
x1 = entry1.get()
x2 = entry2.get()
name = str(x1 + x2)
global dirname
dirname = name
os.mkdir(dirname)
label1 = tk.Label(root, text= "Program Starting")
canvas1.create_window(200, 230, window=label1)
canvas1.destroy()
programStarted()
print("button")
button1 = tk.Button(root, text='Start', command=getInfo)
print("button created")
canvas1.create_window(200, 180, window=button1)
print("canvas created for window")
def programStarted():
print("programstart")
root.update()
#creates new window
global canvas2
canvas2 = tk.Canvas(root, width = 400, height = 300)
canvas2.pack()
# Camera instructions
label2 = tk.Label(root, text= "Press z to take Photos.")
canvas2.create_window(200, 100, window=label2)
label3 = tk.Label(root, text= "Press c multiple times when finished to stop taking photos. ")
canvas2.create_window(200, 150, window=label3)
root.update()
camera()
#camera program
def camera():
print("camera")
global n
global time
global path
n= 1
while(True):
numphoto = "#" + str(n)
ret, frame = cam.read()
cv2.namedWindow("Shipping camera", cv2.WINDOW_NORMAL)
scale_percent = 100 # percent of original size
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
scale_percent = 100 # percent of original size
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
cv2.putText(frame, numphoto, org, font, fontScale,color,thickness, cv2.LINE_AA, False)
cv2.imshow('Shipping camera', frame)
cv2.setWindowProperty("Shipping camera", cv2.WND_PROP_TOPMOST, 1)
if cv2.waitKey(1) & 0xFF == ord('z'):
n+=1
cv2.imwrite(os.path.join(dirname,(file_name + (str(n-1)) + ".jpg")), frame)
path = (os.path.join(str(r"C:\Users\sadsads\Desktop\camera"), str(dirname)))
elif (cv2.waitKey(1) & 0xFF == ord('c')):
# stops everything
cam.release()
cv2.destroyAllWindows()
with open((path+r'\timelog.txt'), 'w') as f:
f.write(time+ '\n')
now = datetime.now()
time2 = now.strftime("%H:%M:%S")
f.write(time2+ '\n')
y = 0
if(y == 0):
# destory the other windows
root.quit()
root.destroy()
break
else:
root.mainloop()

Tkinter frame expand is only displaying half my window

I'm trying to create a phone in tkinter and i'm using frames but the image is being cut in half. Does anyone know why?
https://i.stack.imgur.com/mOtEn.png
import tkinter as tk
def raiseframe(frame):
frame.tkraise()
root = tk.Tk()
bgImage = tk.PhotoImage(file="Phone.gif")
WALogo = tk.PhotoImage(file="whatsappLogo.gif")
width = bgImage.width()
height = bgImage.height()
root.title("Phone")
root.geometry("%dx%d+0+0" % (width, height))
main = tk.Frame()
whatsapp = tk.Frame()
for frame in (main, whatsapp):
frame.pack(fill = tk.BOTH, expand = True)
#Mainscreen:
canvas = tk.Canvas(main, width = width, height = height, bg = "black")
canvas.create_image((width / 2, height / 2), image = bgImage)
canvas.place(x = 0, y = 0)
WAB = tk.Button(main, image = WALogo, command = lambda: raiseframe(whatsapp))
WAB.place(x = 35, y = 85)
raiseframe(main)
root.mainloop()
I believe you have added the picture into a frame which only takes up up to half of the screen.
You could either:
change the dimensions of the frame
add the picture to root like this:
canvas = tk.Canvas(root, width = width, height = height, bg = "black")
canvas.create_image((width / 2, height / 2), image = bgImage)

Can you rescale a PhotoImage in Python Tkinter?

In my program, I have two buttons. button1 calls a function (bt1) which displays an image in the window and then deletes both buttons. button2 calls a function(bt2) I would like this button to display the same image as button1 but by half the scale factor. I am thinking something like this:
scale_half_img = PhotoImage(file = 'Image.png', scale = 0.5)
Of course, this doesn't work but this is the sort of thing I am looking for.
Full code:
from tkinter import *
window = Tk()
def bt1():
img = PhotoImage(file = 'Image.png')
imglbl = Label(window, image = img, anchor = 'nw')
imglbl.place(x = 0, y = 0, width = 865, height = 800)
button1.destroy()
button2.destroy()
def bt2():
# display scaled down image
button1.destroy()
button2.destroy()
button1 = Button(window, text = 'Display Image', command = bt1)
button1.place(x = 10, y = 10, width = 200, height = 30)
button2 = Button (window, text = 'Display Rescaled Image', command = bt2)
button2.place(x = 10, y = 50, width = 200, height = 30)
window.mainloop()
Use PIL.Image to resize an image in tkinter. You can do it as follows:
from PIL import Image, ImageTk
img = Image.open('<Path to Image>')
img = img.resize((img.size[0]/2, img.size[1]/2), Image.ANTIALIAS)
resized_image = ImageTk.Photoimage(img) # use this

Categories