Wait for input() to be called second times [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 hours ago.
Improve this question
I'm new to python. I am trying to use a qr scanner to scan qr code as input name to start recording video. And scan the same qr for the second time to end the recording. But I can't find a way to calculate the input() to be called second time. Please help, thank you.
import cv2
cap= cv2.VideoCapture(0)
width= int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height= int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
count = 0
filename = input()
writer= cv2.VideoWriter('/home/zikingyong/Python/mp4/' + filename + '.mp4', cv2.VideoWriter_fourcc(*'DIVX'), 20, (width,height))
while True:
ret,frame= cap.read()
writer.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == 27:
print(x)
break
cap.release()
writer.release()
cv2.destroyAllWindows()

Related

How can I convert a return statement into something that can be used by Tkinter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
This post was edited and submitted for review 7 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am making a GFC (Greatest Common Factor) calculator with GUI, but my current code only works with a return statement, and tkinter doesn't accept return to fill a textbox widget.
Here is a sample of my code
def gproces():
Gnumber1 = Entry.get(GE1)
Gnumber2 = Entry.get(GE2)
Gnumber1 = int(Gnumber1)
Gnumber2 = int(Gnumber2)
if Gnumber1 > Gnumber2:
Gnumber1, Gnumber2 = Gnumber2, Gnumber1
for x in range (Gnumber1, 0, -1):
if Gnumber1 % x == 0 and Gnumber2 % x == 0:
return x
Here is where it's supposed to be used: (To fill GE3)
GE3=Entry(top, bd =5)
GE3.grid(row=3, column=4)
GB=Button(top, text ="Submit", command = gproces).grid(row=4,column=4,)
How do I convert a return statement into something that can be used by Tkinter?
You can just insert the result into the text box inside gprocess():
def gproces():
# better cater invalid input
try:
Gnumber1 = int(GE1.get())
Gnumber2 = int(GE2.get())
x = min(Gnumber1, Gnumber2)
for x in range(x, 0, -1):
if Gnumber1%x == 0 and Gnumber2%x == 0:
break
# insert result into text box
GE3.delete(0, 'end')
GE3.insert('end', x)
except ValueError:
print('Invalid number input')
Note that there is math.gcd() to find the GCF.
Ok so if I understand this correctly you want the result to be displayed in a textbox.
This code should work:
T.delete('1.0', tk.END) # deletes all previous data
T.insert('1.0', str(x)) # inserts new data
Where T is your textbox.
If you want to fill the Textbox in a loop you can simply run T.insert('1.0', str(x)) instead of using return at the end of your function, or you can use both return and T.insert, but don't forget to clear the textbox at the begining of the function with T.delete.

i want to save the responses i get from users through my code so how do i do that [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
this is my code and i need a way to store the input i get from the 'a' variable
print("Hey Welcome To Mental health chatbot")
import time
time.sleep(1)
a = input("So how are you felling today ").strip().upper()
if (a == "NICE") or (a == "GOOD") or (a == "I am good"):
print("That's nice to hear")
if (a == "BAD") or (a == "NOT NICE") or (a == "IT WAS A BAD DAY"):
print("Oh")
The simplest way is to store the value in a file like that :
def storeVar(a) :
f = open("filename.txt", "w+") # w+ allow to write and create the file if it doesnt exist
f.write(a)
f.close() #always close a file as soon as you stop using it
def readVar() :
f = open("filename.txt", "r")
a=f.read()
f.close()
return(a)

Comparing current and previous frame photos - Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I use python to record the writing process (from 0 to the end), and use opencv to convert the writing video into many frames. But when observing the results, I found that sometimes 2-3 frames of pictures are equal. I want to keep only the first picture that is equal when writing the file, and add the timeline. Can any experts give me some advice? The following is my code:
#cv2
import numpy as np
import cv2
from PIL import Image
def get_images_from_video(video_name, time_F):
video_images = []
vc = cv2.VideoCapture(video_name)
c = 1
#判斷是否開啟影片
if vc.isOpened():
rval, video_frame = vc.read()
else:
rval = False
#擷取視頻至結束
while rval:
rval, video_frame = vc.read()
#每隔幾幀進行擷取
if(c % time_F == 0):
video_images.append(video_frame)
c = c + 1
vc.release()
return video_images
#time_F越小,取樣張數越多
time_F = 24
#影片名稱
video_name = 'writingvideo2/11_0330吳恒基.mp4'
#numpy
#讀取影片並轉成圖片
video_images = get_images_from_video(video_name, time_F)
crop_img=[]
#顯示出所有擷取之圖片
for i in range(0,len(video_images)):
#i_str=str(i)
#cv2.imshow('windows',video_images[i])
x=50
y=150
w=1800
h=650
crop_img.append(video_images[i][y:y+h,x:x+w])
cv2.imshow("cropped", crop_img[i])
#correct write path
i_str=str(i)
filename='output2/image/11/'+i_str+'.png'
cv2.imwrite(filename, crop_img[i], [cv2.IMWRITE_JPEG_QUALITY, 90])
cv2.waitKey(100)
cv2.destroyAllWindows
So I want is, if they are equal, keep the previous frame and discard the current photo
You need to employ some kind of a metric which calculates the similarity between two consecutive frames. This is well studied problem and you can gain a lot of insight by reading this question.
Image comparison - fast algorithm
But be aware that dropping frames from your video will change the speed and thus the length of the video.

terminating a python loop [duplicate]

This question already has answers here:
How to detect ESCape keypress in Python?
(5 answers)
Closed 5 years ago.
I made a program that reads pixels from a camera. I have used a while loop. But I can't close the program from terminal without pressing 'Cltrl + C'. I want to close the program using ESC button ( ASCII 27). I tried the following code, which is not working. Any help would be appreciated
import cv2 as cv
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
redimage = frame[:,:,2]
print(redimage)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
Use:
if k == chr(27):
break
cv.waitKey(1) is working for opencv gui only. You can't capture keyboard events in console with this function.
So, you can change your code to show the frame that you are reading from the camera.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
redimage = frame[:,:,2]
cv2.imshow('frame', frame)
print(redimage)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
You can find in this answer a way to capture keyboard events in console.

Getting specific frames from VideoCapture opencv in python

I have the following code, which continuously fetches all the frames from a video by using VideoCapture library in opencv in python:
import cv2
def frame_capture:
cap = cv2.VideoCapture("video.mp4")
while not cap.isOpened():
cap = cv2.VideoCapture("video.mp4")
cv2.waitKey(1000)
print "Wait for the header"
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
flag, frame = cap.read()
if flag:
# The frame is ready and already captured
cv2.imshow('video', frame)
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
print str(pos_frame)+" frames"
else:
# The next frame is not ready, so we try to read it again
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
print "frame is not ready"
# It is better to wait for a while for the next frame to be ready
cv2.waitKey(1000)
if cv2.waitKey(10) == 27:
break
if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
# If the number of captured frames is equal to the total number of frames,
# we stop
break
But I want to grab a specific frame in a specific timestamp in the video.
How can I achieve this?
You can use set() function of VideoCapture.
You can calculate total frames:
cap = cv2.VideoCapture("video.mp4")
total_frames = cap.get(7)
Here 7 is the prop-Id. You can find more here http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html
After that you can set the frame number, suppose i want to extract 100th frame
cap.set(1, 100)
ret, frame = cap.read()
cv2.imwrite("path_where_to_save_image", frame)
this is my first post so please don't rip into me if I don't follow protocol completely. I just wanted to respond to June Wang just in case she didn't figure out how to set the number of frames to be extracted, or in case anyone else stumbles upon this thread with that question:
The solution is the good ol' for loop:
vid = cv2.VideoCapture(video_path)
for i in range(start_frame, how_many_frames_you_want):
vid.set(1, i)
ret, still = vid.read()
cv2.imwrite(f'{video_path}_frame{i}.jpg', still)

Categories

Resources