I am working on an app that basically turns the raspberry pi 4 into a camera, since I've been learning opencv i thought it would be a cool way to show off everything that I've done so far,
I do manage to retrieve the feed of the raspicam, but it's on the top layer so it covers up everything, including my cursor and i can't even stop the app.
I retrieve the image with this code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# camera_pi.py
#
#
#
import time
import io
import threading
import picamera
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
last_access = 0 # time of last client access to the camera
def initialize(self):
if Camera.thread is None:
# start background frame thread
Camera.thread = threading.Thread(target=self._thread)
Camera.thread.start()
# wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
Camera.last_access = time.time()
self.initialize()
return self.frame
#classmethod
def _thread(cls):
with picamera.PiCamera() as camera:
# camera setup
camera.resolution = (1920, 1080)
camera.hflip = True
camera.vflip = True
#camera.zoom = (0.22,0,0.7,0.7) # (x, y, w, h)
# let camera warm up
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
# store frame
stream.seek(0)
cls.frame = stream.read()
# reset stream for next frame
stream.seek(0)
stream.truncate()
# if there hasn't been any clients asking for frames in
# the last 10 seconds stop the thread
#if time.time() - cls.last_access > 10:
#break
cls.thread = None
And then make it into a full screen Tkinter widget with this code:
import cv2
from camera_pi import *
import sys, os
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
camera = Camera()
feed = camera.get_frame()
frame = cv2.imread(feed)
#cv2.imshow(frame)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
SetButton = Button(root,text="Settings", command=root.destroy)
SetButton.place(x=0,y=0)
def showPIL(pilImage):
imgWidth, imgHeight = pilImage.size
# resize photo to full screen
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(w/2,h/2,image=image)
imagesprite.lower()
root.update_idletasks()
root.update()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
try:
showPIL(frame)
except KeyboardInterrupt:
root.destroy
I'd like to add a button on the corner to open up a settings window where i could modify the camera parameters, or start one of the opencv modes ive been working on but being that i can't see the cursor that doesn't work, i also tried to use the canvas function to lower, and tried moving it around in the code but i think its because the image keeps refreshing, or i simply did it wrong.
Related
I am trying to write a Tkinter application that will also process QR codes. For that to work, I need to have a loop checking if the QR code is valid and I need to make a post request. I'm fully aware that the way I have coded this is highly inefficient. Is there a better way to do this? Here is what I have so far:
import cv2
import tkinter as tk
from PIL import Image, ImageTk
import sys
import os
import pyzbar.pyzbar as zbar
import threading
import requests
import queue
result = []
decodedCode = ""
logo = "logo.png"
settings = "settings.png"
if os.environ.get('DISPLAY','') == '':
print('no display found. Using :0.0')
os.environ.__setitem__('DISPLAY', ':0.0')
#create main window
master = tk.Tk()
master.title("tester")
master.geometry("480x800")
master.configure(bg='white')
ttelogo = tk.PhotoImage(file = logo)
settingslogo = tk.PhotoImage(file = settings)
#settings button
settings_frame = tk.Frame(master,width=50,height=50,bg="white")
settings_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
settingsBtn = tk.Button(settings_frame, image=settingslogo).pack()
settings_frame.place(x=430,y=0)
#logo
img = tk.Label(master, image=ttelogo, bg='white')
img.image = ttelogo
img.place(x=176.5,y=10)
#Name Label
label_frame = tk.Frame(master,width=400,height=100,bg="white")
label_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
tk.Label(label_frame,bg="white",fg="black",text="John Smith Smithington III",font=("Calibri",22)).pack()
label_frame.place(x=40,y=140)
#Instructions Label
instructions_frame = tk.Frame(master,width=440,height=100,bg="white")
instructions_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
tk.Label(instructions_frame,bg="white",fg="black",text="Place your pass under the scanner below.",font=("Calibri",10)).pack()
instructions_frame.place(x=20,y=210)
#Camera Window
cameraFrame = tk.Frame(master, width=440, height=480)
cameraFrame.place(x=20, y=260)
#Camera Feed
lmain = tk.Label(cameraFrame)
lmain.place(x=0, y=0)
cap = cv2.VideoCapture(0)
def startScanning():
global cap
_, frame = cap.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, startScanning)
def processScan():
global decodedCode
stopped = False
delay = 1
while(True):
ret = cv2.waitKey(delay) & 0xFF
if ret == ord('c'): # continue
stopped = False
delay = 1
if ret == ord('q'):
break
if stopped or (ret == ord('s')): # stop
stopped = True
delay = 30
continue
# Capture frame-by-frame
ret, frame = cap.read()
decodedObjects = zbar.decode(frame)
if len(decodedObjects) > 0:
stopped = True
for code in decodedObjects:
#print("Data", obj.data)
#API Calls
decodedCode = code.data.decode('utf-8')
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def checkCode():
global decodedCode
while True:
if decodedCode != "":
print (decodedCode)
result = requests.post("https://example.com/login/index.php", data={'action': 'validate_scan', 'uuid': decodedCode}).text
print(result)
decodedCode = ""
startScanning() #Display 2
threading.Thread(name='background', target=processScan).start()
threading.Thread(name='background2', target=checkCode).start()
master.mainloop() #Starts GUI
Edit: New version in queue form:
# import all the necessary modules
from tkinter import *
from multiprocessing import Process, Queue
from queue import Empty # for excepting a specific error
import numpy as np
import cv2
from PIL import Image, ImageTk
import sys
import os
import pyzbar.pyzbar as zbar
import threading
import requests
# this is the function that will be run in a child process
def processScan(queue_): # pass the queue as an argument
stopped = False
delay = 1
while(True):
ret = cv2.waitKey(delay) & 0xFF
if ret == ord('c'): # continue
stopped = False
delay = 1
if ret == ord('q'):
break
if stopped or (ret == ord('s')): # stop
stopped = True
delay = 30
continue
# Capture frame-by-frame
ret, frame = cap.read()
decodedObjects = zbar.decode(frame)
if len(decodedObjects) > 0:
stopped = True
for code in decodedObjects:
#print("Data", obj.data)
#API Calls
queue_.put(code.data.decode('utf-8'))
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
#master.after(2000, processScan)
#return r
# just a function to not write a `lambda`, just easier
# to read code
def startScanning():
global cap
_, frame = cap.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, startScanning)
#processScan()
#threading.Thread(name='background', target=processScan).start()
# set process `daemon = True` so that it gets terminated with the
# main process, this approach is not suggested if you write to file
# but otherwise it shouldn't cause any issues (maybe an error but
# that probably can be handled with `try/except`)
Process(target=processScan, args=(queue, ), daemon=True).start()
# here is the loop for updating the label
# basically get the info from the queue
def update_label():
try:
# try getting data but since it is `block=False`
# if there is nothing in the queue it will not block
# this process waiting for data to appear in the queue
# but it will raise the Empty error
data = queue.get(block=False)
except Empty:
pass
else:
# if no error was raised just config
# label to new data
labelFrame.config(text=data)
finally:
# and simply schedule this function to run again in
# 100 milliseconds (this btw is not recursion)
master.after(100, update_label)
# crucial part is to use this if statement because
# child processes run this whole script again
if __name__ == '__main__':
master = Tk()
logo = "logo.png"
settings = "settings.png"
if os.environ.get('DISPLAY','') == '':
print('no display found. Using :0.0')
os.environ.__setitem__('DISPLAY', ':0.0')
#create main window
master.attributes("-fullscreen", True)
master.title("Title")
master.geometry("480x800")
master.configure(bg='white')
ttelogo = PhotoImage(file = logo)
settingslogo = PhotoImage(file = settings)
#settings button
settings_frame = Frame(master,width=50,height=50,bg="white")
settings_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
settingsBtn = Button(settings_frame, image=settingslogo).pack()
settings_frame.place(x=430,y=0)
#logo
img = Label(master, image=ttelogo, bg='white')
img.image = ttelogo
img.place(x=176.5,y=10)
#Name Label
label_frame = Frame(master,width=400,height=100,bg="white")
label_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
Label(label_frame,bg="white",fg="black",text="John Smith Smithington III",font=("Calibri",22)).pack()
label_frame.place(x=40,y=140)
#Instructions Label
instructions_frame = Frame(master,width=440,height=100,bg="white")
instructions_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
Label(instructions_frame,bg="white",fg="black",text="Place your pass under the scanner below.",font=("Calibri",15)).pack()
instructions_frame.place(x=20,y=210)
#Camera Window
cameraFrame = Frame(master, width=440, height=480)
cameraFrame.place(x=20, y=260)
#Camera Feed
lmain = Label(cameraFrame)
lmain.place(x=0, y=0)
cap = cv2.VideoCapture(0)
# define queue (since it is a global variable now
# it can be easily used in the functions)
queue = Queue()
#label = Label(root)
#label.pack()
# initially start the update function
update_label()
# just a button for starting the process, but you can also simply
# call the function
#Button(root, text='Start', command=start_process).pack()
startScanning()
master.mainloop()
Still running into errors. Also am not sure if this is correct Queue syntax. The Camera feed is not live. Just a static image is showing up at the moment.
This is about as simple as it gets with multiprocessing (explanation in code comments (which is why the code may seem like it has a lot going on when if the comments were removed it would be approx only 40 lines of code for this example)):
# import all the necessary modules
from tkinter import Tk, Label, Button
from multiprocessing import Process, Queue
from queue import Empty # for excepting a specific error
# this is the function that will be run in a child process
def count(queue_): # pass the queue as an argument
# these modules are just to show the functionality
# but time might be necessary otherwise
# if theses are imported in the global namespace
# then you don't need to import them here again
import itertools
import time
for i in itertools.count():
# do the main looping
# put data in the queue
queue_.put(i)
# you may not need to use sleep here depending
# on how long it takes for the
# loop to finish the iteration
# the issue is that the loop may finish
# way faster than the update function runs
# and that will fill up the queue
# I think the queue size can be limited
# but putting sleep like this to allow
# the update loop to update will work too
time.sleep(0.2)
# just a function to not write a `lambda`, just easier
# to read code
def start_process():
# set process `daemon = True` so that it gets terminated with the
# main process, this approach is not suggested if you write to file
# but otherwise it shouldn't cause any issues (maybe an error but
# that probably can be handled with `try/except`)
Process(target=count, args=(queue, ), daemon=True).start()
# here is the loop for updating the label
# basically get the info from the queue
def update_label():
try:
# try getting data but since it is `block=False`
# if there is nothing in the queue it will not block
# this process waiting for data to appear in the queue
# but it will raise the Empty error
data = queue.get(block=False)
except Empty:
pass
else:
# if no error was raised just config
# label to new data
label.config(text=data)
finally:
# and simply schedule this function to run again in
# 100 milliseconds (this btw is not recursion)
root.after(100, update_label)
# crucial part is to use this if statement because
# child processes run this whole script again
if __name__ == '__main__':
root = Tk()
# define queue (since it is a global variable now
# it can be easily used in the functions)
queue = Queue()
label = Label(root)
label.pack()
# initially start the update function
update_label()
# just a button for starting the process, but you can also simply
# call the function
Button(root, text='Start', command=start_process).pack()
root.mainloop()
I am not too familiar with opencv so there might be a chance it won't work in a child process (tho I think I have done that), in that case you will have to either use threading or two alternatives using subprocess: put the opencv part in another file and run that file using python interpreter in the subprocess.Popen (won't work for computers that don't have Python installed) or convert that other python file with the opencv part to an .exe file or sth and run that executable file in the subprocess.Popen (both approaches tho are probably unnecessary and you probably will be fine with either multiprocessing or threading)
To use threading instead change these lines:
# from multiprocessing import Process, Queue
from threading import Thread
from queue import Empty, Queue
and
# Process(target=count, args=(queue, ), daemon=True).start()
Thread(target=count, args=(queue, ), daemon=True).start()
I want to display images from an Allied Vision camera inside a tkinter frame using OpenCV and the SDK for the camera, VimbaPython.
The only possible way to initialize the camera is with a Python with statement:
with Vimba.get_instance() as vimba:
cams = vimba.get_all_cameras()
with cams[0] as camera:
camera.get_frame()
# Convert frame to opencv image, then use Image.fromarray and ImageTk.PhotoImage to
# display it on the tkinter GUI
Everything works fine so far. But I don't only need a single frame. Instead, I need to continuously get frames and display them on the screen so that it is streaming.
I found that one way to do it is to call the .after(delay, function) method from a tkinter Label widget.
So, after obtaining one frame, I want to call the same function to get a new frame and display it again. The code would look like that:
with Vimba.get_instance() as vimba:
cams = vimba.get_all_cameras()
with cams[0] as camera:
def show_frame():
frame = camera.get_frame()
frame = frame.as_opencv_image()
im = Image.fromarray(frame)
img = Image.PhotoImage(im)
lblVideo.configure(image=img) # this is the Tkinter Label Widget
lblVideo.image = img
show_frame()
lblVideo.after(20, show_frame)
Then this shows the first frame and stops, throwing an error saying that Vimba needs to be initialized with a with statement. I don't know much about Python, but it looks like when I call the function with the .after() method it ends the with statement.
I would like to know if it is possible to execute this show_frame() function without ending the with. Also, I can't initialize the camera every time because the program goes really slow.
Thank you
I know this question is pretty old, but I ran into a similar problem with the Allied Vision cameras and found the solution to be relatively robust. So I hope this helps someone, even if not the OP.
An alternative to using with statements is using __enter__ and __exit__ (see sample here). With this, I created a class for the Vimba camera and during the __init__ I used these functions twice: once to initialize the Vimba instance, and once to open the camera itself. An example as follows...
vimba_handle = Vimba.get_instance().__enter__()
camera = vimba_handle.get_all_cameras()[0].__enter__()
I'll include a longer snippet as code as well, but please note my purpose was slightly different the OP's intent. Hopefully, it is still useful.
class VimbaCam:
def __init__(self, device_id=0):
# Variables
self.current_frame = np.array([])
self.device = None
self.device_id = device_id
self.vimba_handle = Vimba.get_instance().__enter__()
self.is_streaming = False
self.scale_window = 4
self.stream_thread = threading.Thread(target=self.thread_stream, daemon=True)
# Default settings
self.auto_exposure = "Off"
self.auto_gain = "Off"
self.acquisition = "Continuous"
self.exposure_us = 200000
self.fps = 6.763
self.gain = 0
self.gamma = 1
self.open()
def close(self):
if self.device is not None:
if self.is_streaming:
self.stop_stream()
time.sleep(1)
self.device.__exit__(None, None, None)
self.vimba_handle.__exit__(None, None, None)
def open(self):
cams = self.vimba_handle.get_all_cameras()
if not cams:
error_check(151, currentframe())
else:
self.device = cams[self.device_id].__enter__()
self.set_defaults()
self.start_stream()
def start_stream(self):
if self.device is not None:
self.is_streaming = True
self.stream_thread.start()
time.sleep(1)
def thread_stream(self):
while self.is_streaming:
current_frame = self.device.get_frame().as_opencv_image()
h, w, _ = current_frame.shape
self.current_frame = current_frame.reshape((h, w))
self.stream_thread = threading.Thread(target=self.thread_stream, daemon=True)
def stop_stream(self):
if self.device is not None:
self.is_streaming = False
def live_video(self):
if self.device is not None:
window_name = "Allied Vision"
h, w = self.current_frame.shape
w = int(w / self.scale_window)
h = int(h / self.scale_window)
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(window_name, w, h)
while 1:
cv2.imshow(window_name, self.current_frame)
cv2.waitKey(1)
if cv2.getWindowProperty(window_name, cv2.WND_PROP_VISIBLE) < 1:
break
cv2.destroyAllWindows()
def set_defaults(self):
if self.device is not None:
# Exposure time settings
self.device.ExposureAuto.set(self.auto_exposure)
self.device.ExposureTimeAbs.set(self.exposure_us)
# Gain settings
self.device.GainAuto.set(self.auto_gain)
self.device.Gain.set(self.gain)
# Gamma settings
self.device.Gamma.set(self.gamma)
self.device.AcquisitionMode.set(self.acquisition)
self.device.AcquisitionFrameRateAbs.set(self.fps)
# Try to adjust GeV packet size (available for GigE only)
try:
self.device.GVSPAdjustPacketSize.run()
while not self.device.GVSPAdjustPacketSize.is_done():
pass
except (AttributeError, VimbaFeatureError):
pass
# Color formatting (tries mono first, then color)
cv_formats = intersect_pixel_formats(self.device.get_pixel_formats(), OPENCV_PIXEL_FORMATS)
mono_formats = intersect_pixel_formats(cv_formats, MONO_PIXEL_FORMATS)
color_formats = intersect_pixel_formats(cv_formats, COLOR_PIXEL_FORMATS)
if mono_formats:
self.device.set_pixel_format(mono_formats[0])
elif color_formats:
self.device.set_pixel_format(color_formats[0])
if __name__ == "__main__":
dev = VimbaCam()
dev.live_video()
dev.close()
You need to use thread to run the capture code and pass the frames read via queue. Then the main tkinter application reads the queue and show the frames periodically using .after().
Below is an example based on your posted code:
import threading
from queue import SimpleQueue
import tkinter as tk
from PIL import Image, ImageTk
from vimba import Vimba
def camera_streaming(queue):
global is_streaming
is_streaming = True
print("streaming started")
with Vimba.get_instance() as vimba:
with vimba.get_all_cameras()[0] as camera:
while is_streaming:
frame = camera.get_frame()
frame = frame.as_opencv_image()
im = Image.fromarray(frame)
img = ImageTk.PhotoImage(im)
queue.put(img) # put the capture image into queue
print("streaming stopped")
def start_streaming():
start_btn["state"] = "disabled" # disable start button to avoid running the threaded task more than once
stop_btn["state"] = "normal" # enable stop button to allow user to stop the threaded task
show_streaming()
threading.Thread(target=camera_streaming, args=(queue,), daemon=True).start()
def stop_streaming():
global is_streaming, after_id
is_streaming = False # terminate the streaming thread
if after_id:
lblVideo.after_cancel(after_id) # cancel the showing task
after_id = None
stop_btn["state"] = "disabled" # disable stop button
start_btn["state"] = "normal" # enable start button
# periodical task to show frames in queue
def show_streaming():
global after_id
if not queue.empty():
image = queue.get()
lblVideo.config(image=image)
lblVideo.image = image
after_id = lblVideo.after(20, show_streaming)
queue = SimpleQueue() # queue for video frames
after_id = None
root = tk.Tk()
lblVideo = tk.Label(root, image=tk.PhotoImage(), width=640, height=480)
lblVideo.grid(row=0, column=0, columnspan=2)
start_btn = tk.Button(root, text="Start", width=10, command=start_streaming)
start_btn.grid(row=1, column=0)
stop_btn = tk.Button(root, text="Stop", width=10, command=stop_streaming, state="disabled")
stop_btn.grid(row=1, column=1)
root.mainloop()
Note that I don't have the camera and the SDK installed, the above code may not work for you. I just demonstrate how to use thread, queue and .after().
Below is a testing vimba module (saved as vimba.py) I use to simulate VimbaPython module using OpenCV and a webcam:
import cv2
class Frame:
def __init__(self, frame):
self.frame = frame
def as_opencv_image(self):
return self.frame
class Camera:
def __init__(self, cam_id=0):
self.cap = cv2.VideoCapture(cam_id, cv2.CAP_DSHOW)
def __enter__(self):
return self
def __exit__(self, *args):
self.cap.release()
return self
def get_frame(self):
ret, frame = self.cap.read()
if ret:
return Frame(frame)
class Vimba:
_instance = None
#classmethod
def get_instance(self):
if self._instance is None:
self._instance = Vimba()
return self._instance
def __enter__(self):
return self
def __exit__(self, *args):
return self
def get_all_cameras(self):
return (Camera(),)
I tried to read the frames in openCV and display them in tkinter label. I was able to do so using the below code:
import tkinter as tk
import cv2
from PIL import ImageTk, Image
video_path = "SAMPLE/STORED_VIDEO/PATH"
root = tk.Tk()
base_img = Image.open("PATH/TO/DEFAULT/LABLE/IMAGE")
img_obj = ImageTk.PhotoImage(base_img)
lblVideo = tk.Label(root, image=img_obj)
lblVideo.pack()
cap = cv2.VideoCapture(video_path)
if cap.isOpened():
def show_frame():
_, frame = cap.read()
im = Image.fromarray(frame)
img = ImageTk.PhotoImage(im)
lblVideo.configure(image=img)
lblVideo.image = img
lblVideo.after(1, show_frame) # Need to create callback here
show_frame()
root.mainloop()
Although this doesnot contain the with statement, you can try replacing the after() callback inside the show_frame function itself.
I am having problem that how to display a video preview window inside the tkinter window. Below code will play video but i want to show that video in the tkinter window..
Python Code:
from moviepy.editor import *
from moviepy.video.fx.resize import resize
import pygame
pygame.display.set_caption('Kumawat!')
clip=VideoFileClip('mk.mp4')
w=1300
h=700
display=(w,h)
clip.resize(display).preview()
pygame.quit()
After some researching it does not seem you can embed the clip easily into a tkinter frame. The solution I came up with is:
use imageio to download the video
extract each video frame using an iterator into an image
convert the image to a ImageTk
add this image to a tkinter label
In below example I have added two control buttons to start and stop the video as well as an waiting loop to run the video at real time assuming 24 frames per second. I have not investigated how to include sound.
import time
import tkinter as tk
import imageio
from PIL import Image, ImageTk
global pause_video
# download video at: http://www.html5videoplayer.net/videos/toystory.mp4
video_name = "toystory.mp4"
video = imageio.get_reader(video_name)
def video_frame_generator():
def current_time():
return time.time()
start_time = current_time()
_time = 0
for frame, image in enumerate(video.iter_data()):
# turn video array into an image and reduce the size
image = Image.fromarray(image)
image.thumbnail((750, 750), Image.ANTIALIAS)
# make image in a tk Image and put in the label
image = ImageTk.PhotoImage(image)
# introduce a wait loop so movie is real time -- asuming frame rate is 24 fps
# if there is no wait check if time needs to be reset in the event the video was paused
_time += 1 / 24
run_time = current_time() - start_time
while run_time < _time:
run_time = current_time() - start_time
else:
if run_time - _time > 0.1:
start_time = current_time()
_time = 0
yield frame, image
def _stop():
global pause_video
pause_video = True
def _start():
global pause_video
pause_video = False
if __name__ == "__main__":
root = tk.Tk()
root.title('Video in tkinter')
my_label = tk.Label(root)
my_label.pack()
tk.Button(root, text='start', command=_start).pack(side=tk.LEFT)
tk.Button(root, text='stop', command=_stop).pack(side=tk.LEFT)
pause_video = False
movie_frame = video_frame_generator()
while True:
if not pause_video:
frame_number, frame = next(movie_frame)
my_label.config(image=frame)
root.update()
root.mainloop()
From picamera.PiCamera() Thread I try to get cls.frameCV2 = snap.array for handling in opencv, and another cls.frame = stream.read() for web streaming. Both work, but very slowly.
What is the problem? If Use only frameCV2 it works quite fast, or if I only Use stream.read, it also ok.
Here is my code snippet:
import time
import io
import threading
import cv2
import picamera
from picamera.array import PiRGBArray
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
frameCV2 = None # same, but as a numpy array
last_access = 0 # time of last client access to the camera
def initialize(self):
if Camera.thread is None:
# start background frame thread
Camera.thread = threading.Thread(target=self._thread)
Camera.thread.start()
# wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
Camera.last_access = time.time()
self.initialize()
return self.frame
def get_frame_for_internal_proc(self): # store frame for cv2 я добавил
Camera.last_access = time.time()
self.initialize()
return self.frameCV2
#classmethod
def _thread(cls):
with picamera.PiCamera() as camera:
# camera setup
camera.resolution = (800, 600)
camera.hflip = True
camera.vflip = True
# let camera warm up
camera.start_preview()
time.sleep(2)
rawCapture = PiRGBArray(camera) # я добавил
stream = io.BytesIO()
for snap in camera.capture_continuous(rawCapture, 'bgr',
use_video_port=True):
cls.frameCV2 = snap.array # frame for cv2
# store frame for web
camera.capture(stream, format='jpeg')
stream.seek(0)
cls.frame = stream.read()
# reset stream for next frame
stream.seek(0)
stream.truncate()
rawCapture.truncate(0)
# if there hasn't been any clients asking for frames in
# the last 10 seconds stop the thread
if time.time() - cls.last_access > 10:
break
cls.thread = None
So, I didn't find the way to make it working faster. The main reason of low speed is doubled capturing inside of camera.capture_continuous circle.
Anyhow I solved the problem using 1 thread for both generation frame and frameCV2, just converting second one to the first. I just put self.frame = cv2.imencode('.jpg', self.frameCV2)[1].tobytes() in get_frame() method which converts numpy matrix to format, fit for web streaming.
Now it works well.
I am trying to simply play a video in gtk environment using opencv code in python. In order to achieve it I made a glade file that contains a toplevel window, a file menu, a drawing area and a file chooser dialog. When user select a file, code starts a thread that calls function VideoPlayerDA that starts reading video and after every frame it generates a queue_draw signal to display frame in drawing area. The problem however is that after few frames the whole UI freezes and becomes unresponsive, video gets stuck.
Tools: I am using Gtk version 3.22.11, python 3.5.3, OpenCV version 3.3.0 on debian stretch.
PS: cv2.waitkey also seems to be not working.
import cv2
import time
import threading
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, Gdk, GdkPixbuf
GObject.threads_init()
mymutex = threading.Lock()
dimg = GdkPixbuf.Pixbuf.new_from_file('test.jpg')
def VideoPlayerDA(filename,drawing_area):
global dimg,dimg_available
cap = cv2.VideoCapture(filename)
while(cap.isOpened()):
mymutex.acquire()
ret, img = cap.read()
if img is not None:
boxAllocation = drawing_area.get_allocation()
img = cv2.resize(img, (boxAllocation.width,\
boxAllocation.height))
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # opencv by default load BGR colorspace. Gtk supports RGB hance the conversion
dimg = GdkPixbuf.Pixbuf.new_from_data(img.tostring(),
GdkPixbuf.Colorspace.RGB,False,8,
img.shape[1],
img.shape[0],
img.shape[2]*img.shape[1],None,None)
#time.sleep(0.03)
drawing_area.queue_draw()
mymutex.release()
time.sleep(0.03)
#if ((cv2.waitKey(30) & 0xFF) == ord('q')):
# break
else:
mymutex.release()
break
print('end of file')
class video_player_gui:
def on_main_window_destroy(self,object):
Gtk.main_quit()
def on_open_activate(self,widget):
response = self.file_chooser.run()
if response == 0:
self.filename = self.file_chooser.get_filename()
thread = threading.Thread(target = VideoPlayerDA, args=(self.filename, self.drawing_area,))
thread.daemon = True
thread.start()
self.file_chooser.hide()
else:
pass
def on_drawing_area_draw(self,widget,cr):
global dimg
Gdk.cairo_set_source_pixbuf(cr, dimg.copy(), 0, 0)
cr.paint()
def __init__(self):
self.gladefile = '/home/nouman/Development/Glade/P2/OpenCv_integration_test.glade'
self.builder = Gtk.Builder()
self.builder.add_from_file(self.gladefile)
self.builder.connect_signals(self)
self.main_window = self.builder.get_object("main_window")
self.file_chooser = self.builder.get_object("file_chooser")
self.drawing_area = self.builder.get_object("drawing_area")
self.main_window.show()
if __name__ == "__main__":
main = video_player_gui()
Gtk.main()
I found a solution for now for anyone who will be getting same problem. I was using a global variable dimg without thread synchronization. Synchronizing threads before use of variable solved the problem. Edit on_drawing_area_draw as following will solve the issue
def on_drawing_area_draw(self,widget,cr):
global dimg
mymutex.acquire()
Gdk.cairo_set_source_pixbuf(cr, dimg.copy(), 0, 0)
cr.paint()
mymutex.release()