How can I combine a graph, webcam capture (image) and buttons into the same window? - python-3.x

My code is designed to take an image off of the webcam, display the image, read the RGB colors from multiple pixels OpenCV and then plot those points in a graph (matplotlib). It all works, but I want to have the image, the graph and the buttons all in the same window, instead of three separate windows. Can anyone help?
Here is my code.
import cv2
import numpy as np
import time
from tkinter import *
from matplotlib import pyplot as plt
def closeWindow():
exit()
#def newSample():
def nextSample():
ramp_frames = 30
cv2.destroyAllWindows()
cap = cv2.VideoCapture(0)
s, im = cap.read()
cv2.imshow("test11.bmp", im)
cv2.imwrite("test11.bmp", im)
cv2.destroyAllWindows()
cap.release()
img = cv2.imread('test11.bmp', cv2.IMREAD_COLOR)
#img1 = PhotoImage(file="C:\Users\Isaac Erickson\Documents\Python\test.bmp")
plt.gcf().clear()
px1 = im[90,100]
px2 = im[90,150]
px3 = im[90,200]
px4 = im[90,250]
px5 = im[90,300]
px6 = im[90,350]
px7 = im[90,400]
px8 = im[90,550] #max 480, 640
plt.plot(["300","400","450","500","550", "600","650","700"], [px1,px2,px3,px4,px5,px6,px7,px8]) #x and y coordinates
cv2.imshow('image',im)
plt.show()
def reaction():
ramp_frames = 30
cv2.destroyAllWindows()
cap = cv2.VideoCapture(0)
s, im = cap.read()
cv2.imshow("test11.bmp", im)
cv2.imwrite("test11.bmp", im)
cv2.destroyAllWindows()
cap.release()
img = cv2.imread('test11.bmp', cv2.IMREAD_COLOR)
plt.gcf().clear()
px1 = im[90,100]
px2 = im[90,150]
px3 = im[90,200]
px4 = im[90,250]
px5 = im[90,300]
px6 = im[90,350]
px7 = im[90,400]
px8 = im[90,550] #max 480, 640
plt.plot(["1","2","3","4","5", "6","7","8"], [px1,px2,px3,px4,px5,px6,px7,px8]) #x and y coordinates
cv2.imshow('image',im)
plt.show()
ramp_frames = 30
cap = cv2.VideoCapture(0)
s, im = cap.read()
cv2.imshow("test11.bmp", im)
cv2.imwrite("test11.bmp", im)
cv2.destroyAllWindows()
cap.release()
#Analysis of image
root = Tk()
img = cv2.imread('test11.bmp', cv2.IMREAD_COLOR)
px1 = im[90,100]
px2 = im[90,150]
px3 = im[90,200]
px4 = im[90,250]
px5 = im[90,300]
px6 = im[90,350]
px7 = im[90,400]
px8 = im[90,550] #max 480, 640
plt.plot(["300","400","450","500","550", "600","650","700"], [px1,px2,px3,px4,px5,px6,px7,px8]) #x and y coordinates
title = Label(root, text= "VISIBLE COLORS")
p1 = Label(root, text=px1)
p2 = Label(root, text=px2)
p3 = Label(root, text=px3)
p4 = Label(root, text=px4)
p5 = Label(root, text=px5)
p6 = Label(root, text=px6)
p7 = Label(root, text=px7)
p8 = Label(root, text=px8)
title.pack()
p1.pack()
p2.pack()
p3.pack()
p4.pack()
p5.pack()
p6.pack()
p7.pack()
p8.pack()
button1 = Button(root, text="CLOSE", command=closeWindow)
button2 = Button(root, text="Next Sample", command=nextSample)
button3 = Button(root, text="reaction", command=reaction)
button1.pack()
button2.pack()
button3.pack()
print(px1)
print(px2)
print(px3)
print(px4)
print(px5)
print(px6)
print(px7)
print(px8)
cv2.imshow('image',im)
plt.show()
root.mainloop()
cv2.waitKey(0)
cap.release()
#out.release()
cv2.destroyAllWindows()

Related

Problem with askopenfilename() sending to converting function and saving file using asksavefile() - Python Tkinter

I wrote a CAD coordinate conversion application that reads a .txt file using filedialok.askopenfilename() using the function read_file_click().
After selecting the appropriate scale in the Combobox, the program converts the file using the convert() function, then saves it to a .txt file after calling the function save_file_click().
The problem is that when I send the returned value from the convert function to the save_file_click() function, I get two notifications about opening the file.
I don't know how to correct this error. I tried using global variables, but it doesn't help, and weak errors appears with the data_list_no_head variable. Thanks for help:)
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
root = Tk()
root.title("Autocad Coordinate Converter")
root.geometry("")
root.geometry("280x320")
root.resizable(False, False)
def combo_sets():
scale_combo.set("")
def ending_message():
messagebox.showinfo("Autocad Coordinate Converter", "End")
def read_file_click():
global data_list_no_head
file_path = filedialog.askopenfilename()
return file_path
def convert():
file_path_new = read_file_click()
data_list = []
with open(file_path_new, encoding='utf-16') as file:
for line in file:
data_list.append(line.split())
data_list_no_head = data_list[4:]
return data_list_no_head
def save_file_click():
new = convert()
scale_get = scale_combo.get()
data = None
event_eng = None
cal = None
x_coordinate = None
y_coordinate = None
output_file = open(output_file_path_name, 'a')
if scale_get == "1:500" or scale_get == "1:1000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = int(event_eng[-1])*2-2
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:2000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 2*(int(event_eng[-1])*2-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:5000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 5*(int(event_eng[-1])*2-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:10000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 20*(int(event_eng[-1])-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
# Frame1
frame1 = LabelFrame(root, padx=15, pady=15, relief=FLAT)
frame1.grid(row=1, column=0)
button_1 = Button(frame1, text="Read .txt file", padx=15, pady=15, width=20, height=1, command=read_file_click)
button_1.grid(row=1, column=0, padx=3, pady=3)
# Frame2
frame2 = LabelFrame(root, padx=15, pady=15, relief=FLAT)
frame2.grid(row=2, column=0)
Label(frame2, text="Select scale:", width=14).grid(row=1, column=1, padx=1, pady=1)
scale_combo = ttk.Combobox(frame2, values=["1:500", "1:1000", "1:2000", "1:5000", "1:10000"], width=9, state='readonly')
scale_combo.current()
scale_combo.grid(row=2, column=1, padx=1, pady=1)
# Frame3
frame3 = LabelFrame(root, padx=50, pady=50, relief=FLAT)
frame3.grid(row=3, column=0)
button_2 = Button(frame3, text="Save file in CAD format", padx=15, pady=15, width=20, height=1,
command=save_file_click)
button_2.grid(row=0, column=0, padx=3, pady=3)
root.mainloop()

why the recording file is empty in python

I am trying to record my desktop screen and record the audio from microphone simentensously with the help of this python script.
Now when i run only the screen capture part the code works perfectly fine but when i try to run both sound recording and screen capture combine code as shown in below code. my video and audio both file does not open. (0 bytes) or very less size file.
How can i solve this problem.
updated Code
now i am able to record voice properly but the video file is not opening?
import datetime
import tkinter as tk
from tkinter import *
from tkinter import ttk ,FLAT
from PIL import Image, ImageTk, ImageGrab
import cv2
import numpy as np
import threading
import win32api
import pyaudio
import wave
VIDEO_SIZE = (800 , 420) #(960, 540)
p = ImageGrab.grab()
a, b = p.size
chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
fs = 44100
frames = []
g = pyaudio.PyAudio()
date = datetime.datetime.now()
filename='rec_%s-%s-%s-%s-%s-%s.mp4' % (date.year, date.month, date.day,date.hour, date.minute, date.second)
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
frame_rate = 24
cap = cv2.VideoCapture(0)
out = cv2.VideoWriter()
def screen_capturing():
global capturing
capturing = True
while capturing:
img = ImageGrab.grab()
frame = np.array(img)
sc = np.array(img)
_xs,_ys = win32api.GetCursorPos()
cv2.circle(frame,(_xs,_ys),20,(255,255,0), 2)
sc = cv2.resize(sc, VIDEO_SIZE)
tkimage.paste(Image.fromarray(sc))
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
out.write(frame)
def start_screen_capturing():
if not out.isOpened():
out.open(filename, 0x31637661, frame_rate,(VIDEO_SIZE))
t1=threading.Thread(target=screen_capturing, daemon=True)
t1.start()
def stop_screen_capturing():
global capturing
capturing = False
out.release()
def voice_recording():
global recording
while recording:
data = stream.read(chunk)
frames.append(data)
def start_voice_recording():
global stream
stream = g.open(format=sample_format,channels=channels,rate=fs,frames_per_buffer=chunk,input=True)
global recording
recording = True
print('capturing')
t2 = threading.Thread(target=voice_recording) # daemon=True
t2.start()
def stop_voice_recording():
#global recording
recording =False
print(' complete')
filename='test'
filename = filename+".wav"
wf = wave.open(filename,'wb')
wf.setnchannels(channels)
wf.setsampwidth(g.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()
root = tk.Tk()
root.title('Screen Recorder')
root.geometry('+260+70')
tkimage = ImageTk.PhotoImage(Image.new('RGB', VIDEO_SIZE, (0,0,0)))
w, h = VIDEO_SIZE
vbox = tk.Label(root, image=tkimage, width=w, height=h, bg='black')
vbox.pack(pady=10,padx=25)
frame = tk.Frame(root)
frame.pack()
start_cap = tk.Button(frame, text='Start screen Recording', width=30, command=start_screen_capturing)
start_cap.grid(row=0, column=0)
stop_cap = tk.Button(frame, text='Stop screen Recording', width=30, command=stop_screen_capturing)
stop_cap.grid(row=0, column=1)
start_voice = tk.Button(frame, text='Start voice Recording', width=30, command=start_voice_recording)
start_voice.grid(row=0, column=2)
stop_voice = tk.Button(frame, text='Stop voice Recording', width=30, command=stop_voice_recording)
stop_voice.grid(row=0, column=3)
root.mainloop()

Skip files on button click [tkinter + Python 3.5]

Suppose I have 'n' image files in a directory filedir which I want to view via tkinter console. Now, I want to skip a few files whenever necessary, using a button click event which invokes a function nextFile().
E.g.
import os
def nextFile():
global img
img_2 = process(img)
return img_2
window = tk.Tk()
window.title("File Viewer")
files = os.listdir(filedir)
button1 = tk.Button(window, text="Browse Files...", fg="black", command=askopenfilename)
button2 = tk.Button(window, text="SELECT", width=50, command=nextFile)
canvas = tk.Canvas(window, width=width, height=height)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.BOTTOM)
canvas.pack()
for f in files:
img = cv2.cvtColor(cv2.imread(filedir + '/' + f), cv2.COLOR_BGR2RGB)
photo = ImageTk.PhotoImage(image=Image.fromarray((img))
canvas.create_image(0, 0, image=photo, anchor=tk.CENTER)
window.mainloop()
Any help is appreciated. Thanks!
Here is a simple example using PIL to load the inital image and then use a button and function to load each next image.
import tkinter as tk
from PIL import ImageTk, Image
import os
path = 'C:/your/file/path/here'
def nextFile():
# the global is needed to keep track of current index and also keep
# a reference of the image being displayed so its is not garbage collected.
global current_ndex, image
current_ndex += 1
if current_ndex < len(files):
img = Image.open('{}/{}'.format(path, files[current_ndex]))
image = ImageTk.PhotoImage(img)
# clear the canvas before adding the new image.
canvas.delete("all")
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)
current_ndex = 0
button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()
first_image = files[0]
img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()

Tkinter - Canvas in new window and the image resize to the new window resolution

I'm trying to do a Canvas that display a picture in a new window with a pressing a button, actually that is working, but I need the display that show the image in the new windows resize to the new window dimension.
I already tried to manage to get the size to an specific but nothing really worked out for me.
Here is the code:
from tkinter import *
import requests
import shutil
from xml.dom.minidom import parse
import fileinput
import os.path as path
import os
import tempfile
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
root = Tk()
root.title("Etiquetas")
root.configure(width=1280,height=720)
root.geometry('{}x{}'.format(427, 600))
root.resizable(width=False, height=False)
canvas = Canvas(root, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
def new_winF(): # new window definition
newwin = Toplevel(root)
display = Label(newwin, text="Humm, see a new window !")
display.pack()
def retrieve_input():
f = open('DataXML.xml', 'w+')
f.truncate(0)
inputParamString = ParamString.get("1.0","end-1c")
inputAlto = Alto.get("1.0","end-1c")
inputAncho = Ancho.get("1.0","end-1c")
inputTemplateLabel = TemplateLabel.get("1.0","end-1c")
#StringEtiqueta = open("DataXML.xml", "a+")
f.write(inputParamString)
f.close()
doc = parse("DataXML.xml")
my_node_list = doc.getElementsByTagName("label_param")
LabelResultado = open("Template.txt", "w")
LabelResultado.write(inputTemplateLabel)
LabelResultado.close()
for node in my_node_list:
name_node = node.getElementsByTagName("name")
value_node = node.getElementsByTagName("value")
y = ("[" + name_node[0].firstChild.data + "]")
z = y.upper()
print(z)
if (value_node[0].firstChild != None):
print(value_node[0].firstChild.data)
x = value_node[0].firstChild.data
else:
print("")
x = ""
with fileinput.FileInput("Template.txt", inplace=True) as file:
for line in file:
print(line.replace(z, x), end='')
w = open('Template.txt.bak', 'w+')
w.close()
codigoZPL = open("Template.txt", "r")
zpl = codigoZPL.read()
codigoZPL.close()
url = ('http://api.labelary.com/v1/printers/8dpmm/labels/'+inputAlto+'x'+inputAncho+'/0/')
files = {'file': zpl}
#headers = {'Accept': 'application/pdf'}
response = requests.post(url, headers=0, files=files, stream=True)
if response.status_code == 200:
response.raw.decode_content = True
with open('label.png', 'wb') as out_file: # change file name for PNG images
shutil.copyfileobj(response.raw, out_file)
else:
print('Error: ' + response.text)
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
root.mainloop()
def click_limpiar():
Alto.delete(0.0, END)
Ancho.delete(0.0, END)
ParamString.delete(0.0, END)
TemplateLabel.delete(0.0, END)
def close_window():
root.destroy()
exit()
#Crear un label
Label (text="Ingresar ParamString: ") .place(x=10,y=15)
Label (text="Ingresar TamaƱo (pulgadas): ") .place(x=10,y=160)
Label (text="Ingresar TemplateLabel: ") .place(x=10,y=218)
#Crear un textbox
ParamString = Text(root)
ParamString.pack()
ParamString.place(x=12, y=50, height=100, width=400)
Alto = Text(root)
Alto.pack()
Alto.place(x=12, y=190, height=20, width=20)
Ancho = Text(root)
Ancho.pack()
Ancho.place(x=52, y=190, height=20, width=20)
TemplateLabel = Text(root)
TemplateLabel.pack
TemplateLabel.place(x=12, y=250, height=300, width=400)
#Botones
Button(root, text="Aceptar", width=16, command=retrieve_input) .place(x=20,y=560)
Button(root, text="Limpiar", width=16, command=click_limpiar) .place(x=150,y=560)
Button(root, text="Salir", width=16, command=close_window) .place(x=280,y=560)
app = Window(root)
root.mainloop()
The Canvas part is this one:
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
Thanks in advance,

AttributeError User Questions object has no attribute

I have this section of code that is not working properly. Was wondering whether anyone could understand what is wrong with it?
import os
from tkinter import *
import time
import sys
root = Tk()
root.attributes("-fullscreen", True)
class User_Questions:
def __init__(self, master):
self.master = master
master.title("MIT")
global frame
frame = Frame(master)
frame.pack()
self.choosen_questions = []
self.choosen_answers = []
self.choosen_questions_file = open(os.path.expanduser("~/Desktop/Bradfield/Project/" + str(test_choice) + "/Questions.txt"))
self.choosen_answers_file = open(os.path.expanduser("~/Desktop/Bradfield/Project/" + str(test_choice) + "/Answers.txt"))
for line in self.choosen_questions_file:
self.new_question = line.replace("\n","")
self.choosen_questions.append(self.new_question)
for line in self.choosen_answers_file:
self.new_answer = line.replace("\n","")
self.choosen_answers.append(self.new_answer)
self.correct_answers = 0
self.question_label = Label(frame, text = self.choosen_questions[0].replace("1. ",""), font = "Helvetica", fg = "blue")
self.question_label.pack()
self.answer_entry = Entry(frame, text = "", font = "Helvetica")
self.answer_entry.pack()
self.answer_entry.bind('<Return>', self.question)
self.check_test_exists_button = Button(frame, text="SUBMIT", font = "Helvetica", command=self.question)
self.check_test_exists_button.pack()
self.back_button = Button(frame, text="GO BACK", font = "Helvetica", command=self.go_back)
self.back_button.pack()
self.quit_button = Button(frame, text="QUIT", font = "Helvetica", command=master.destroy)
self.quit_button.pack()
def question(self, event):
for i in range(1, len(self.choosen_questions)):
return(self.choosen_questions[i+1].replace(i+". ",""))
def go_back(self):
frame.destroy()
my_gui = User_Choose_Test(root)
This is the error that outputs:
AttributeError: 'User_Questions' object has no attribute 'question'
The indentation of question and go_back is incorrect. It needs to be un-indented one level.

Resources